1 // Package filter builds the BIP158 basic compact block filter of a block.
2 //
3 // The element set is the one BIP158 defines: the scriptPubKey of every output
4 // that is not an OP_RETURN, and the previous output script of every
5 // non-coinbase input. Input scripts come from the block's own transactions
6 // where the spent output is earlier in the same block, and from a lookup for
7 // anything older. That lookup is the caller's, because this package holds no
8 // chain state.
9 //
10 // The Golomb-coded set itself is not reimplemented: it is nostrino's
11 // pkg/filter, which carries the BIP158 test vectors, so there is one
12 // implementation of the wire format in the two repositories.
13 package filter
14 15 import (
16 "bytes"
17 "fmt"
18 19 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
20 gcs "git.smesh.lol/nostrino/pkg/filter"
21 22 "git.smesh.lol/btcd-lite/internal/wire"
23 )
24 25 // ScriptLookup returns the scriptPubKey of an outpoint that is not in the block
26 // being filtered. found is false when the caller does not have it, which for a
27 // correctly synced chain cannot happen above the creation point of the outpoint
28 // and does happen for a block whose inputs are older than what the caller holds.
29 type ScriptLookup func(outpoint wire.OutPoint) (script []byte, found bool)
30 31 // IsUnspendable reports whether a script is an OP_RETURN output, which BIP158
32 // excludes from the element set. Only the first opcode is looked at; an empty
33 // script is treated as unspendable because it can never be committed to as an
34 // output anyone spends.
35 func IsUnspendable(script []byte) bool {
36 return len(script) == 0 || script[0] == 0x6a
37 }
38 39 // Elements returns the distinct, non-empty filter elements of one block.
40 //
41 // It returns an error when a non-coinbase input spends an outpoint the block
42 // does not create and the lookup does not have it, because a filter built
43 // without that script is wrong and wrong in a way that is silent.
44 func Elements(block *wire.Block, lookup ScriptLookup) ([][]byte, error) {
45 // Outputs of this block, by outpoint, so an input spending within the
46 // block does not need the lookup.
47 type outpointKey [36]byte
48 spendable := make(map[outpointKey][]byte, len(block.Txs))
49 key := func(op wire.OutPoint) outpointKey {
50 var k outpointKey
51 copy(k[:32], op.Hash[:])
52 k[32] = byte(op.Index)
53 k[33] = byte(op.Index >> 8)
54 k[34] = byte(op.Index >> 16)
55 k[35] = byte(op.Index >> 24)
56 return k
57 }
58 spentInBlock := make(map[outpointKey]bool, len(block.Txs))
59 60 elems := make([][]byte, 0, len(block.Txs)*2)
61 for i := range block.Txs {
62 tx := &block.Txs[i]
63 for j := range tx.TxOut {
64 script := tx.TxOut[j].PkScript
65 if IsUnspendable(script) {
66 continue
67 }
68 elems = append(elems, script)
69 spendable[key(wire.OutPoint{Hash: tx.TxID(), Index: uint32(j)})] = script
70 }
71 }
72 73 for i := range block.Txs {
74 tx := &block.Txs[i]
75 if i == 0 && tx.IsCoinBase() {
76 continue
77 }
78 for j := range tx.TxIn {
79 op := tx.TxIn[j].PreviousOutPoint
80 k := key(op)
81 spentInBlock[k] = true
82 if script, ok := spendable[k]; ok {
83 elems = append(elems, script)
84 continue
85 }
86 if lookup == nil {
87 return nil, fmt.Errorf("filter: no script for %s and no lookup", op)
88 }
89 script, found := lookup(op)
90 if !found {
91 return nil, fmt.Errorf("filter: the input script for %s is not known", op)
92 }
93 elems = append(elems, script)
94 }
95 }
96 return dedupe(elems), nil
97 }
98 99 // dedupe drops empty and duplicate elements while keeping the first order.
100 func dedupe(elems [][]byte) [][]byte {
101 seen := make(map[string]struct{}, len(elems))
102 out := elems[:0]
103 for _, e := range elems {
104 if len(e) == 0 {
105 continue
106 }
107 if _, ok := seen[string(e)]; ok {
108 continue
109 }
110 seen[string(e)] = struct{}{}
111 out = append(out, e)
112 }
113 return out
114 }
115 116 // Build returns the BIP158 basic filter of one block.
117 func Build(block *wire.Block, lookup ScriptLookup) ([]byte, error) {
118 elems, err := Elements(block, lookup)
119 if err != nil {
120 return nil, err
121 }
122 hash := block.BlockHash()
123 return gcs.Build(elems, hash), nil
124 }
125 126 // Hash is the value a filter header chain commits to: double SHA-256 of the
127 // filter's bytes.
128 func Hash(filter []byte) chainhash.Hash {
129 return chainhash.DoubleHashH(filter)
130 }
131 132 // Fold returns the filter header at one height: double SHA-256 of the filter
133 // hash and the previous filter header, which is BIP157's chain rule with the
134 // genesis header as its first element.
135 func Fold(filterHash, previousHeader chainhash.Hash) chainhash.Hash {
136 buf := make([]byte, 0, 64)
137 buf = append(buf, filterHash[:]...)
138 buf = append(buf, previousHeader[:]...)
139 return chainhash.DoubleHashH(buf)
140 }
141 142 // Match reports whether any of the query scripts is in the filter, keyed by the
143 // block hash in internal byte order.
144 func Match(filter []byte, blockHash chainhash.Hash, scripts [][]byte) (bool, error) {
145 return gcs.Match(filter, blockHash, scripts)
146 }
147 148 // Equal reports whether two filters are byte-identical.
149 func Equal(a, b []byte) bool { return bytes.Equal(a, b) }
150