Skip to content

Commit 934349f

Browse files
committed
blockchain: test strict best block loading
1 parent 29cfb6e commit 934349f

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

blockchain/chainio_test.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,12 @@ import (
99
"errors"
1010
"math/big"
1111
"reflect"
12+
"strings"
1213
"testing"
1314

15+
"github.com/btcsuite/btcd/btcutil/v2"
1416
"github.com/btcsuite/btcd/database"
17+
"github.com/btcsuite/btcd/txscript/v2"
1518
"github.com/btcsuite/btcd/wire/v2"
1619
)
1720

@@ -37,6 +40,52 @@ func TestErrNotInMainChain(t *testing.T) {
3740
}
3841
}
3942

43+
// TestInitChainStateRejectsTrailingBestBlockBytes ensures startup rejects a
44+
// stored best block whose bytes contain a valid block plus trailing data.
45+
func TestInitChainStateRejectsTrailingBestBlockBytes(t *testing.T) {
46+
chain, params, teardown := utxoCacheTestChain(
47+
"TestInitChainStateRejectsTrailingBestBlockBytes")
48+
defer teardown()
49+
50+
tip := btcutil.NewBlock(params.GenesisBlock)
51+
tip.SetHeight(0)
52+
53+
block, _, err := newBlock(chain, tip, nil)
54+
if err != nil {
55+
t.Fatalf("failed to build block: %v", err)
56+
}
57+
58+
var serialized bytes.Buffer
59+
err = block.MsgBlock().Serialize(&serialized)
60+
if err != nil {
61+
t.Fatalf("failed to serialize block: %v", err)
62+
}
63+
64+
trailingBytes := append([]byte(nil), serialized.Bytes()...)
65+
trailingBytes = append(trailingBytes, 0x00)
66+
trailingBlock := btcutil.NewBlockFromBlockAndBytes(
67+
block.MsgBlock(), trailingBytes,
68+
)
69+
70+
_, _, err = chain.ProcessBlock(trailingBlock, BFNone)
71+
if err != nil {
72+
t.Fatalf("failed to process block: %v", err)
73+
}
74+
75+
_, err = New(&Config{
76+
DB: chain.db,
77+
ChainParams: params,
78+
TimeSource: NewMedianTime(),
79+
SigCache: txscript.NewSigCache(1000),
80+
})
81+
if err == nil {
82+
t.Fatal("expected trailing best block bytes to fail startup")
83+
}
84+
if !strings.Contains(err.Error(), "trailing bytes") {
85+
t.Fatalf("expected trailing byte error, got: %v", err)
86+
}
87+
}
88+
4089
// TestStxoSerialization ensures serializing and deserializing spent transaction
4190
// output entries works as expected.
4291
func TestStxoSerialization(t *testing.T) {

0 commit comments

Comments
 (0)