package domain import ( "errors" "testing" "github.com/btcsuite/btcd/btcec/v2" btcecdsa "github.com/btcsuite/btcd/btcec/v2/ecdsa" "git.smesh.lol/tinywallet/pkg/tx" ) // fundedRestored gives a rig whose btc wallet owns one coin of value, at height 150. func fundedRestored(t *testing.T, value uint64) *rig { t.Helper() r := newRig(t, "regtest") if _, err := r.domain.Restore("btc", phrase, "pass"); err != nil { t.Fatal(err) } address, err := r.domain.Addresses("btc", false, 0, 1) if err != nil { t.Fatal(err) } chain := r.chains["btc"] chain.syncTo = chaindataPosition(200) chain.matched = []uint32{150} chain.blocks = map[uint32][]byte{150: buildBlock(t, address[0].Script(), value)} if _, err := r.domain.Sync("btc", 0); err != nil { t.Fatal(err) } return r } // TestSendBuildsSignsAndBroadcasts: the send is local end to end — coins selected from the // table, the transaction built and signed here, one broadcast, spent coins forgotten and the // change remembered. func TestSendBuildsSignsAndBroadcasts(t *testing.T) { r := fundedRestored(t, 100_000) destination, err := r.domain.Addresses("btc", false, 2, 1) if err != nil { t.Fatal(err) } txid, err := r.domain.Send("btc", destination[0].Text, 50_000, 1_000, SendPolicy{ MaxSpend: 100_000, MaxFee: 2_000, }) if err != nil { t.Fatalf("Send: %v", err) } chain := r.chains["btc"] if chain.broadcastCalls != 1 { t.Fatalf("broadcast %d times", chain.broadcastCalls) } sent, err := tx.Decode(chain.broadcast[0]) if err != nil { t.Fatalf("decode what was broadcast: %v", err) } if got, _ := sent.TxID(); got != txid { t.Fatalf("the returned txid %x is not the transaction's %x", txid, got) } if len(sent.Outputs) != 2 { t.Fatalf("%d outputs, want payment and change", len(sent.Outputs)) } if sent.Outputs[0].Value != 50_000 || string(sent.Outputs[0].Script) != string(destination[0].Script()) { t.Fatalf("the payment is %+v", sent.Outputs[0]) } var change uint64 = 100_000 - 50_000 - 1_000 if sent.Outputs[1].Value != change { t.Fatalf("the change is %d, want %d", sent.Outputs[1].Value, change) } if len(sent.Inputs) != 1 || len(sent.Inputs[0].Witness) != 2 { t.Fatalf("inputs %d, witness %d", len(sent.Inputs), len(sent.Inputs[0].Witness)) } // The spent coin is gone and the change is remembered as an unconfirmed coin. coins, err := r.domain.UnspentOn("btc") if err != nil { t.Fatal(err) } if len(coins) != 1 { t.Fatalf("%d coins after the send", len(coins)) } if coins[0].Value != change || coins[0].Height != 0 || coins[0].TxID != txid { t.Fatalf("change coin %+v", coins[0]) } } // TestSendRefusesWhatThePolicyForbids: each refusal is distinct and none of them touches the // chain or the coin table. func TestSendRefusesWhatThePolicyForbids(t *testing.T) { r := fundedRestored(t, 100_000) destination, _ := r.domain.Addresses("btc", false, 2, 1) chain := r.chains["btc"] if _, err := r.domain.Send("btc", destination[0].Text, 50_000, 1_000, SendPolicy{MaxSpend: 99_999}); !errors.Is(err, ErrSendPolicy) { t.Fatalf("spend over the limit: %v", err) } if _, err := r.domain.Send("btc", destination[0].Text, 50_000, 1_000, SendPolicy{MaxFee: 999}); !errors.Is(err, ErrSendPolicy) { t.Fatalf("fee over the limit: %v", err) } if _, err := r.domain.Send("btc", destination[0].Text, 200_000, 1_000, SendPolicy{}); !errors.Is(err, ErrNoFunds) { t.Fatalf("funds the wallet does not have: %v", err) } if _, err := r.domain.Send("btc", "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4", 50_000, 1_000, SendPolicy{}); err == nil { t.Fatal("an address on another network was accepted") } if _, err := r.domain.Send("blake", destination[0].Text, 50_000, 1_000, SendPolicy{}); err == nil { t.Fatal("a chain the wallet does not drive was accepted") } if chain.broadcastCalls != 0 { t.Fatalf("a refused send broadcast %d times", chain.broadcastCalls) } if coins, _ := r.domain.UnspentOn("btc"); len(coins) != 1 { t.Fatalf("a refused send changed the coin table: %d coins", len(coins)) } // A broadcast the chain refuses leaves the coins alone too. chain.broadcastErr = errors.New("the peer is gone") if _, err := r.domain.Send("btc", destination[0].Text, 50_000, 1_000, SendPolicy{}); err == nil { t.Fatal("a failed broadcast reported success") } if coins, _ := r.domain.UnspentOn("btc"); len(coins) != 1 { t.Fatalf("a failed broadcast changed the coin table: %d coins", len(coins)) } } // TestSendRefusesPreForkCoinsOnLegacyBTC: the Bitcoin wallet has no unified // bit, so a pre-fork coin spent with a legacy signature would be valid on XBT // too. It must stay refused; only the XBT wallet can use a shared coin safely. func TestSendRefusesPreForkCoinsOnLegacyBTC(t *testing.T) { r := newRig(t, "regtest") if _, err := r.domain.Restore("btc", phrase, "pass"); err != nil { t.Fatal(err) } address, err := r.domain.Addresses("btc", false, 0, 1) if err != nil { t.Fatal(err) } chain := r.chains["btc"] chain.syncTo = chaindataPosition(60) chain.matched = []uint32{50} chain.blocks = map[uint32][]byte{50: buildBlock(t, address[0].Script(), 100_000)} if _, err := r.domain.Sync("btc", 0); err != nil { t.Fatal(err) } // Before the rule is applied the coin is visible but not necessarily spendable. if coins, _ := r.domain.UnspentOn("btc"); len(coins) != 1 { t.Fatalf("%d coins", len(coins)) } link, err := r.domain.link("btc") if err != nil { t.Fatal(err) } link.Profile.ForkHeight = 100 r.domain.mu.Lock() r.domain.links["btc"] = link r.domain.mu.Unlock() if coins, _ := r.domain.SpendableOn("btc"); len(coins) != 0 { t.Fatalf("%d pre-fork coins are spendable", len(coins)) } destination, _ := r.domain.Addresses("btc", false, 2, 1) if _, err := r.domain.Send("btc", destination[0].Text, 50_000, 1_000, SendPolicy{}); !errors.Is(err, ErrNotNative) { t.Fatalf("a pre-fork coin: %v", err) } if chain.broadcastCalls != 0 { t.Fatal("a pre-fork coin was spent") } } // TestSendFundsAContract: a swap is funded by paying a P2WSH address, so a 32-byte witness // program is a valid destination and the output carries it. func TestSendFundsAContract(t *testing.T) { r := fundedRestored(t, 100_000) addresses, err := r.domain.Addresses("btc", false, 0, 1) if err != nil { t.Fatal(err) } sum := sha256Of([]byte("rigorous preimage")) refundKey, _ := btcec.PrivKeyFromBytes([]byte{31: 0x11}) contract, witness, _, err := r.domain.DeriveHTLC( "btc", addresses[0].Pubkey, refundKey.PubKey().SerializeCompressed(), sum, 500, ) if err != nil { t.Fatal(err) } if _, err := r.domain.Send("btc", contract, 50_000, 1_000, SendPolicy{}); err != nil { t.Fatalf("Send to a contract: %v", err) } sent, err := tx.Decode(r.chains["btc"].broadcast[0]) if err != nil { t.Fatal(err) } digest := sha256Of(witness) want := append([]byte{0x00, 0x20}, digest[:]...) if string(sent.Outputs[0].Script) != string(want) { t.Fatalf("the contract output pays %x", sent.Outputs[0].Script) } } // TestSendOnXBTUsesTheUnifiedSighash: the XBT wallet's funding spend opts into // SIGHASH_UNIFIED, so the transaction is invalid on a chain that does not // implement the bit. This is the client-side replay protection for a shared // UTXO, not just for a post-fork one. func TestSendOnXBTUsesTheUnifiedSighash(t *testing.T) { r := newRig(t, "regtest") if _, err := r.domain.Restore("blake", phrase, "pass"); err != nil { t.Fatal(err) } address, err := r.domain.Addresses("blake", false, 0, 1) if err != nil { t.Fatal(err) } // Deliberately a pre-fork coin: the unified signature, not ancestry, is // what makes this spend XBT-only. chain := r.chains["blake"] chain.syncTo = chaindataPosition(60) chain.matched = []uint32{50} chain.blocks = map[uint32][]byte{50: buildBlock(t, address[0].Script(), 100_000)} if _, err := r.domain.Sync("blake", 0); err != nil { t.Fatal(err) } link, err := r.domain.link("blake") if err != nil { t.Fatal(err) } link.Profile.Name = "blake" link.Profile.ForkHeight = 100 r.domain.mu.Lock() r.domain.links["blake"] = link r.domain.mu.Unlock() destination, err := r.domain.Addresses("blake", false, 2, 1) if err != nil { t.Fatal(err) } if _, err := r.domain.Send("blake", destination[0].Text, 50_000, 1_000, SendPolicy{}); err != nil { t.Fatal(err) } sent, err := tx.Decode(chain.broadcast[0]) if err != nil { t.Fatal(err) } if len(sent.Inputs) != 1 || len(sent.Inputs[0].Witness) != 2 { t.Fatalf("witness = %d inputs, %d items", len(sent.Inputs), len(sent.Inputs[0].Witness)) } item := sent.Inputs[0].Witness[0] if item[len(item)-1] != byte(tx.SighashAllUnified) { t.Fatalf("sighash byte %#x, want %#x", item[len(item)-1], byte(tx.SighashAllUnified)) } spent := []tx.SpentOutput{{Value: 100_000, Script: address[0].Script()}} digest, err := sent.SighashUnifiedV0( 0, tx.P2WPKHScriptCode(address[0].Program), spent, tx.SighashAllUnified, ) if err != nil { t.Fatal(err) } signature, err := btcecdsa.ParseDERSignature(item[:len(item)-1]) if err != nil { t.Fatal(err) } pubkey, err := btcec.ParsePubKey(sent.Inputs[0].Witness[1]) if err != nil { t.Fatal(err) } if !signature.Verify(digest[:], pubkey) { t.Fatal("the funding signature does not verify over the unified digest") } }