Skip to content

Commit

Permalink
backend/transactions: add test for tx serialization
Browse files Browse the repository at this point in the history
Recent btcd updates changed the way hashes are serialized. We proposed a
fix (see btcsuite/btcd#2025) to restore backward
compatibility.

This commit adds a specific test case to ensure that the newer and the
legacy serialization methods work.
  • Loading branch information
Beerosagos committed Apr 29, 2024
1 parent 7f33634 commit f08ac5c
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions backend/coins/btc/transactions/transactions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package transactions_test

import (
"encoding/json"
"os"
"testing"

Expand Down Expand Up @@ -190,6 +191,40 @@ func (s *transactionsSuite) TestUpdateAddressHistorySingleTxReceive() {
require.Equal(s.T(), expectedHeight, transactions[0].Height)
}

// TestTxSerialization checks that Tx marshaling/unmarshaling work with both current and legacy
// chainhash.Hash marshaling methods.
// see https://github.com/btcsuite/btcd/pull/2025
func (s *transactionsSuite) TestTxSerialization() {
// create a new Tx
addresses, err := s.addressChain.EnsureAddresses()
require.NoError(s.T(), err)
address := addresses[0]
expectedAmount := btcutil.Amount(123)
tx1 := newTx(chainhash.HashH(nil), 0, address, expectedAmount)

// marshal transaction with current method
tx1Serialized, err := json.Marshal(tx1)
require.NoError(s.T(), err)
s.log.Print("Tx marshaled: " + string(tx1Serialized))

// marshal prevout hash with legacy method
hashBytes := [32]byte(tx1.TxIn[0].PreviousOutPoint.Hash.CloneBytes())
legacyMarshalledHash, err := json.Marshal(hashBytes)
require.NoError(s.T(), err)
s.log.Printf("legacy hash: %s", legacyMarshalledHash)
var tx2 *wire.MsgTx

// build a serialized tx string which is identical of the previous tx, except for the prevout hash.
tx2serialized := "{\"Version\":1,\"TxIn\":[{\"PreviousOutPoint\":{\"Hash\":" + string(legacyMarshalledHash) + ",\"Index\":0},\"SignatureScript\":null,\"Witness\":null,\"Sequence\":4294967295}],\"TxOut\":[{\"Value\":123,\"PkScript\":\"dqkU+tJNI2oRHKW1g4q4XbLEvaq3w76IrA==\"}],\"LockTime\":0}"
err = json.Unmarshal([]byte(tx2serialized), &tx2)
require.NoError(s.T(), err)
s.log.Print("Tx1 hash: " + tx1.TxIn[0].PreviousOutPoint.Hash.String())
s.log.Print("Tx2 hash: " + tx2.TxIn[0].PreviousOutPoint.Hash.String())

// check prevout hashes
require.Equal(s.T(), tx1.TxIn[0].PreviousOutPoint.Hash.String(), tx2.TxIn[0].PreviousOutPoint.Hash.String())
}

// TestSpendableOutputs checks that the utxo set is correct. Only confirmed (or unconfirmed outputs
// we own) outputs can be spent.
func (s *transactionsSuite) TestSpendableOutputs() {
Expand Down

0 comments on commit f08ac5c

Please sign in to comment.