2

I am creating a raw transaction using the bitcoin testnet, but when I push the raw transaction onto the network it takes all my balance. Am I suppose to send the remaining 'change' back to myself? Here is the code im using to create the raw transaction:

var bitcoin = require('bitcoinjs-lib');

var keyPair = bitcoin.ECPair.fromWIF('cMvPQZiG5mLARSjxbBwMxKwzhTHaxgpTsXB6ymx7SGAeYUqF8HAT', bitcoin.networks.testnet);
var tx = new bitcoin.TransactionBuilder(bitcoin.networks.testnet);

tx.addInput('87502f792d477f0514a92486c875fa1fb631fd68c95ccf458c264155165a95c6', 1);
tx.addOutput('msWccFYm5PPCn6TNPbNEnprA4hydPGadBN', 10000);
tx.sign(0, keyPair);

console.log(tx.build().toHex());

Am I correct in thinking i also have to send myself back my remaining amount? so for example if my original balance was 0.00114 BTC I would do this:

tx.addInput('87502f792d477f0514a92486c875fa1fb631fd68c95ccf458c264155165a95c6', 1);

// senders address
tx.addOutput('ms9ySK54aEC2ykDviet9jo4GZE6GxEZMzf ', 104000);

// receivers address
tx.addOutput('msWccFYm5PPCn6TNPbNEnprA4hydPGadBN', 10000);

Is this the correct way?

brandbei37
  • 501
  • 3
  • 13

1 Answers1

1

Am I correct in thinking i also have to send myself back my remaining amount?

Yes, you are correct. Any funds that are not sent to any specific address can be claimed by the miner as a transaction fee. This is how the transaction fee is created.

Check out the first bitcoin transaction made by Satoshi Nakamoto to Hal Finney in Block 170. Satoshi sent 10BTC to Hal and 40 back to himself. Since it was so early, there was no need for a transaction fee because they were mining the blocks themselves. Today, if you tried to send a transaction with no fee, the nodes would reject it (min. relay fee not met), but even a low fee miners would probably choose not to mine it any time soon (if ever).

block 170

JBaczuk
  • 13,886
  • 10
  • 58
  • 86
  • 1
    This is kind of a bad example as he sent the change back to the same address; it's best practice to generate a new address for receiving the change. This is also what a Bitcoin wallet will do today. – Michael Hampton May 31 '19 at 14:49
  • Yes good point, for privacy you should always use a new address for change. This is typically done using hierarchical deterministic key generation see BIP32 – JBaczuk May 31 '19 at 14:52