send_test.go raw
1 package domain
2
3 import (
4 "errors"
5 "testing"
6
7 "github.com/btcsuite/btcd/btcec/v2"
8 btcecdsa "github.com/btcsuite/btcd/btcec/v2/ecdsa"
9
10 "git.smesh.lol/tinywallet/pkg/tx"
11 )
12
13 // fundedRestored gives a rig whose btc wallet owns one coin of value, at height 150.
14 func fundedRestored(t *testing.T, value uint64) *rig {
15 t.Helper()
16
17 r := newRig(t, "regtest")
18
19 if _, err := r.domain.Restore("btc", phrase, "pass"); err != nil {
20 t.Fatal(err)
21 }
22
23 address, err := r.domain.Addresses("btc", false, 0, 1)
24
25 if err != nil {
26 t.Fatal(err)
27 }
28
29 chain := r.chains["btc"]
30 chain.syncTo = chaindataPosition(200)
31 chain.matched = []uint32{150}
32 chain.blocks = map[uint32][]byte{150: buildBlock(t, address[0].Script(), value)}
33
34 if _, err := r.domain.Sync("btc", 0); err != nil {
35 t.Fatal(err)
36 }
37
38 return r
39 }
40
41 // TestSendBuildsSignsAndBroadcasts: the send is local end to end — coins selected from the
42 // table, the transaction built and signed here, one broadcast, spent coins forgotten and the
43 // change remembered.
44 func TestSendBuildsSignsAndBroadcasts(t *testing.T) {
45 r := fundedRestored(t, 100_000)
46
47 destination, err := r.domain.Addresses("btc", false, 2, 1)
48
49 if err != nil {
50 t.Fatal(err)
51 }
52
53 txid, err := r.domain.Send("btc", destination[0].Text, 50_000, 1_000, SendPolicy{
54 MaxSpend: 100_000,
55 MaxFee: 2_000,
56 })
57
58 if err != nil {
59 t.Fatalf("Send: %v", err)
60 }
61
62 chain := r.chains["btc"]
63
64 if chain.broadcastCalls != 1 {
65 t.Fatalf("broadcast %d times", chain.broadcastCalls)
66 }
67
68 sent, err := tx.Decode(chain.broadcast[0])
69
70 if err != nil {
71 t.Fatalf("decode what was broadcast: %v", err)
72 }
73
74 if got, _ := sent.TxID(); got != txid {
75 t.Fatalf("the returned txid %x is not the transaction's %x", txid, got)
76 }
77
78 if len(sent.Outputs) != 2 {
79 t.Fatalf("%d outputs, want payment and change", len(sent.Outputs))
80 }
81
82 if sent.Outputs[0].Value != 50_000 || string(sent.Outputs[0].Script) != string(destination[0].Script()) {
83 t.Fatalf("the payment is %+v", sent.Outputs[0])
84 }
85
86 var change uint64 = 100_000 - 50_000 - 1_000
87
88 if sent.Outputs[1].Value != change {
89 t.Fatalf("the change is %d, want %d", sent.Outputs[1].Value, change)
90 }
91
92 if len(sent.Inputs) != 1 || len(sent.Inputs[0].Witness) != 2 {
93 t.Fatalf("inputs %d, witness %d", len(sent.Inputs), len(sent.Inputs[0].Witness))
94 }
95
96 // The spent coin is gone and the change is remembered as an unconfirmed coin.
97 coins, err := r.domain.UnspentOn("btc")
98
99 if err != nil {
100 t.Fatal(err)
101 }
102
103 if len(coins) != 1 {
104 t.Fatalf("%d coins after the send", len(coins))
105 }
106
107 if coins[0].Value != change || coins[0].Height != 0 || coins[0].TxID != txid {
108 t.Fatalf("change coin %+v", coins[0])
109 }
110 }
111
112 // TestSendRefusesWhatThePolicyForbids: each refusal is distinct and none of them touches the
113 // chain or the coin table.
114 func TestSendRefusesWhatThePolicyForbids(t *testing.T) {
115 r := fundedRestored(t, 100_000)
116
117 destination, _ := r.domain.Addresses("btc", false, 2, 1)
118 chain := r.chains["btc"]
119
120 if _, err := r.domain.Send("btc", destination[0].Text, 50_000, 1_000, SendPolicy{MaxSpend: 99_999}); !errors.Is(err, ErrSendPolicy) {
121 t.Fatalf("spend over the limit: %v", err)
122 }
123
124 if _, err := r.domain.Send("btc", destination[0].Text, 50_000, 1_000, SendPolicy{MaxFee: 999}); !errors.Is(err, ErrSendPolicy) {
125 t.Fatalf("fee over the limit: %v", err)
126 }
127
128 if _, err := r.domain.Send("btc", destination[0].Text, 200_000, 1_000, SendPolicy{}); !errors.Is(err, ErrNoFunds) {
129 t.Fatalf("funds the wallet does not have: %v", err)
130 }
131
132 if _, err := r.domain.Send("btc", "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4", 50_000, 1_000, SendPolicy{}); err == nil {
133 t.Fatal("an address on another network was accepted")
134 }
135
136 if _, err := r.domain.Send("blake", destination[0].Text, 50_000, 1_000, SendPolicy{}); err == nil {
137 t.Fatal("a chain the wallet does not drive was accepted")
138 }
139
140 if chain.broadcastCalls != 0 {
141 t.Fatalf("a refused send broadcast %d times", chain.broadcastCalls)
142 }
143
144 if coins, _ := r.domain.UnspentOn("btc"); len(coins) != 1 {
145 t.Fatalf("a refused send changed the coin table: %d coins", len(coins))
146 }
147
148 // A broadcast the chain refuses leaves the coins alone too.
149 chain.broadcastErr = errors.New("the peer is gone")
150
151 if _, err := r.domain.Send("btc", destination[0].Text, 50_000, 1_000, SendPolicy{}); err == nil {
152 t.Fatal("a failed broadcast reported success")
153 }
154
155 if coins, _ := r.domain.UnspentOn("btc"); len(coins) != 1 {
156 t.Fatalf("a failed broadcast changed the coin table: %d coins", len(coins))
157 }
158 }
159
160 // TestSendRefusesPreForkCoinsOnLegacyBTC: the Bitcoin wallet has no unified
161 // bit, so a pre-fork coin spent with a legacy signature would be valid on XBT
162 // too. It must stay refused; only the XBT wallet can use a shared coin safely.
163 func TestSendRefusesPreForkCoinsOnLegacyBTC(t *testing.T) {
164 r := newRig(t, "regtest")
165
166 if _, err := r.domain.Restore("btc", phrase, "pass"); err != nil {
167 t.Fatal(err)
168 }
169
170 address, err := r.domain.Addresses("btc", false, 0, 1)
171
172 if err != nil {
173 t.Fatal(err)
174 }
175
176 chain := r.chains["btc"]
177 chain.syncTo = chaindataPosition(60)
178 chain.matched = []uint32{50}
179 chain.blocks = map[uint32][]byte{50: buildBlock(t, address[0].Script(), 100_000)}
180
181 if _, err := r.domain.Sync("btc", 0); err != nil {
182 t.Fatal(err)
183 }
184
185 // Before the rule is applied the coin is visible but not necessarily spendable.
186 if coins, _ := r.domain.UnspentOn("btc"); len(coins) != 1 {
187 t.Fatalf("%d coins", len(coins))
188 }
189
190 link, err := r.domain.link("btc")
191
192 if err != nil {
193 t.Fatal(err)
194 }
195
196 link.Profile.ForkHeight = 100
197
198 r.domain.mu.Lock()
199 r.domain.links["btc"] = link
200 r.domain.mu.Unlock()
201
202 if coins, _ := r.domain.SpendableOn("btc"); len(coins) != 0 {
203 t.Fatalf("%d pre-fork coins are spendable", len(coins))
204 }
205
206 destination, _ := r.domain.Addresses("btc", false, 2, 1)
207
208 if _, err := r.domain.Send("btc", destination[0].Text, 50_000, 1_000, SendPolicy{}); !errors.Is(err, ErrNotNative) {
209 t.Fatalf("a pre-fork coin: %v", err)
210 }
211
212 if chain.broadcastCalls != 0 {
213 t.Fatal("a pre-fork coin was spent")
214 }
215 }
216
217 // TestSendFundsAContract: a swap is funded by paying a P2WSH address, so a 32-byte witness
218 // program is a valid destination and the output carries it.
219 func TestSendFundsAContract(t *testing.T) {
220 r := fundedRestored(t, 100_000)
221
222 addresses, err := r.domain.Addresses("btc", false, 0, 1)
223
224 if err != nil {
225 t.Fatal(err)
226 }
227
228 sum := sha256Of([]byte("rigorous preimage"))
229
230 refundKey, _ := btcec.PrivKeyFromBytes([]byte{31: 0x11})
231
232 contract, witness, _, err := r.domain.DeriveHTLC(
233 "btc", addresses[0].Pubkey, refundKey.PubKey().SerializeCompressed(), sum, 500,
234 )
235
236 if err != nil {
237 t.Fatal(err)
238 }
239
240 if _, err := r.domain.Send("btc", contract, 50_000, 1_000, SendPolicy{}); err != nil {
241 t.Fatalf("Send to a contract: %v", err)
242 }
243
244 sent, err := tx.Decode(r.chains["btc"].broadcast[0])
245
246 if err != nil {
247 t.Fatal(err)
248 }
249
250 digest := sha256Of(witness)
251 want := append([]byte{0x00, 0x20}, digest[:]...)
252
253 if string(sent.Outputs[0].Script) != string(want) {
254 t.Fatalf("the contract output pays %x", sent.Outputs[0].Script)
255 }
256 }
257
258 // TestSendOnXBTUsesTheUnifiedSighash: the XBT wallet's funding spend opts into
259 // SIGHASH_UNIFIED, so the transaction is invalid on a chain that does not
260 // implement the bit. This is the client-side replay protection for a shared
261 // UTXO, not just for a post-fork one.
262 func TestSendOnXBTUsesTheUnifiedSighash(t *testing.T) {
263 r := newRig(t, "regtest")
264
265 if _, err := r.domain.Restore("blake", phrase, "pass"); err != nil {
266 t.Fatal(err)
267 }
268
269 address, err := r.domain.Addresses("blake", false, 0, 1)
270
271 if err != nil {
272 t.Fatal(err)
273 }
274
275 // Deliberately a pre-fork coin: the unified signature, not ancestry, is
276 // what makes this spend XBT-only.
277 chain := r.chains["blake"]
278 chain.syncTo = chaindataPosition(60)
279 chain.matched = []uint32{50}
280 chain.blocks = map[uint32][]byte{50: buildBlock(t, address[0].Script(), 100_000)}
281
282 if _, err := r.domain.Sync("blake", 0); err != nil {
283 t.Fatal(err)
284 }
285
286 link, err := r.domain.link("blake")
287
288 if err != nil {
289 t.Fatal(err)
290 }
291
292 link.Profile.Name = "blake"
293 link.Profile.ForkHeight = 100
294
295 r.domain.mu.Lock()
296 r.domain.links["blake"] = link
297 r.domain.mu.Unlock()
298
299 destination, err := r.domain.Addresses("blake", false, 2, 1)
300
301 if err != nil {
302 t.Fatal(err)
303 }
304
305 if _, err := r.domain.Send("blake", destination[0].Text, 50_000, 1_000, SendPolicy{}); err != nil {
306 t.Fatal(err)
307 }
308
309 sent, err := tx.Decode(chain.broadcast[0])
310
311 if err != nil {
312 t.Fatal(err)
313 }
314
315 if len(sent.Inputs) != 1 || len(sent.Inputs[0].Witness) != 2 {
316 t.Fatalf("witness = %d inputs, %d items", len(sent.Inputs), len(sent.Inputs[0].Witness))
317 }
318
319 item := sent.Inputs[0].Witness[0]
320 if item[len(item)-1] != byte(tx.SighashAllUnified) {
321 t.Fatalf("sighash byte %#x, want %#x", item[len(item)-1], byte(tx.SighashAllUnified))
322 }
323
324 spent := []tx.SpentOutput{{Value: 100_000, Script: address[0].Script()}}
325
326 digest, err := sent.SighashUnifiedV0(
327 0, tx.P2WPKHScriptCode(address[0].Program), spent, tx.SighashAllUnified,
328 )
329
330 if err != nil {
331 t.Fatal(err)
332 }
333
334 signature, err := btcecdsa.ParseDERSignature(item[:len(item)-1])
335 if err != nil {
336 t.Fatal(err)
337 }
338
339 pubkey, err := btcec.ParsePubKey(sent.Inputs[0].Witness[1])
340 if err != nil {
341 t.Fatal(err)
342 }
343
344 if !signature.Verify(digest[:], pubkey) {
345 t.Fatal("the funding signature does not verify over the unified digest")
346 }
347 }
348