package domain import ( "errors" "testing" "git.smesh.lol/tinywallet/pkg/psbt" "git.smesh.lol/tinywallet/pkg/store" "git.smesh.lol/tinywallet/pkg/tx" "git.smesh.lol/tinywallet/pkg/wallet" ) const signPhrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" // signDomain is a domain with one restored btc chain and a memory store. func signDomain(t *testing.T) (*Domain, string) { t.Helper() cache, err := store.OpenManual(&memPersistence{items: map[string][]byte{}}) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = cache.Close() }) dom, err := New(cache) if err != nil { t.Fatal(err) } profile, err := wallet.ProfileFor("btc", "regtest") if err != nil { t.Fatal(err) } if err := dom.Add("btc", Link{Profile: profile, Client: &fakeChain{}}); err != nil { t.Fatal(err) } created, err := dom.Restore("btc", signPhrase, "sign-test") if err != nil { t.Fatal(err) } return dom, created.Address.Text } // TestSignPSBTSignsTheWalletsOwnInput: the wallet finds its own script among the inputs, signs // it inside the policy, and refuses a policy that does not cover the spend. func TestSignPSBTSignsTheWalletsOwnInput(t *testing.T) { dom, addressText := signDomain(t) derived, err := dom.Addresses("btc", false, 0, 1) if err != nil { t.Fatal(err) } script := derived[0].Script() transaction := tx.New() transaction.AddInput(tx.Outpoint{Hash: [32]byte{5}, Index: 1}, 0xfffffffd) transaction.AddOutput(60_000, []byte{0x00, 0x14, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}) unsigned, err := psbt.Write(transaction, []psbt.SegwitInput{{ Amount: 70_000, ScriptPubKey: script, }}) if err != nil { t.Fatal(err) } signed, count, err := dom.SignPSBT("btc", unsigned, psbt.Policy{MaxSpend: 70_000, MaxFee: 10_000}) if err != nil { t.Fatalf("SignPSBT: %v", err) } if count != 1 { t.Fatalf("signed %d inputs, want 1 (address %s)", count, addressText) } if string(signed) == string(unsigned) { t.Fatal("the signed PSBT is the unsigned one") } if _, _, err := dom.SignPSBT("btc", unsigned, psbt.Policy{MaxFee: 9_999}); !errors.Is(err, psbt.ErrPolicy) { t.Fatalf("a fee over the limit: %v", err) } if _, _, err := dom.SignPSBT("btc", unsigned, psbt.Policy{MaxSpend: 69_999}); !errors.Is(err, psbt.ErrPolicy) { t.Fatalf("a spend over the limit: %v", err) } if _, _, err := dom.SignPSBT("blake", unsigned, psbt.Policy{}); err == nil { t.Fatal("a chain the wallet does not drive was accepted") } }