forked from gcash/bchd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
txfilter.go
366 lines (314 loc) · 9.6 KB
/
txfilter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package bchrpc
import (
"encoding/hex"
"fmt"
"github.com/cctip/bchd/bchrpc/pb"
"github.com/cctip/bchd/chaincfg"
"github.com/cctip/bchd/chaincfg/chainhash"
"github.com/cctip/bchd/txscript"
"github.com/cctip/bchd/wire"
"github.com/gcash/bchutil"
"github.com/simpleledgerinc/goslp/v1parser"
"golang.org/x/crypto/ripemd160"
)
// txFilter is used to filter transactions based on a clients interest.
// It supports filtering for TX outpoints and all kinds of addresses.
type txFilter struct {
outpoints map[wire.OutPoint]struct{}
pubKeyHashes map[[ripemd160.Size]byte]struct{}
scriptHashes map[[ripemd160.Size]byte]struct{}
compressedPubKeys map[[33]byte]struct{}
uncompressedPubKeys map[[65]byte]struct{}
dataElements map[string]struct{}
fallbacks map[string]struct{}
matchAll bool
matchAllSlp bool
slpTokenIds map[[32]byte]struct{}
}
// newTxFilter creates a new txFilter.
func newTxFilter() *txFilter {
return &txFilter{
outpoints: map[wire.OutPoint]struct{}{},
pubKeyHashes: map[[ripemd160.Size]byte]struct{}{},
scriptHashes: map[[ripemd160.Size]byte]struct{}{},
compressedPubKeys: map[[33]byte]struct{}{},
uncompressedPubKeys: map[[65]byte]struct{}{},
dataElements: map[string]struct{}{},
fallbacks: map[string]struct{}{},
slpTokenIds: map[[32]byte]struct{}{},
}
}
// AddOutpoint adds a new outpoint to the filter.
func (f *txFilter) AddOutpoint(op wire.OutPoint) {
f.outpoints[op] = struct{}{}
}
// RemoveOutpoint removes an outpoint from the filter.
func (f *txFilter) RemoveOutpoint(op wire.OutPoint) {
delete(f.outpoints, op)
}
// AddDataElement adds a new data element to the filter.
func (f *txFilter) AddDataElement(dataElement []byte) {
if len(dataElement) > txscript.MaxScriptElementSize {
return
}
f.dataElements[hex.EncodeToString(dataElement)] = struct{}{}
}
// RemoveDataElement removes a data element from the filter.
func (f *txFilter) RemoveDataElement(dataElement []byte) {
delete(f.dataElements, hex.EncodeToString(dataElement))
}
func (f *txFilter) AddSlpTokenID(tokenID []byte) {
var id [32]byte
copy(id[:], tokenID)
f.slpTokenIds[id] = struct{}{}
}
func (f *txFilter) RemoveSlpTokenID(tokenID []byte) {
var id [32]byte
copy(id[:], tokenID)
delete(f.slpTokenIds, id)
}
// AddAddress adds a new address to the filter.
func (f *txFilter) AddAddress(addr bchutil.Address) {
switch a := addr.(type) {
case *bchutil.AddressPubKeyHash:
f.pubKeyHashes[*a.Hash160()] = struct{}{}
case *bchutil.AddressScriptHash:
f.scriptHashes[*a.Hash160()] = struct{}{}
case *bchutil.AddressPubKey:
pubkeyBytes := a.ScriptAddress()
switch len(pubkeyBytes) {
case 33: // Compressed
var compressedPubkey [33]byte
copy(compressedPubkey[:], pubkeyBytes)
f.compressedPubKeys[compressedPubkey] = struct{}{}
case 65: // Uncompressed
var uncompressedPubkey [65]byte
copy(uncompressedPubkey[:], pubkeyBytes)
f.uncompressedPubKeys[uncompressedPubkey] = struct{}{}
}
default:
// A new address type must have been added. Use encoded
// payment address string as a fallback until a fast path
// is added.
addrStr := addr.EncodeAddress()
log.Infof("Unknown address type: %v", addrStr)
f.fallbacks[addrStr] = struct{}{}
}
}
// RemoveAddress removes an address from the filter.
func (f *txFilter) RemoveAddress(addr bchutil.Address) {
switch a := addr.(type) {
case *bchutil.AddressPubKeyHash:
delete(f.pubKeyHashes, *a.Hash160())
case *bchutil.AddressScriptHash:
delete(f.scriptHashes, *a.Hash160())
case *bchutil.AddressPubKey:
pubkeyBytes := a.ScriptAddress()
switch len(pubkeyBytes) {
case 33: // Compressed
var compressedPubkey [33]byte
copy(compressedPubkey[:], pubkeyBytes)
delete(f.compressedPubKeys, compressedPubkey)
case 65: // Uncompressed
var uncompressedPubkey [65]byte
copy(uncompressedPubkey[:], pubkeyBytes)
delete(f.uncompressedPubKeys, uncompressedPubkey)
}
default:
// A new address type must have been added. Use encoded
// payment address string as a fallback until a fast path
// is added.
addrStr := addr.EncodeAddress()
log.Infof("Unknown address type: %v", addrStr)
delete(f.fallbacks, addrStr)
}
}
// AddRPCFilter adds all filter properties from the pb.TransactionFilter
// to the filter.
func (f *txFilter) AddRPCFilter(rpcFilter *pb.TransactionFilter, params *chaincfg.Params) error {
if rpcFilter == nil {
return nil
}
// Add outpoints.
for _, op := range rpcFilter.GetOutpoints() {
hash, err := chainhash.NewHash(op.GetHash())
if err != nil {
return err
}
f.AddOutpoint(wire.OutPoint{Hash: *hash, Index: op.GetIndex()})
}
// Interpret and add addresses.
for _, addrStr := range rpcFilter.GetAddresses() {
addr, err := bchutil.DecodeAddress(addrStr, params)
if err != nil {
return fmt.Errorf("unable to decode address '%v': %v", addrStr, err)
}
f.AddAddress(addr)
}
// Add data elements
for _, dataElement := range rpcFilter.GetDataElements() {
f.AddDataElement(dataElement)
}
f.matchAll = rpcFilter.AllTransactions
// handle SLP
if !f.matchAll {
f.matchAllSlp = rpcFilter.AllSlpTransactions
if !f.matchAllSlp {
for _, tokenID := range rpcFilter.GetSlpTokenIds() {
f.AddSlpTokenID(tokenID)
}
}
}
return nil
}
// RemoveRPCFilter removes all filter properties from the
// pb.TransactionFilter from the filter.
func (f *txFilter) RemoveRPCFilter(rpcFilter *pb.TransactionFilter, params *chaincfg.Params) error {
if rpcFilter == nil {
return nil
}
// Remove outpoints.
for _, op := range rpcFilter.GetOutpoints() {
hash, err := chainhash.NewHash(op.GetHash())
if err != nil {
return err
}
f.RemoveOutpoint(wire.OutPoint{Hash: *hash, Index: op.GetIndex()})
}
// Interpret and remove addresses.
for _, addrStr := range rpcFilter.GetAddresses() {
addr, err := bchutil.DecodeAddress(addrStr, params)
if err != nil {
return fmt.Errorf("unable to decode address '%v': %v", addrStr, err)
}
f.RemoveAddress(addr)
}
// Remove data elements
for _, dataElement := range rpcFilter.GetDataElements() {
f.RemoveDataElement(dataElement)
}
f.matchAll = rpcFilter.AllTransactions
// handle SLP
for _, tokenID := range rpcFilter.GetSlpTokenIds() {
f.RemoveSlpTokenID(tokenID)
}
return nil
}
// MatchAndUpdate returns whether the transaction matches against the filter.
// When the tx contains any matching outputs, all these outputs are added to the
// filter as outpoints for matching further spends of these outputs.
// All matching outpoints are removed from the filter.
func (f *txFilter) MatchAndUpdate(tx *bchutil.Tx, params *chaincfg.Params) bool {
// We don't return early on a match because we prefer full processing:
// - all matching outputs need to be added to the filter for later matching
// - all matching inputs can be removed from the filter for later efficiency
matched := f.matchAll
if len(tx.MsgTx().TxOut) > 0 {
slpMsg, err := v1parser.ParseSLP(tx.MsgTx().TxOut[0].PkScript)
if err == nil && slpMsg != nil {
if f.matchAllSlp {
matched = true
} else {
var tokenID [32]byte
switch msg := slpMsg.(type) {
case *v1parser.SlpGenesis:
txnHash := tx.Hash().CloneBytes()
var txid []byte
for i := len(txnHash) - 1; i >= 0; i-- {
txid = append(txid, txnHash[i])
}
copy(tokenID[:], txid)
case *v1parser.SlpMint:
copy(tokenID[:], msg.TokenID())
case *v1parser.SlpSend:
copy(tokenID[:], msg.TokenID())
}
_, ok := f.slpTokenIds[tokenID]
if ok {
matched = true
}
}
}
}
for _, txin := range tx.MsgTx().TxIn {
if _, ok := f.outpoints[txin.PreviousOutPoint]; ok {
delete(f.outpoints, txin.PreviousOutPoint)
matched = true
}
}
for txOutIdx, txout := range tx.MsgTx().TxOut {
outputMatch := false
_, addrs, _, _ := txscript.ExtractPkScriptAddrs(txout.PkScript, params)
for _, addr := range addrs {
switch a := addr.(type) {
case *bchutil.AddressPubKeyHash:
if _, ok := f.pubKeyHashes[*a.Hash160()]; !ok {
continue
}
case *bchutil.AddressScriptHash:
if _, ok := f.scriptHashes[*a.Hash160()]; !ok {
continue
}
case *bchutil.AddressPubKey:
found := false
switch sa := a.ScriptAddress(); len(sa) {
case 33: // Compressed
var key [33]byte
copy(key[:], sa)
if _, ok := f.compressedPubKeys[key]; ok {
found = true
}
case 65: // Uncompressed
var key [65]byte
copy(key[:], sa)
if _, ok := f.uncompressedPubKeys[key]; ok {
found = true
}
default:
log.Warnf("Skipping rescanned pubkey of unknown "+
"serialized length %d", len(sa))
continue
}
// If the transaction output pays to the pubkey of
// a rescanned P2PKH address, include it as well.
if !found {
pkh := a.AddressPubKeyHash()
if _, ok := f.pubKeyHashes[*pkh.Hash160()]; !ok {
continue
}
}
default:
// A new address type must have been added. Encode as a
// payment address string and check the fallback map.
addrStr := addr.EncodeAddress()
_, ok := f.fallbacks[addrStr]
if !ok {
continue
}
}
// Matching address.
outputMatch = true
break
}
dataElements, err := txscript.ExtractDataElements(txout.PkScript)
if err == nil && len(dataElements) > 0 {
for _, dataElement := range dataElements {
_, ok := f.dataElements[hex.EncodeToString(dataElement)]
if ok {
outputMatch = true
break
}
}
}
// Matching output should be added to filter.
if outputMatch {
outpoint := wire.OutPoint{
Hash: *tx.Hash(),
Index: uint32(txOutIdx),
}
f.outpoints[outpoint] = struct{}{}
matched = true
}
}
return matched
}