package domain import ( "encoding/hex" "errors" "fmt" "git.smesh.lol/tinywallet/pkg/bech32" "git.smesh.lol/tinywallet/pkg/script" "git.smesh.lol/tinywallet/pkg/tx" "git.smesh.lol/tinywallet/pkg/utxo" "git.smesh.lol/tinywallet/pkg/wallet" ) // Errors a send refuses. var ( // ErrNoFunds is a spend the chain's unspent coins cannot cover. ErrNoFunds = errors.New("domain: the wallet cannot cover this spend") // ErrSendPolicy is a spend or fee above what the caller allowed. ErrSendPolicy = errors.New("domain: the send is above the policy") // ErrSendChain is a coin on another chain, which cannot be spent here. ErrSendChain = errors.New("domain: a coin belongs to another chain") // ErrNotNative is a coin from before the fork. It exists on both chains and is Bitcoin, // not the forked chain's own money, so spending it here would swap Bitcoin for itself. ErrNotNative = errors.New("domain: a coin predates the fork and is not this chain's money") ) // SendPolicy is what a caller allows one send to do. type SendPolicy struct { // MaxSpend is the largest total input value, in satoshis. MaxSpend uint64 // MaxFee is the largest fee, in satoshis. Zero means the caller set none. MaxFee uint64 // MaxInputs bounds how many coins one send may spend. MaxInputs int } // DefaultMaxInputs bounds a send when the policy sets no limit. const DefaultMaxInputs = 32 // Dust is the value below which change is not worth an output; it is paid as fee instead. const Dust = 546 // Send pays an address from the wallet's own coins on one chain. // // The transaction is built here, signed here with the wallet's keys and broadcast through the // chain channel; no node wallet is involved at any step. The fee is explicit because the two // chains price differently and a local estimate would be a guess; the policy is the caller's // ceiling on both the spend and the fee. // // The spent coins are forgotten and the change is remembered as an unconfirmed coin at height // zero, so a second send does not try to spend them again. func (d *Domain) Send(name, to string, amount, fee uint64, policy SendPolicy) ([32]byte, error) { var none [32]byte if amount == 0 { return none, fmt.Errorf("domain: a send of zero") } link, err := d.link(name) if err != nil { return none, err } derived, err := d.walletOf(name) if err != nil { return none, err } meta, err := d.meta(name) if err != nil { return none, err } hrp, version, program, err := bech32.DecodeSegwit(to) if err != nil { return none, fmt.Errorf("domain: %q: %w", to, err) } if hrp != link.Profile.HRP || version != 0 { return none, fmt.Errorf("domain: %q is not a %s segwit address", to, name) } // Two program sizes matter: a wallet address (20 bytes) and a contract (32 bytes). A swap // is funded by paying its P2WSH address, so refusing 32-byte programs here would make the // one payment the product exists for impossible. var destination []byte switch len(program) { case 20: destination = script.P2WPKH([20]byte(program)) case 32: destination = append([]byte{0x00, 0x20}, program...) default: return none, fmt.Errorf("domain: %q has a %d-byte witness program", to, len(program)) } coins, err := d.UnspentOn(name) if err != nil { return none, err } maxInputs := policy.MaxInputs if maxInputs <= 0 { maxInputs = DefaultMaxInputs } keys, err := d.spendKeys(derived, meta) if err != nil { return none, err } var ( chosen []signedCoin total uint64 ) for _, coin := range coins { if coin.Chain != name { return none, fmt.Errorf("%w: %s", ErrSendChain, coin.Chain) } if !link.Profile.Native(coin.Height) { return none, fmt.Errorf( "%w: coin %s at height %d, the fork is at %d", ErrNotNative, coin.Outpoint(), coin.Height, link.Profile.ForkHeight, ) } key, ours := keys[string(coin.Script)] if !ours { // A watched contract's coin is not this wallet's to spend with a BIP84 key. continue } chosen = append(chosen, signedCoin{coin: coin, key: key}) total += coin.Value if total >= amount+fee { break } if len(chosen) >= maxInputs { break } } if total < amount+fee { return none, fmt.Errorf("%w: %d sat need %d", ErrNoFunds, total, amount+fee) } if policy.MaxSpend > 0 && total > policy.MaxSpend { return none, fmt.Errorf("%w: spending %d sat, the limit is %d", ErrSendPolicy, total, policy.MaxSpend) } if policy.MaxFee > 0 && fee > policy.MaxFee { return none, fmt.Errorf("%w: the fee is %d sat, the limit is %d", ErrSendPolicy, fee, policy.MaxFee) } return d.sendSigned(name, to, destination, amount, fee, policy, chosen) } // sendSigned builds, signs, broadcasts and records one spend of a chosen coin set. // // It is the shared tail of Send and Fork: the coin selection differs, but the // construction, signing, broadcast and bookkeeping do not. `destination` is the // decoded witness program of the payee and `chosen` the coins this spend consumes. func (d *Domain) sendSigned( name, to string, destination []byte, amount, fee uint64, policy SendPolicy, chosen []signedCoin, ) ([32]byte, error) { var none [32]byte link, err := d.link(name) if err != nil { return none, err } derived, err := d.walletOf(name) if err != nil { return none, err } meta, err := d.meta(name) if err != nil { return none, err } var total uint64 for _, coin := range chosen { total += coin.coin.Value } if total < amount+fee { return none, fmt.Errorf("%w: %d sat need %d", ErrNoFunds, total, amount+fee) } if policy.MaxSpend > 0 && total > policy.MaxSpend { return none, fmt.Errorf("%w: spending %d sat, the limit is %d", ErrSendPolicy, total, policy.MaxSpend) } if policy.MaxFee > 0 && fee > policy.MaxFee { return none, fmt.Errorf("%w: the fee is %d sat, the limit is %d", ErrSendPolicy, fee, policy.MaxFee) } transaction := tx.New() for _, coin := range chosen { transaction.AddInput(tx.Outpoint{Hash: coin.coin.TxID, Index: coin.coin.Vout}, 0xfffffffd) } transaction.AddOutput(amount, destination) change := total - amount - fee var changeCoin *utxo.Coin if change >= Dust { changeAddress, err := derived.Address(true, meta.Change) if err != nil { return none, err } secret, err := derived.Secret(true, meta.Change) if err != nil { return none, err } if !verifyKey(secret, changeAddress.Program) { return none, fmt.Errorf("domain: the change key does not match its address") } transaction.AddOutput(change, changeAddress.Script()) changeCoin = &utxo.Coin{ Chain: name, Value: change, Script: changeAddress.Script(), } } else { // Below dust the change is not worth an output; it is paid to the miner, which is // why the fee the caller named can come out slightly higher. fee += change } spent := make([]tx.SpentOutput, len(chosen)) for index, coin := range chosen { spent[index] = tx.SpentOutput{Value: coin.coin.Value, Script: coin.coin.Script} } unified := link.Profile.UnifiedSighash() for index, coin := range chosen { // The coin knows which account it came from; a credited restored seed can hold coins at // the standard account while this wallet derives from another one. accountWallet, err := derived.ForAccount(coin.key.account) if err != nil { return none, err } derivedKey, err := accountWallet.Secret(coin.key.change, coin.key.index) if err != nil { return none, err } if unified { if err := tx.SignP2WPKHUnified(transaction, index, derivedKey, coin.key.program, spent); err != nil { return none, err } continue } if err := tx.SignP2WPKH(transaction, index, derivedKey, coin.key.program, coin.coin.Value); err != nil { return none, err } } raw, err := transaction.SerializeWitness() if err != nil { return none, err } if err := link.Client.Broadcast(raw); err != nil { return none, fmt.Errorf("domain: %q: broadcast: %w", name, err) } txid, err := transaction.TxID() if err != nil { return none, err } // The transaction is on the wire, so the coins are spent now rather than on the next scan. for _, coin := range chosen { if err := d.utxos.Spend(name, coin.coin.TxID, coin.coin.Vout); err != nil { return txid, err } } if changeCoin != nil { changeCoin.TxID = txid changeCoin.Vout = uint32(len(transaction.Outputs) - 1) if err := d.utxos.Add(*changeCoin); err != nil { return txid, err } } // The wallet is the only record of what it sent: keep the bytes and the payment so a // recovery or a receipt can find them without a node wallet. if err := d.RecordSent(Sent{ Chain: name, TxID: hex.EncodeToString(reversed(txid[:])), Hex: hex.EncodeToString(raw), Address: to, Amount: amount, Fee: fee, Vout: 0, }); err != nil { return txid, err } // The change address is used, so the next one is the one after it. meta.Change++ if err := d.store.Put(metaKey(name), PutMeta(meta)); err != nil { return txid, err } return txid, nil } // reversed is the display order of a transaction id. func reversed(raw []byte) []byte { out := make([]byte, len(raw)) for i, b := range raw { out[len(raw)-1-i] = b } return out } // spendKey says which address and key spends one coin. type spendKey struct { account uint32 change bool index uint32 program [20]byte } type signedCoin struct { coin utxo.Coin key spendKey } // spendKeys maps every script the wallet can sign for to the address that owns it. func (d *Domain) spendKeys(derived *wallet.Wallet, meta Meta) (map[string]spendKey, error) { keys := make(map[string]spendKey, int(meta.Receive+meta.Change+2*DefaultLookahead)) for _, account := range scanAccounts(derived.Profile().Account) { accountWallet, err := derived.ForAccount(account) if err != nil { return nil, err } for _, branch := range []struct { change bool count uint32 }{ {change: false, count: meta.Receive + DefaultLookahead}, {change: true, count: meta.Change + DefaultLookahead}, } { for index := uint32(0); index < branch.count; index++ { address, err := accountWallet.Address(branch.change, index) if err != nil { return nil, err } keys[string(address.Script())] = spendKey{ change: branch.change, index: index, program: address.Program, account: account, } } } } return keys, nil } // verifyKey checks that a secret really controls a witness program before it is used, so a // mismatched derivation is caught before a coin is spent rather than after. func verifyKey(secret []byte, program [20]byte) bool { _, derived, err := wallet.Public(secret) return err == nil && derived == program }