我正在try 使用发送加密库发送比特币.它似乎要求私钥采用十六进制格式,但我的密钥的格式是"L3fKJ..."据我所知是WIF格式的?我想我需要使用ECPair来转换它,但它不起作用.

当前错误是"TypeError:ECPair.FromWIF不是一个函数".如果我使用Send-Crypto创建一个新的私有代码,则余额代码工作得很好.

如果有一种不使用Send-Crypto的更简单的方法,也会try 这样做.

const bitcoin = require('bitcoinjs-lib');
const ECPair = require('ecpair');
const CryptoAccount = require("send-crypto");

/* Load account from private key */
const privateKeyWIF = "L3fKJ...";
const keyPair = ECPair.fromWIF(privateKeyWIF);
const privateKey = keyPair.privateKey;
console.log(privateKey);
const account = new CryptoAccount(privateKey);

async function start() {
    console.log(await account.address("BTC"));

    console.log(await account.getBalance("BTC"));
    console.log(await account.getBalance("BTC", {address:"bc1qe6..."}));

    const balance = await account.getBalance("BTC");
    await account.send("bc1qe6...", balance, "BTC", {
            subtractFee: true,
    });

};
start();

推荐答案

这就是最终起作用的代码. 注意,根据版本的不同,比特币代码看起来需要有所不同,根本不是向后兼容的,该代码正在运行2023年10月的最新版本.

// npm install --save send-crypto
// npm install --save bitcoinjs-lib
// npm install --save ecpair
// npm install --save tiny-secp256k1

const bitcoin = require('bitcoinjs-lib');
const ECPairFactory = require('ecpair');
const ecc = require('tiny-secp256k1');
const CryptoAccount = require("send-crypto");

const network = bitcoin.networks.bitcoin;

// Load your private key (WIF)
const ECPair = ECPairFactory.ECPairFactory(ecc);
const privateKeyWIF = 'L3fK...';
const keyPair = ECPair.fromWIF(privateKeyWIF, network);

/* Load account from private key */
//const privateKey = process.env.PRIVATE_KEY || CryptoAccount.newPrivateKey();
const privateKey = keyPair.privateKey;
console.log(privateKey);
const account = new CryptoAccount(privateKey);

async function start() {
    console.log(await account.address("BTC"));

    console.log(await account.getBalance("BTC"));
    console.log(await account.getBalance("BTC", {address:"bc1q..."}));

    const balance = await account.getBalance("BTC");
    await account.send("bc1q...", balance, "BTC", {
            subtractFee: true,
    });

    /*const txHash = await account
            .send("bc1q...", 0.01, "BTC")
            .on("transactionHash", console.log)
            .on("confirmation", console.log);*/


    console.log(await account.getBalance("BTC"));
    console.log(await account.getBalance("BTC", {address:"bc1q..."}));

};
start();

Node.js相关问答推荐

可以删除一个mongodb catch块

查询嵌套数组中的最后一个元素具有特定值的mongoDB集合中的文档

Jest由于UUID而无法解析测试,即使在Jest中启用ESModule支持后也是如此

编辑Mongoose中的对象嵌套数组

Sequelize-测试使用虚拟场更新模型

如何在Firebase Cloud Function v2计划函数中设置代码中的时区?

如何将Node.js与Nuxt.js一起使用?

Webpack:如何避免导出函数的重命名?

如何从谷歌云中部署的应用程序连接到mongoDB Atlas?

Socket.io 未将用户加入给定房间

NPM如何管理node_modules传递依赖?

是否可以在 NodeJS 代码库中的每个函数之前和之后添加 console.log?

结合后端(Express)和前端(Angular)路由

使用 NPM 三个 mocha+typescript 进行测试

AWS EC2 npm install 突然很慢

如何在 MongoDB collection.find() 上获取回调

使用 Node.js 在内存中缓冲整个文件

如何在 MongoDB 上只收听 localhost

遍历 NodeJS 中的一系列日期

如何调试 Gulp 任务?