var bitcoin = require('bitcoinjs-lib');
var rp = require('request-promise');
var data = Buffer.from('Hello World', 'utf8');
var testnet = bitcoin.networks.testnet;
var privateKey = 'p2pkh';
var SourceAddress = "myaddress";
var url = "https://chain.so/api/v2/get_tx_unspent/BTCTEST/"+SourceAddress;
var DestionationAddress = '2MsHsi4CHXsaNZSq5krnrpP4WShNgtuRa9U';
var options =
{
uri: url,
json: true
};
rp(options).then(function (response) {
var index = response.data.txs.length - 1;
console.log(response.data.txs[index]);
var UtxoId = response.data.txs[index].txid;
var vout = response.data.txs[index].output_no;
var amount = Number(response.data.txs[index].value*100000000);
var fee = 0.0005*100000000;
}).catch(function (err) { console.error(err);});
const RawTransaction = new bitcoin.TransactionBuilder(testnet);
RawTransaction.addInput(UtxoId, vout);
RawTransaction.addOutput(DestionationAddress, parseInt(amount-fee));
scrypt = bitcoin.script.compile([bitcoin.opcodes.OP_RETURN,data]);
RawTransaction.addOutput(scrypt, 0);
var keyPair = bitcoin.ECPair.fromWIF(privateKeyWIF, testnet);
tx.sign(0, keyPair);
const p2wpkh = bitcoin.payments.p2wpkh({
pubkey: keyPair.publicKey,
network: bitcoin.networks.testnet
});
const p2sh = bitcoin.payments.p2sh({
redeem: p2wpkh,
network: bitcoin.networks.testnet
});
RawTransaction.sign(0, keyPair, p2sh.redeem.output, null, parseInt(amount));
var Transaction=RawTransaction.build().toHex();
var Sendingoptions = { method: 'POST', url: 'https://chain.so/api/v2/send_tx/BTCTEST',
body: {tx_hex: Transaction}, json: true};
rp(Sendingoptions).then(function (response) {
var Jresponse = JSON.stringify(response);
console.log("Transaction ID:\n"+Jresponse);
}).catch(function (err) { console.error(err); });
我试图创建一个原始事务,但不知道为什么它显示 UtoxId 未定义的错误。
RawTransaction.addInput(UtxoId, vout);
^
ReferenceError: UtxoId is not defined
at Object.<anonymous> (/home/ubuntu/Documents/blockchain/hello.js:27:25)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
我认为这可能包含更多错误,因为它在 UtoxId 处停止。但我想知道如何解决这个问题并将我的输出作为事务 id、脚本十六进制、值、时间等。