Skip to content

Commit

Permalink
fix up input length check and add test
Browse files Browse the repository at this point in the history
  • Loading branch information
Mark committed May 5, 2021
1 parent 4bb9384 commit 94ffaf8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
2 changes: 1 addition & 1 deletion tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ func (tx *Tx) Change(s *bscript.Script, f []*Fee) error {
// ChangeToOutput will calculate fees and add them to an output at the index specified (0 based).
// If an invalid index is supplied and error is returned.
func (tx *Tx) ChangeToOutput(index uint, f []*Fee) error {
if len(tx.Outputs)-1 > int(index) {
if int(index) > len(tx.Outputs)-1 {
return errors.New("index is greater than number of inputs in transaction")
}
available, hasChange, err := tx.change(tx.Outputs[index].LockingScript, f, false)
Expand Down
22 changes: 21 additions & 1 deletion tx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package bt_test

import (
"encoding/hex"
"errors"
"reflect"
"testing"

Expand Down Expand Up @@ -841,11 +842,30 @@ func TestTx_ChangeToOutput(t *testing.T) {
expOutputTotal: 2353,
expChangeOutput: 853,
err: nil,
}, "index out of range should return error": {
tx: func() *bt.Tx {
tx := bt.NewTx()
assert.NoError(t, tx.From(
"07912972e42095fe58daaf09161c5a5da57be47c2054dc2aaa52b30fefa1940b",
0,
"76a914af2590a45ae401651fdbdf59a76ad43d1862534088ac",
1000))
assert.NoError(t, tx.PayTo("mxAoAyZFXX6LZBWhoam3vjm6xt9NxPQ15f", 500))
return tx
}(),
index: 1,
fees: bt.DefaultFees(),
err: errors.New("index is greater than number of inputs in transaction"),
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
assert.Equal(t, test.err, test.tx.ChangeToOutput(test.index, test.fees))
err := test.tx.ChangeToOutput(test.index, test.fees)
if test.err != nil {
assert.Error(t, err)
assert.Equal(t, test.err, err)
return
}
assert.Equal(t, test.expOutputTotal, test.tx.GetTotalOutputSatoshis())
assert.Equal(t, test.expChangeOutput, test.tx.Outputs[test.index].Satoshis)
})
Expand Down

0 comments on commit 94ffaf8

Please sign in to comment.