如何使用bitcoinjs签署BlockCypher交易

时间:2019-05-21 09:21:42

标签: javascript blockchain bitcoin blockcypher

我正在尝试使用here中所述的使用bitcoinjs在比特币测试网上签署BlockCypher交易,但我不断收到错误消息:

{"error": "Couldn't deserialize request: invalid character 'x' in literal true (expecting 'r')"}

我到处搜索,找不到关于问题所在的文档。下面是用于尝试签署交易的代码。

var bitcoin = require("bitcoinjs-lib");
var buffer  = require('buffer');
var keys    = new bitcoin.ECPair.fromWIF('cMvPQZiG5mLARSjxbBwMxKwzhTHaxgpTsXB6ymx7SGAeYUqF8HAT', bitcoin.networks.testnet);
const publicKey = keys.publicKey;

console.log(keys.publicKey.toString("hex"));

var newtx = {
  inputs: [{addresses: ['ms9ySK54aEC2ykDviet9jo4GZE6GxEZMzf']}],
  outputs: [{addresses: ['msWccFYm5PPCn6TNPbNEnprA4hydPGadBN'], value: 1000}]
};
// calling the new endpoint, same as above
$.post('https://api.blockcypher.com/v1/btc/test3/txs/new', JSON.stringify(newtx))
  .then(function(tmptx) {
    // signing each of the hex-encoded string required to finalize the transaction
    tmptx.pubkeys = [];
    tmptx.signatures = tmptx.tosign.map(function(tosign, n) {
      tmptx.pubkeys.push(keys.publicKey.toString("hex"));
      return keys.sign(new buffer.Buffer(tosign, "hex")).toString("hex");
    });
    // sending back the transaction with all the signatures to broadcast
    $.post('https://api.blockcypher.com/v1/btc/test3/txs/send', tmptx).then(function(finaltx) {
      console.log(finaltx);
    }).catch(function (response) {
   console.log(response.responseText);
});
  }).catch(function (response) {
   console.log(response.responseText);
});

这行return keys.sign(new buffer.Buffer(tosign, "hex")).toString("hex");似乎是问题所在,但我不确定什么地方出了错。

1 个答案:

答案 0 :(得分:0)

讨论并回答了这个问题hereThis postthis one要特别注意。

据我了解,根据respective one问题,BlockCypher存储库已打开。尽管到目前为止,其状态仍为opened,但当前的BlockCypher JS docs respective API description包含该行的更改版本

return keys.sign(new buffer.Buffer(tosign, "hex")).toString("hex"); 

toDER()之前进行toString()转换,因此现在看起来像这样

return keys.sign(new buffer.Buffer(tosign, "hex")).toDER().toString("hex");