1 package gate
2 3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "path/filepath"
8 "strconv"
9 "testing"
10 11 "git.smesh.lol/btcd-lite/internal/chains"
12 "git.smesh.lol/btcd-lite/internal/filler"
13 "git.smesh.lol/btcd-lite/internal/process"
14 "git.smesh.lol/btcd-lite/internal/service"
15 "git.smesh.lol/btcd-lite/internal/staging"
16 "git.smesh.lol/btcd-lite/internal/store"
17 "git.smesh.lol/btcd-lite/internal/utxo"
18 "git.smesh.lol/btcd-lite/internal/utxobuild"
19 "git.smesh.lol/btcd-lite/internal/wire"
20 21 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
22 )
23 24 // TestUTXOSetMatchesTheNode builds a UTXO chain out of the bodies the filler
25 // pulled from a node, and asks the node what it thinks of every outpoint the
26 // build produced.
27 //
28 // This is the plan's phase 6 cross-check in miniature: a checkpoint's answer
29 // against `gettxout` for the same outpoint, at the tip the checkpoint was
30 // built at. Every coinbase output of every mined block is in the set and the
31 // node agrees it is unspent; an outpoint that was never created is in neither.
32 func TestUTXOSetMatchesTheNode(t *testing.T) {
33 r := nodeOn(t)
34 r.createWallet(t)
35 r.mine(t, 30)
36 tip, err := strconv.Atoi(r.must(t, "getblockcount"))
37 if err != nil {
38 t.Fatal(err)
39 }
40 // The chain's own maturity, not a constant: the node is on the parent chain
41 // here, and the fork states a different number.
42 // The largest requirement the chain can impose at this tip, which is what
43 // decides whether the node would call a coinbase at height h immature.
44 maturity := chains.Regtest().Exported.Maturity.RequiredAt(uint32(tip), uint32(tip))
45 dir := t.TempDir()
46 headers, err := store.NewHeaderStore(filepath.Join(dir, "headers"))
47 if err != nil {
48 t.Fatal(err)
49 }
50 defer headers.Close()
51 bodies, err := store.NewBlockStore(filepath.Join(dir, "blocks"))
52 if err != nil {
53 t.Fatal(err)
54 }
55 defer bodies.Close()
56 peer := "127.0.0.1:" + itoa(r.p2p)
57 synced := syncHeaders(t, headers, peer)
58 prof, err := chains.ByName(chains.Parent)
59 if err != nil {
60 t.Fatal(err)
61 }
62 log, err := staging.Open(staging.Dir(dir, "btc"))
63 if err != nil {
64 t.Fatal(err)
65 }
66 defer log.Close()
67 pool, err := filler.NewPool(filler.PoolConfig{
68 Chain: "btc", Profile: prof.Profile, Headers: headers, Bodies: bodies,
69 Staging: log, Peers: []filler.Peer{{Addr: peer}}, Logf: t.Logf,
70 })
71 if err != nil {
72 t.Fatal(err)
73 }
74 pool.Reuse(peer, synced)
75 if err := pool.Run(context.Background()); err != nil {
76 t.Fatalf("fill: %v", err)
77 }
78 _ = pool.Close()
79 if _, err := process.Run(process.Config{
80 Chain: "btc", Staging: log, Bodies: bodies, Headers: headers, Logf: t.Logf,
81 }); err != nil {
82 t.Fatalf("process: %v", err)
83 }
84 85 // A checkpoint every ten blocks over what was filled.
86 utxoDir := filepath.Join(dir, "utxo")
87 res, err := utxobuild.Build(utxobuild.Config{
88 Dir: utxoDir, Interval: 10, From: 0, To: uint32(tip + 1),
89 Blocks: utxobuild.StoreSource{S: bodies, Headers: headers}, Logf: t.Logf,
90 })
91 if err != nil {
92 t.Fatalf("build: %v", err)
93 }
94 t.Logf("checkpoint chain ends at %d with set %s", tip+1, res.Name)
95 96 // Every coinbase outpoint of every block, answered by the checkpoint the
97 // build wrote and by the node's gettxout, and required to agree.
98 src := &service.DiskUTXO{Dirs: []string{utxoDir}}
99 set, at, err := src.Set(uint32(tip + 1))
100 if err != nil {
101 t.Fatalf("set: %v", err)
102 }
103 t.Logf("the set at %d holds %d entries", at, len(set))
104 agreed, missing := 0, 0
105 for h := 0; h <= tip; h++ {
106 hash := r.must(t, "getblockhash", strconv.Itoa(h))
107 blk := r.must(t, "getblock", hash, "2")
108 var decoded struct {
109 Tx []struct {
110 TxID string `json:"txid"`
111 Vout []struct {
112 N uint32 `json:"n"`
113 } `json:"vout"`
114 } `json:"tx"`
115 }
116 if err := json.Unmarshal([]byte(blk), &decoded); err != nil {
117 t.Fatal(err)
118 }
119 txid := decoded.Tx[0].TxID
120 vout := decoded.Tx[0].Vout[0].N
121 inSet := hasOutpoint(set, txid, vout)
122 node := bytes.TrimSpace([]byte(r.must(t, "gettxout", txid, strconv.FormatUint(uint64(vout), 10))))
123 onNode := len(node) > 0 && string(node) != "null"
124 if inSet == onNode {
125 agreed++
126 continue
127 }
128 // A coinbase from the last blocks can be absent on the node at its own
129 // tip only because it is not mature yet; anything else is a disagreement
130 // worth stopping on. The window is the chain's own maturity, not a
131 // constant: maturity is a per-chain rule.
132 if uint32(h)+maturity <= uint32(tip) {
133 t.Fatalf("height %d: %s:%d is in the set=%v, on the node=%v", h, txid, vout, inSet, onNode)
134 }
135 missing++
136 }
137 if agreed < tip+1-int(maturity) {
138 t.Fatalf("%d agreements from %d heights", agreed, tip+1)
139 }
140 t.Logf("%d coinbase outpoints agree with gettxout, %d in the last 100 blocks were not checked", agreed, missing)
141 }
142 143 // hasOutpoint finds a txid:vout in a sorted set.
144 func hasOutpoint(set []utxo.Entry, txid string, vout uint32) bool {
145 h, err := chainhash.NewHashFromStr(txid)
146 if err != nil {
147 return false
148 }
149 _, ok := utxo.Find(set, wire.OutPoint{Hash: *h, Index: vout})
150 return ok
151 }
152