Testnet

如何使用 BitcoinJS(和請求)推送原始交易?

  • February 5, 2018

我正在使用 BitcoinJS 為比特幣交易創建一個遊樂場。我創建了以下 Javascript 文件:

const request = require('request');
const proxiedRequest = request.defaults({proxy: "http://localhost:3128"});
const Btc = require('bitcoinjs-lib');
const TestNet = Btc.networks.testnet;
const apiUrl = 'https://testnet.blockexplorer.com/api/addr/';

let privateKey = <my private key>;
let wallet = new Btc.ECPair.fromWIF(privateKey, TestNet);
let publicKey = wallet.getAddress();
console.log("my public key:", publicKey);

let tx = new Btc.TransactionBuilder(TestNet);

let amountWeHave = 100000000; // 1.0 BTC
let amountToKeep = 90000000; // 0.9 BTC
let transactionFee = 1000; // 0.0001 BTC
let amountToSend = amountWeHave - amountToKeep - transactionFee; // ~0.1 (0.0999)

tx.addInput(<one of my input transactions>, 0);

tx.addOutput(<destination public key>, amountToSend);
tx.addOutput(publicKey, amountToKeep);
tx.sign(0, wallet);

let tx_hex = tx.build().toHex();

proxiedRequest.post({
   headers: {'content-type' : 'multipart/mixed'},
   url:     'https://testnet.blockexplorer.com/api/tx/send',
   body:    tx_hex
}, (error, response, body) => {
   console.log('error', error);
   console.log('body', body);
});

這是我的輸出:

my public key: <my public key>
error null
body TypeError: Cannot read property 'toString' of undefined<br>    at Array.types.str (/home/bitcore/lib/bitcore-node/node_modules/bitcoind-rpc/lib/index.js:260:17)<br>    at RpcClient.<anonymous> (/home/bitcore/lib/bitcore-node/node_modules/bitcoind-rpc/lib/index.js:236:35)<br>    at Bitcoin.sendTransaction (/home/bitcore/lib/bitcore-node/lib/services/bitcoind.js:1791:15)<br>    at Node.self.(anonymous function) [as sendTransaction] (/home/bitcore/lib/bitcore-node/lib/node.js:223:27)<br>    at TxController.send (/home/bitcore/dev/insight-api/lib/transactions.js:290:13)<br>    at Layer.handle [as handle_request] (/home/bitcore/lib/bitcore-node/node_modules/express/lib/router/layer.js:95:5)<br>    at next (/home/bitcore/lib/bitcore-node/node_modules/express/lib/router/route.js:131:13)<br>    at Route.dispatch (/home/bitcore/lib/bitcore-node/node_modules/express/lib/router/route.js:112:3)<br>    at Layer.handle [as handle_request] (/home/bitcore/lib/bitcore-node/node_modules/express/lib/router/layer.js:95:5)<br>    at /home/bitcore/lib/bitcore-node/node_modules/express/lib/router/index.js:277:22

你能告訴我我的程式碼有什麼問題嗎?好像是伺服器問題…

正文必須是字元串。

您可以使用形式而不是正文。

參考: https ://www.npmjs.com/package/request#forms

引用自:https://bitcoin.stackexchange.com/questions/70259