1 package domain
2 3 import (
4 "encoding/hex"
5 "errors"
6 "fmt"
7 8 "git.smesh.lol/tinywallet/pkg/bech32"
9 "git.smesh.lol/tinywallet/pkg/script"
10 "git.smesh.lol/tinywallet/pkg/tx"
11 "git.smesh.lol/tinywallet/pkg/utxo"
12 "git.smesh.lol/tinywallet/pkg/wallet"
13 )
14 15 // Errors a send refuses.
16 var (
17 // ErrNoFunds is a spend the chain's unspent coins cannot cover.
18 ErrNoFunds = errors.New("domain: the wallet cannot cover this spend")
19 // ErrSendPolicy is a spend or fee above what the caller allowed.
20 ErrSendPolicy = errors.New("domain: the send is above the policy")
21 // ErrSendChain is a coin on another chain, which cannot be spent here.
22 ErrSendChain = errors.New("domain: a coin belongs to another chain")
23 // ErrNotNative is a coin from before the fork. It exists on both chains and is Bitcoin,
24 // not the forked chain's own money, so spending it here would swap Bitcoin for itself.
25 ErrNotNative = errors.New("domain: a coin predates the fork and is not this chain's money")
26 )
27 28 // SendPolicy is what a caller allows one send to do.
29 type SendPolicy struct {
30 // MaxSpend is the largest total input value, in satoshis.
31 MaxSpend uint64
32 // MaxFee is the largest fee, in satoshis. Zero means the caller set none.
33 MaxFee uint64
34 // MaxInputs bounds how many coins one send may spend.
35 MaxInputs int
36 }
37 38 // DefaultMaxInputs bounds a send when the policy sets no limit.
39 const DefaultMaxInputs = 32
40 41 // Dust is the value below which change is not worth an output; it is paid as fee instead.
42 const Dust = 546
43 44 // Send pays an address from the wallet's own coins on one chain.
45 //
46 // The transaction is built here, signed here with the wallet's keys and broadcast through the
47 // chain channel; no node wallet is involved at any step. The fee is explicit because the two
48 // chains price differently and a local estimate would be a guess; the policy is the caller's
49 // ceiling on both the spend and the fee.
50 //
51 // The spent coins are forgotten and the change is remembered as an unconfirmed coin at height
52 // zero, so a second send does not try to spend them again.
53 func (d *Domain) Send(name, to string, amount, fee uint64, policy SendPolicy) ([32]byte, error) {
54 var none [32]byte
55 56 if amount == 0 {
57 return none, fmt.Errorf("domain: a send of zero")
58 }
59 60 link, err := d.link(name)
61 62 if err != nil {
63 return none, err
64 }
65 66 derived, err := d.walletOf(name)
67 68 if err != nil {
69 return none, err
70 }
71 72 meta, err := d.meta(name)
73 74 if err != nil {
75 return none, err
76 }
77 78 hrp, version, program, err := bech32.DecodeSegwit(to)
79 80 if err != nil {
81 return none, fmt.Errorf("domain: %q: %w", to, err)
82 }
83 84 if hrp != link.Profile.HRP || version != 0 {
85 return none, fmt.Errorf("domain: %q is not a %s segwit address", to, name)
86 }
87 88 // Two program sizes matter: a wallet address (20 bytes) and a contract (32 bytes). A swap
89 // is funded by paying its P2WSH address, so refusing 32-byte programs here would make the
90 // one payment the product exists for impossible.
91 var destination []byte
92 93 switch len(program) {
94 case 20:
95 destination = script.P2WPKH([20]byte(program))
96 case 32:
97 destination = append([]byte{0x00, 0x20}, program...)
98 default:
99 return none, fmt.Errorf("domain: %q has a %d-byte witness program", to, len(program))
100 }
101 102 coins, err := d.UnspentOn(name)
103 104 if err != nil {
105 return none, err
106 }
107 108 maxInputs := policy.MaxInputs
109 110 if maxInputs <= 0 {
111 maxInputs = DefaultMaxInputs
112 }
113 114 keys, err := d.spendKeys(derived, meta)
115 116 if err != nil {
117 return none, err
118 }
119 120 var (
121 chosen []signedCoin
122 total uint64
123 )
124 125 for _, coin := range coins {
126 if coin.Chain != name {
127 return none, fmt.Errorf("%w: %s", ErrSendChain, coin.Chain)
128 }
129 130 if !link.Profile.Native(coin.Height) {
131 return none, fmt.Errorf(
132 "%w: coin %s at height %d, the fork is at %d",
133 ErrNotNative, coin.Outpoint(), coin.Height, link.Profile.ForkHeight,
134 )
135 }
136 137 key, ours := keys[string(coin.Script)]
138 139 if !ours {
140 // A watched contract's coin is not this wallet's to spend with a BIP84 key.
141 continue
142 }
143 144 chosen = append(chosen, signedCoin{coin: coin, key: key})
145 total += coin.Value
146 147 if total >= amount+fee {
148 break
149 }
150 151 if len(chosen) >= maxInputs {
152 break
153 }
154 }
155 156 if total < amount+fee {
157 return none, fmt.Errorf("%w: %d sat need %d", ErrNoFunds, total, amount+fee)
158 }
159 160 if policy.MaxSpend > 0 && total > policy.MaxSpend {
161 return none, fmt.Errorf("%w: spending %d sat, the limit is %d", ErrSendPolicy, total, policy.MaxSpend)
162 }
163 164 if policy.MaxFee > 0 && fee > policy.MaxFee {
165 return none, fmt.Errorf("%w: the fee is %d sat, the limit is %d", ErrSendPolicy, fee, policy.MaxFee)
166 }
167 168 return d.sendSigned(name, to, destination, amount, fee, policy, chosen)
169 }
170 171 // sendSigned builds, signs, broadcasts and records one spend of a chosen coin set.
172 //
173 // It is the shared tail of Send and Fork: the coin selection differs, but the
174 // construction, signing, broadcast and bookkeeping do not. `destination` is the
175 // decoded witness program of the payee and `chosen` the coins this spend consumes.
176 func (d *Domain) sendSigned(
177 name, to string,
178 destination []byte,
179 amount, fee uint64,
180 policy SendPolicy,
181 chosen []signedCoin,
182 ) ([32]byte, error) {
183 var none [32]byte
184 185 link, err := d.link(name)
186 187 if err != nil {
188 return none, err
189 }
190 191 derived, err := d.walletOf(name)
192 193 if err != nil {
194 return none, err
195 }
196 197 meta, err := d.meta(name)
198 199 if err != nil {
200 return none, err
201 }
202 203 var total uint64
204 205 for _, coin := range chosen {
206 total += coin.coin.Value
207 }
208 209 if total < amount+fee {
210 return none, fmt.Errorf("%w: %d sat need %d", ErrNoFunds, total, amount+fee)
211 }
212 213 if policy.MaxSpend > 0 && total > policy.MaxSpend {
214 return none, fmt.Errorf("%w: spending %d sat, the limit is %d", ErrSendPolicy, total, policy.MaxSpend)
215 }
216 217 if policy.MaxFee > 0 && fee > policy.MaxFee {
218 return none, fmt.Errorf("%w: the fee is %d sat, the limit is %d", ErrSendPolicy, fee, policy.MaxFee)
219 }
220 221 transaction := tx.New()
222 223 for _, coin := range chosen {
224 transaction.AddInput(tx.Outpoint{Hash: coin.coin.TxID, Index: coin.coin.Vout}, 0xfffffffd)
225 }
226 227 transaction.AddOutput(amount, destination)
228 229 change := total - amount - fee
230 231 var changeCoin *utxo.Coin
232 233 if change >= Dust {
234 changeAddress, err := derived.Address(true, meta.Change)
235 236 if err != nil {
237 return none, err
238 }
239 240 secret, err := derived.Secret(true, meta.Change)
241 242 if err != nil {
243 return none, err
244 }
245 246 if !verifyKey(secret, changeAddress.Program) {
247 return none, fmt.Errorf("domain: the change key does not match its address")
248 }
249 250 transaction.AddOutput(change, changeAddress.Script())
251 252 changeCoin = &utxo.Coin{
253 Chain: name,
254 Value: change,
255 Script: changeAddress.Script(),
256 }
257 } else {
258 // Below dust the change is not worth an output; it is paid to the miner, which is
259 // why the fee the caller named can come out slightly higher.
260 fee += change
261 }
262 263 spent := make([]tx.SpentOutput, len(chosen))
264 265 for index, coin := range chosen {
266 spent[index] = tx.SpentOutput{Value: coin.coin.Value, Script: coin.coin.Script}
267 }
268 269 unified := link.Profile.UnifiedSighash()
270 271 for index, coin := range chosen {
272 // The coin knows which account it came from; a credited restored seed can hold coins at
273 // the standard account while this wallet derives from another one.
274 accountWallet, err := derived.ForAccount(coin.key.account)
275 276 if err != nil {
277 return none, err
278 }
279 280 derivedKey, err := accountWallet.Secret(coin.key.change, coin.key.index)
281 282 if err != nil {
283 return none, err
284 }
285 286 if unified {
287 if err := tx.SignP2WPKHUnified(transaction, index, derivedKey, coin.key.program, spent); err != nil {
288 return none, err
289 }
290 291 continue
292 }
293 294 if err := tx.SignP2WPKH(transaction, index, derivedKey, coin.key.program, coin.coin.Value); err != nil {
295 return none, err
296 }
297 }
298 299 raw, err := transaction.SerializeWitness()
300 301 if err != nil {
302 return none, err
303 }
304 305 if err := link.Client.Broadcast(raw); err != nil {
306 return none, fmt.Errorf("domain: %q: broadcast: %w", name, err)
307 }
308 309 txid, err := transaction.TxID()
310 311 if err != nil {
312 return none, err
313 }
314 315 // The transaction is on the wire, so the coins are spent now rather than on the next scan.
316 for _, coin := range chosen {
317 if err := d.utxos.Spend(name, coin.coin.TxID, coin.coin.Vout); err != nil {
318 return txid, err
319 }
320 }
321 322 if changeCoin != nil {
323 changeCoin.TxID = txid
324 changeCoin.Vout = uint32(len(transaction.Outputs) - 1)
325 326 if err := d.utxos.Add(*changeCoin); err != nil {
327 return txid, err
328 }
329 }
330 331 // The wallet is the only record of what it sent: keep the bytes and the payment so a
332 // recovery or a receipt can find them without a node wallet.
333 if err := d.RecordSent(Sent{
334 Chain: name, TxID: hex.EncodeToString(reversed(txid[:])), Hex: hex.EncodeToString(raw),
335 Address: to, Amount: amount, Fee: fee, Vout: 0,
336 }); err != nil {
337 return txid, err
338 }
339 340 // The change address is used, so the next one is the one after it.
341 meta.Change++
342 343 if err := d.store.Put(metaKey(name), PutMeta(meta)); err != nil {
344 return txid, err
345 }
346 347 return txid, nil
348 }
349 350 // reversed is the display order of a transaction id.
351 func reversed(raw []byte) []byte {
352 out := make([]byte, len(raw))
353 354 for i, b := range raw {
355 out[len(raw)-1-i] = b
356 }
357 358 return out
359 }
360 361 // spendKey says which address and key spends one coin.
362 type spendKey struct {
363 account uint32
364 change bool
365 index uint32
366 program [20]byte
367 }
368 369 type signedCoin struct {
370 coin utxo.Coin
371 key spendKey
372 }
373 374 // spendKeys maps every script the wallet can sign for to the address that owns it.
375 func (d *Domain) spendKeys(derived *wallet.Wallet, meta Meta) (map[string]spendKey, error) {
376 keys := make(map[string]spendKey, int(meta.Receive+meta.Change+2*DefaultLookahead))
377 378 for _, account := range scanAccounts(derived.Profile().Account) {
379 accountWallet, err := derived.ForAccount(account)
380 381 if err != nil {
382 return nil, err
383 }
384 385 for _, branch := range []struct {
386 change bool
387 count uint32
388 }{
389 {change: false, count: meta.Receive + DefaultLookahead},
390 {change: true, count: meta.Change + DefaultLookahead},
391 } {
392 for index := uint32(0); index < branch.count; index++ {
393 address, err := accountWallet.Address(branch.change, index)
394 395 if err != nil {
396 return nil, err
397 }
398 399 keys[string(address.Script())] = spendKey{
400 change: branch.change, index: index, program: address.Program,
401 account: account,
402 }
403 }
404 }
405 }
406 407 return keys, nil
408 }
409 410 // verifyKey checks that a secret really controls a witness program before it is used, so a
411 // mismatched derivation is caught before a coin is spent rather than after.
412 func verifyKey(secret []byte, program [20]byte) bool {
413 _, derived, err := wallet.Public(secret)
414 415 return err == nil && derived == program
416 }
417