Как создать транзакцию bitcoin-testnet - blockcypher? - PullRequest
2 голосов
/ 08 апреля 2019

Я новичок в криптовалютах и ​​блокчейне. Мне нужно отправить testnet-биткойны с одного адреса на другой. Я хочу использовать API-интерфейс blockcypher для создания транзакции:

https://www.blockcypher.com/dev/bitcoin/#creating-transactions

Я создал два новых адреса, используя библиотеки bitcore и buffer, например:

  var rand_buff = bitcore.crypto.Random.getRandomBuffer(32);
  var rand_num = bitcore.crypto.BN.fromBuffer(rand_buff);
  var PrivateKeyWIF = bitcore.PrivateKey("testnet").toWIF();
  var privateKey = bitcore.PrivateKey.fromWIF(PrivateKeyWIF);
  var address = privateKey.toAddress();
  //print("address: " + address + "\nprivate key: " + privateKey);

Я не могу найти ресурс, который помог бы мне узнать больше о транзакциях testnet. Буду признателен, если вы укажете мне на любой ценный ресурс.

Всякий раз, когда я делаю запрос к блок-шифру с действительными адресами (созданные мной) Я получаю ошибку - 400 Bad Request с полученным JSON:

  "errors": [
    {
      "error": "Unable to find a transaction to spend for address mxeHfaF413y6xzB3S1NnGsXzK6ewYxsQ2R."
    },
    {
      "error": "Error building transaction: Invalid output address: wrong network.."
    },
    {
      "error": "Not enough funds after fees in 0 inputs to pay for 0 outputs, missing -6800."
    },
    {
      "error": "Error validating generated transaction: Transaction missing input or output."
    }
  ...
}

Когда я использую адреса, упомянутые в документации Blockcypher, запрос действителен.

Я создал транзакционную функцию на основе кода, приведенного в документации по blockcypher.

function transact() {
//getsourceaddress
  var sourceAddress = document.getElementById("transactionInput").value;
///getdesAddress
  var destinationAddress = document.getElementById("transactionOutput").value;
//get privateKey
  var pk = document.getElementById("pk").value;
//get Transaction Amt
  var transactionAmount = document.getElementById("transactionAmount").value;

//make sure these fields are complete
  if (destinationAddress === "" || pk === "" || transactionAmount === "") {
    print("EMPTY");
    return null;
  } else {
//convert to INT
    var transactionAmountSatoshis = parseInt(transactionAmount, 10);
    //var keys = new bitcoin.ECPair(bitcoin.bigi.fromHex(pk));
    var inaddress = [];
    inaddress.push(sourceAddress);
    var outaddress = [];
    outaddress.push(destinationAddress);
    var newtx = {
      inputs: [{ addresses: inaddress }],
      outputs: [{ addresses: outaddress, value: transactionAmountSatoshis }]
    };
    //print(newtx);
    //request
    $.post(
      "https://api.blockcypher.com/v1/bcy/test/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.getPublicKeyBuffer().toString("hex"));
          return keys
            .sign(new buffer.Buffer(tosign, "hex"))
            .toDER()
            .toString("hex");
        });
        // sending back the transaction with all the signatures to broadcast
        $.post("https://api.blockcypher.com/v1/bcy/test/txs/send", tmptx).then(
          function(finaltx) {
            console.log(finaltx);
          }
        );
      })
      .catch(function(e) {
        window.alert("Failed!");
        console.log(e);
      });
  }

  print(newtx);
}

Ожидается: TXSkeleton Object

Факт: ошибка JSON

...