htlc_test.go raw
1 package psbt
2
3 import (
4 "encoding/hex"
5 "errors"
6 "testing"
7
8 "github.com/btcsuite/btcd/btcec/v2"
9 btcecdsa "github.com/btcsuite/btcd/btcec/v2/ecdsa"
10
11 "git.smesh.lol/tinywallet/pkg/script"
12 "git.smesh.lol/tinywallet/pkg/tx"
13 )
14
15 // contractFixture builds a contract whose claimer is the wallet's own key, and returns the
16 // address, the key, the parsed terms, the witness script and the preimage.
17 func contractFixture(t *testing.T) (walletAddress, claimKey, witnessScript []byte, terms HTLC, preimage []byte) {
18 t.Helper()
19
20 address, key := walletKey(t)
21
22 refundKey, _ := btcec.PrivKeyFromBytes([]byte{31: 0x07})
23 refunder := refundKey.PubKey().SerializeCompressed()
24
25 // The claim branch checks OP_SIZE 32, so the fixture's secret is 32 bytes.
26 preimage = make([]byte, 32)
27 copy(preimage, []byte("the preimage that opens the contract"))
28
29 var secretHash [32]byte
30
31 sum := sha256Of(preimage)
32 copy(secretHash[:], sum)
33
34 witness, err := script.HTLC(address.Pubkey, refunder, secretHash, 400)
35
36 if err != nil {
37 t.Fatalf("HTLC: %v", err)
38 }
39
40 parsed, err := ParseHTLC(witness)
41
42 if err != nil {
43 t.Fatalf("ParseHTLC: %v", err)
44 }
45
46 return address.Pubkey, key.Secret, witness, parsed, preimage
47 }
48
49 // contractPSBT describes a spend of the contract output, with the preimage when it is a claim.
50 func contractPSBT(t *testing.T, witnessScript []byte, secretHash [32]byte, preimage []byte, locktime uint32) []byte {
51 t.Helper()
52
53 transaction := tx.New()
54 transaction.AddInput(tx.Outpoint{Hash: [32]byte{3}, Index: 2}, 0xfffffffe)
55 transaction.AddOutput(60_000, []byte{0x00, 0x14, 5, 5, 5, 5})
56 transaction.LockTime = locktime
57
58 input := SegwitInput{
59 Amount: 70_000,
60 ScriptPubKey: p2wsh(witnessScript),
61 WitnessScript: witnessScript,
62 }
63
64 if preimage != nil {
65 input.Preimage = preimage
66 input.SecretHash = secretHash
67 }
68
69 raw, err := Write(transaction, []SegwitInput{input})
70
71 if err != nil {
72 t.Fatalf("Write: %v", err)
73 }
74
75 return raw
76 }
77
78 // finalWitness finds the final scriptWitness record in a signed PSBT.
79 func finalWitness(t *testing.T, raw []byte) [][]byte {
80 t.Helper()
81
82 for at := 0; at+2 < len(raw); at++ {
83 if raw[at] != 0x01 || raw[at+1] != inputFinalWitness {
84 continue
85 }
86
87 length, next := int(raw[at+2]), at+3
88 value := raw[next : next+length]
89
90 count := int(value[0])
91 items := make([][]byte, 0, count)
92 offset := 1
93
94 for i := 0; i < count; i++ {
95 size := int(value[offset])
96 offset++
97 items = append(items, value[offset:offset+size])
98 offset += size
99 }
100
101 return items
102 }
103
104 t.Fatal("no final witness record")
105
106 return nil
107 }
108
109 // verifyContractSig checks the signature over the P2WSH digest the contract defines.
110 func verifyContractSig(t *testing.T, pubkey, signature, witnessScript []byte, locktime uint32, amount uint64) {
111 t.Helper()
112
113 transaction := tx.New()
114 transaction.AddInput(tx.Outpoint{Hash: [32]byte{3}, Index: 2}, 0xfffffffe)
115 transaction.AddOutput(60_000, []byte{0x00, 0x14, 5, 5, 5, 5})
116 transaction.LockTime = locktime
117
118 digest, err := transaction.SighashV0(0, witnessScript, amount, tx.SighashAll)
119
120 if err != nil {
121 t.Fatal(err)
122 }
123
124 parsed, err := btcec.ParsePubKey(pubkey)
125
126 if err != nil {
127 t.Fatal(err)
128 }
129
130 sig, err := btcecdsa.ParseDERSignature(signature[:len(signature)-1])
131
132 if err != nil {
133 t.Fatalf("parse signature: %v", err)
134 }
135
136 if !sig.Verify(digest[:], parsed) {
137 t.Fatal("the witness signature does not verify")
138 }
139 }
140
141 // TestSignContractClaim: the claim branch is finalised with the preimage, and the witness has
142 // the shape the script reads: preimage, signature, a true selector, the script.
143 func TestSignContractClaim(t *testing.T) {
144 claimer, claimSecret, witnessScript, terms, preimage := contractFixture(t)
145
146 raw := contractPSBT(t, witnessScript, terms.SecretHash, preimage, 0)
147
148 signed, count, err := SignWithContracts(raw, nil, map[string][]byte{
149 hex.EncodeToString(claimer): claimSecret,
150 }, Policy{MaxSpend: 70_000, MaxFee: 10_000})
151
152 if err != nil {
153 t.Fatalf("SignWithContracts: %v", err)
154 }
155
156 if count != 1 {
157 t.Fatalf("signed %d inputs", count)
158 }
159
160 items := finalWitness(t, signed)
161
162 if len(items) != 4 {
163 t.Fatalf("claim witness has %d items, want preimage, signature, selector, script", len(items))
164 }
165
166 if !bytesEqual(items[0], preimage) {
167 t.Fatalf("the preimage is %x", items[0])
168 }
169
170 if len(items[2]) != 1 || items[2][0] != 0x01 {
171 t.Fatalf("the selector is %x", items[2])
172 }
173
174 if !bytesEqual(items[3], witnessScript) {
175 t.Fatal("the witness script is not last")
176 }
177
178 verifyContractSig(t, claimer, items[1], witnessScript, 0, 70_000)
179 }
180
181 // TestSignContractRefund: only the refunder's key may take the refund branch, and only once the
182 // locktime has passed. The refund witness is the signature, an empty selector, then the script.
183 func TestSignContractRefund(t *testing.T) {
184 _, _, witnessScript, _, _ := contractFixture(t)
185
186 refundKey, _ := btcec.PrivKeyFromBytes([]byte{31: 0x07})
187 refunder := refundKey.PubKey().SerializeCompressed()
188
189 raw := contractPSBT(t, witnessScript, [32]byte{}, nil, 400)
190
191 signed, _, err := SignWithContracts(raw, nil, map[string][]byte{
192 hex.EncodeToString(refunder): refundKey.Serialize(),
193 }, Policy{})
194
195 if err != nil {
196 t.Fatalf("refund: %v", err)
197 }
198
199 items := finalWitness(t, signed)
200
201 if len(items) != 3 || len(items[1]) != 0 || !bytesEqual(items[2], witnessScript) {
202 t.Fatalf("refund witness has %d items", len(items))
203 }
204
205 verifyContractSig(t, refunder, items[0], witnessScript, 400, 70_000)
206
207 // Before the locktime it is not spendable.
208 early := contractPSBT(t, witnessScript, [32]byte{}, nil, 399)
209
210 if _, _, err := SignWithContracts(early, nil, map[string][]byte{
211 hex.EncodeToString(refunder): refundKey.Serialize(),
212 }, Policy{}); !errors.Is(err, ErrPolicy) {
213 t.Fatalf("a refund before its locktime: %v", err)
214 }
215 }
216
217 // TestSignContractRefusals: a claim without the preimage, and a contract whose keys the wallet
218 // does not hold, are refused.
219 func TestSignContractRefusals(t *testing.T) {
220 claimer, claimSecret, witnessScript, terms, _ := contractFixture(t)
221 keys := map[string][]byte{hex.EncodeToString(claimer): claimSecret}
222
223 noPreimage := contractPSBT(t, witnessScript, terms.SecretHash, nil, 0)
224
225 if _, _, err := SignWithContracts(noPreimage, nil, keys, Policy{}); !errors.Is(err, ErrPolicy) {
226 t.Fatalf("a claim without the preimage: %v", err)
227 }
228
229 if _, _, err := SignWithContracts(noPreimage, nil, map[string][]byte{}, Policy{}); !errors.Is(err, ErrNoOwnedInput) {
230 t.Fatalf("a contract we hold no key for: %v", err)
231 }
232 }
233
234 // TestFinalWitnessReadsTheRecord: the exported reader returns the stack a signer finalised.
235 func TestFinalWitnessReadsTheRecord(t *testing.T) {
236 claimer, claimSecret, witnessScript, terms, preimage := contractFixture(t)
237
238 raw := contractPSBT(t, witnessScript, terms.SecretHash, preimage, 0)
239
240 signed, _, err := SignWithContracts(raw, nil, map[string][]byte{
241 hex.EncodeToString(claimer): claimSecret,
242 }, Policy{})
243
244 if err != nil {
245 t.Fatal(err)
246 }
247
248 items, err := FinalWitness(signed)
249
250 if err != nil {
251 t.Fatalf("FinalWitness: %v", err)
252 }
253
254 if len(items) != 4 || !bytesEqual(items[0], preimage) || !bytesEqual(items[3], witnessScript) {
255 t.Fatalf("the witness is %d items", len(items))
256 }
257
258 if _, err := FinalWitness(raw); err == nil {
259 t.Fatal("an unsigned psbt reported a final witness")
260 }
261 }
262
263 // TestParseHTLCReadsAPaddedLocktime: a locktime whose top byte has its high bit set is encoded
264 // with a zero pad, and the parser must accept that form and report the value it means.
265 func TestParseHTLCReadsAPaddedLocktime(t *testing.T) {
266 address, _ := walletKey(t)
267
268 refundKey, _ := btcec.PrivKeyFromBytes([]byte{31: 0x11})
269
270 var secretHash [32]byte
271
272 secretHash[0] = 0x5a
273
274 for _, locktime := range []uint32{127, 128, 43283, 0xffffffff} {
275 witness, err := script.HTLC(address.Pubkey, refundKey.PubKey().SerializeCompressed(), secretHash, locktime)
276
277 if err != nil {
278 t.Fatalf("%d: %v", locktime, err)
279 }
280
281 terms, err := ParseHTLC(witness)
282
283 if err != nil {
284 t.Fatalf("%d: %v", locktime, err)
285 }
286
287 if terms.Locktime != locktime {
288 t.Fatalf("locktime %d parsed as %d", locktime, terms.Locktime)
289 }
290 }
291 }
292