bitcoinjs / bitcoinjs-lib

A javascript Bitcoin library for node.js and browsers.
MIT License
5.69k stars 2.11k forks source link

How to send change to special address? #1328

Closed zhongjixiuxing closed 5 years ago

zhongjixiuxing commented 5 years ago

If I send 1 BTC to Alice with a 0.001 BTC fee, and I only have a 2 BTC input, how to send to my special own address 0.999 BTC change?

junderw commented 5 years ago

https://github.com/bitcoinjs/bitcoinjs-lib/blob/74f492b786bae22c391440edf22369d1471b9770/test/integration/transactions.js#L27-L44

addInput the 2 BTC input

then do addOutput 2 times. once for 1 BTC for Alice, and once for 0.999 for your change address.

zhongjixiuxing commented 5 years ago

bitcoinjs-lib/test/integration/transactions.js

Lines 27 to 44 in 74f492b

it('can create a 2-to-2 Transaction', function () { const alice = bitcoin.ECPair.fromWIF('L1Knwj9W3qK3qMKdTvmg3VfzUs3ij2LETTFhxza9LfD5dngnoLG1') const bob = bitcoin.ECPair.fromWIF('KwcN2pT3wnRAurhy7qMczzbkpY5nXMW2ubh696UBc1bcwctTx26z')

const txb = new bitcoin.TransactionBuilder() txb.setVersion(1) txb.addInput('b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c', 6) // Alice's previous transaction output, has 200000 satoshis txb.addInput('7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730', 0) // Bob's previous transaction output, has 300000 satoshis txb.addOutput('1CUNEBjYrCn2y1SdiUMohaKUi4wpP326Lb', 180000) txb.addOutput('1JtK9CQw1syfWj1WtFMWomrYdV3W2tWBF9', 170000) // (in)(200000 + 300000) - (out)(180000 + 170000) = (fee)150000, this is the miner fee

txb.sign(1, bob) // Bob signs his input, which was the second input (1th) txb.sign(0, alice) // Alice signs her input, which was the first input (0th)

// prepare for broadcast to the Bitcoin network, see "can broadcast a Transaction" below assert.strictEqual(txb.build().toHex(), '01000000024c94e48a870b85f41228d33cf25213dfcc8dd796e7211ed6b1f9a014809dbbb5060000006a473044022041450c258ce7cac7da97316bf2ea1ce66d88967c4df94f3e91f4c2a30f5d08cb02203674d516e6bb2b0afd084c3551614bd9cec3c2945231245e891b145f2d6951f0012103e05ce435e462ec503143305feb6c00e06a3ad52fbf939e85c65f3a765bb7baacffffffff3077d9de049574c3af9bc9c09a7c9db80f2d94caaf63988c9166249b955e867d000000006b483045022100aeb5f1332c79c446d3f906e4499b2e678500580a3f90329edf1ba502eec9402e022072c8b863f8c8d6c26f4c691ac9a6610aa4200edc697306648ee844cfbc089d7a012103df7940ee7cddd2f97763f67e1fb13488da3fbdd7f9c68ec5ef0864074745a289ffffffff0220bf0200000000001976a9147dd65592d0ab2fe0d0257d571abf032cd9db93dc88ac10980200000000001976a914c42e7ef92fdb603af844d064faad95db9bcdfd3d88ac00000000') }) addInput the 2 BTC input

then do addOutput 2 times. once for 1 BTC for Alice, and once for 0.999 for your change address.

Got it, thanks your reply.