Skip to content

Commit

Permalink
Merge pull request #12 from ctnguyen/feature/AddInputFromTx
Browse files Browse the repository at this point in the history
add method AddInputFromTx (owned by a specific public key)
  • Loading branch information
jadwahab authored Jan 25, 2021
2 parents 447d6f9 + 603f3c7 commit 2524730
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
24 changes: 24 additions & 0 deletions tx.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package bt

import (
"bytes"
"encoding/binary"
"encoding/hex"
"errors"
Expand Down Expand Up @@ -132,6 +133,29 @@ func (tx *Tx) AddInput(input *Input) {
tx.Inputs = append(tx.Inputs, input)
}

// AddInputFromTx take all outputs from previous transaction
// that match a specific public key, add it as input to this new transaction.
func (tx *Tx) AddInputFromTx(pvsTx *Tx, matchPK []byte) error {
matchPKHASH160 := crypto.Hash160(matchPK)
for i, utxo := range pvsTx.Outputs {
utxoPkHASH160, errPK := utxo.LockingScript.GetPublicKeyHash()
if errPK != nil {
return errPK
}
if !bytes.Equal(utxoPkHASH160, matchPKHASH160) {
continue
}
tx.AddInput(&Input{
PreviousTxID: pvsTx.GetTxID(),
PreviousTxOutIndex: uint32(i),
PreviousTxSatoshis: utxo.Satoshis,
PreviousTxScript: utxo.LockingScript,
SequenceNumber: 0xffffffff,
})
}
return nil
}

// From adds a new input to the transaction from the specified UTXO fields.
func (tx *Tx) From(txID string, vout uint32, prevTxLockingScript string, satoshis uint64) error {
pts, err := bscript.NewFromHexString(prevTxLockingScript)
Expand Down
22 changes: 22 additions & 0 deletions tx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,28 @@ func TestNewTxFromBytes(t *testing.T) {
})
}

func TestAddInputFromTx(t *testing.T) {
pubkey1 := []byte{1, 2, 3} // utxo test owner
pubkey2 := []byte{1, 2, 4}

output1, err1 := bt.NewP2PKHOutputFromPubKeyBytes(pubkey1, uint64(100000))
assert.NoError(t, err1)
output2, err2 := bt.NewP2PKHOutputFromPubKeyBytes(pubkey1, uint64(100000))
assert.NoError(t, err2)
output3, err3 := bt.NewP2PKHOutputFromPubKeyBytes(pubkey2, uint64(5000000))
assert.NoError(t, err3)

prvTx := bt.NewTx()
prvTx.AddOutput(output1)
prvTx.AddOutput(output2)
prvTx.AddOutput(output3)
newTx := bt.NewTx()
err := newTx.AddInputFromTx(prvTx, pubkey1)
assert.NoError(t, err)
assert.Equal(t, newTx.InputCount(), 2) // only 2 utxos has been added
assert.Equal(t, newTx.GetTotalInputSatoshis(), uint64(200000))
}

func TestTx_GetTxID(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 2524730

Please sign in to comment.