batch_test.go raw
1 package verify
2
3 import (
4 "context"
5 "errors"
6 "testing"
7
8 "git.smesh.lol/tinywallet/pkg/tx"
9 )
10
11 type batchFake struct {
12 name string
13 raw []byte
14 size int
15 asked [][32]byte
16 }
17
18 func (b *batchFake) Name() string { return b.name }
19
20 func (b *batchFake) Tx(context.Context, [32]byte) (TxFact, error) {
21 return TxFact{}, errors.New("not used: this source is batched")
22 }
23
24 func (b *batchFake) Tip(context.Context) (Tip, error) { return Tip{}, nil }
25
26 func (b *batchFake) FeeEstimate(context.Context) (int64, error) { return 1, nil }
27
28 func (b *batchFake) TxBatch(_ context.Context, txids [][32]byte) (map[[32]byte]TxFact, error) {
29 b.size = len(txids)
30 b.asked = append([][32]byte{}, txids...)
31
32 out := map[[32]byte]TxFact{}
33
34 for _, txid := range txids {
35 if txid == [32]byte{} {
36 continue
37 }
38
39 out[txid] = TxFact{Found: true, Raw: b.raw, Height: 800}
40 }
41
42 return out, nil
43 }
44
45 func TestBatchRunsOneFixedSizeRoundAndAgrees(t *testing.T) {
46 built := buildTx(t, 0, tx.SequenceFinal, tx.Output{Value: 3, Script: []byte{0x51}})
47 raw := rawOf(t, built)
48
49 txid, err := TxidOf(raw)
50
51 if err != nil {
52 t.Fatal(err)
53 }
54
55 one := &batchFake{name: "one", raw: raw}
56 two := &batchFake{name: "two", raw: raw}
57
58 engine, err := NewFacts([]Source{one, two}, 2)
59
60 if err != nil {
61 t.Fatal(err)
62 }
63
64 batch := engine.NewBatch(3)
65 batch.Add(txid)
66 batch.Add(txid) // duplicate, must not be asked twice
67
68 answers, err := batch.Run(context.Background())
69
70 if err != nil {
71 t.Fatal(err)
72 }
73
74 if len(answers) != 1 {
75 t.Fatalf("answers %d, want 1", len(answers))
76 }
77
78 if one.size != 1+3 {
79 t.Fatalf("the source was asked %d lookups, want the txid plus 3 padding", one.size)
80 }
81
82 if len(one.asked) != 1+3 {
83 t.Fatalf("asked %d", len(one.asked))
84 }
85
86 // The padding is the zero txid, which a source must treat as a miss, so the batch cannot
87 // be distinguished by size.
88 if one.asked[1] != ([32]byte{}) {
89 t.Fatal("the padding was not the fixed dummy txid")
90 }
91 }
92
93 func TestBatchFailsWhenOneSourceContradicts(t *testing.T) {
94 built := buildTx(t, 0, tx.SequenceFinal, tx.Output{Value: 3, Script: []byte{0x51}})
95 raw := rawOf(t, built)
96
97 txid, err := TxidOf(raw)
98
99 if err != nil {
100 t.Fatal(err)
101 }
102
103 engine, err := NewFacts([]Source{
104 &batchFake{name: "one", raw: raw},
105 &batchFake{name: "two", raw: rawOf(t, buildTx(t, 0, tx.SequenceFinal, tx.Output{Value: 4, Script: []byte{0x51}}))},
106 }, 2)
107
108 if err != nil {
109 t.Fatal(err)
110 }
111
112 batch := engine.NewBatch(0)
113 batch.Add(txid)
114
115 if _, err := batch.Run(context.Background()); !errors.Is(err, ErrDisagree) {
116 t.Fatalf("err %v, want ErrDisagree", err)
117 }
118 }
119