package psbt import ( "encoding/hex" "errors" "testing" "github.com/btcsuite/btcd/btcec/v2" btcecdsa "github.com/btcsuite/btcd/btcec/v2/ecdsa" "git.smesh.lol/tinywallet/pkg/script" "git.smesh.lol/tinywallet/pkg/tx" ) // contractFixture builds a contract whose claimer is the wallet's own key, and returns the // address, the key, the parsed terms, the witness script and the preimage. func contractFixture(t *testing.T) (walletAddress, claimKey, witnessScript []byte, terms HTLC, preimage []byte) { t.Helper() address, key := walletKey(t) refundKey, _ := btcec.PrivKeyFromBytes([]byte{31: 0x07}) refunder := refundKey.PubKey().SerializeCompressed() // The claim branch checks OP_SIZE 32, so the fixture's secret is 32 bytes. preimage = make([]byte, 32) copy(preimage, []byte("the preimage that opens the contract")) var secretHash [32]byte sum := sha256Of(preimage) copy(secretHash[:], sum) witness, err := script.HTLC(address.Pubkey, refunder, secretHash, 400) if err != nil { t.Fatalf("HTLC: %v", err) } parsed, err := ParseHTLC(witness) if err != nil { t.Fatalf("ParseHTLC: %v", err) } return address.Pubkey, key.Secret, witness, parsed, preimage } // contractPSBT describes a spend of the contract output, with the preimage when it is a claim. func contractPSBT(t *testing.T, witnessScript []byte, secretHash [32]byte, preimage []byte, locktime uint32) []byte { t.Helper() transaction := tx.New() transaction.AddInput(tx.Outpoint{Hash: [32]byte{3}, Index: 2}, 0xfffffffe) transaction.AddOutput(60_000, []byte{0x00, 0x14, 5, 5, 5, 5}) transaction.LockTime = locktime input := SegwitInput{ Amount: 70_000, ScriptPubKey: p2wsh(witnessScript), WitnessScript: witnessScript, } if preimage != nil { input.Preimage = preimage input.SecretHash = secretHash } raw, err := Write(transaction, []SegwitInput{input}) if err != nil { t.Fatalf("Write: %v", err) } return raw } // finalWitness finds the final scriptWitness record in a signed PSBT. func finalWitness(t *testing.T, raw []byte) [][]byte { t.Helper() for at := 0; at+2 < len(raw); at++ { if raw[at] != 0x01 || raw[at+1] != inputFinalWitness { continue } length, next := int(raw[at+2]), at+3 value := raw[next : next+length] count := int(value[0]) items := make([][]byte, 0, count) offset := 1 for i := 0; i < count; i++ { size := int(value[offset]) offset++ items = append(items, value[offset:offset+size]) offset += size } return items } t.Fatal("no final witness record") return nil } // verifyContractSig checks the signature over the P2WSH digest the contract defines. func verifyContractSig(t *testing.T, pubkey, signature, witnessScript []byte, locktime uint32, amount uint64) { t.Helper() transaction := tx.New() transaction.AddInput(tx.Outpoint{Hash: [32]byte{3}, Index: 2}, 0xfffffffe) transaction.AddOutput(60_000, []byte{0x00, 0x14, 5, 5, 5, 5}) transaction.LockTime = locktime digest, err := transaction.SighashV0(0, witnessScript, amount, tx.SighashAll) if err != nil { t.Fatal(err) } parsed, err := btcec.ParsePubKey(pubkey) if err != nil { t.Fatal(err) } sig, err := btcecdsa.ParseDERSignature(signature[:len(signature)-1]) if err != nil { t.Fatalf("parse signature: %v", err) } if !sig.Verify(digest[:], parsed) { t.Fatal("the witness signature does not verify") } } // TestSignContractClaim: the claim branch is finalised with the preimage, and the witness has // the shape the script reads: preimage, signature, a true selector, the script. func TestSignContractClaim(t *testing.T) { claimer, claimSecret, witnessScript, terms, preimage := contractFixture(t) raw := contractPSBT(t, witnessScript, terms.SecretHash, preimage, 0) signed, count, err := SignWithContracts(raw, nil, map[string][]byte{ hex.EncodeToString(claimer): claimSecret, }, Policy{MaxSpend: 70_000, MaxFee: 10_000}) if err != nil { t.Fatalf("SignWithContracts: %v", err) } if count != 1 { t.Fatalf("signed %d inputs", count) } items := finalWitness(t, signed) if len(items) != 4 { t.Fatalf("claim witness has %d items, want preimage, signature, selector, script", len(items)) } if !bytesEqual(items[0], preimage) { t.Fatalf("the preimage is %x", items[0]) } if len(items[2]) != 1 || items[2][0] != 0x01 { t.Fatalf("the selector is %x", items[2]) } if !bytesEqual(items[3], witnessScript) { t.Fatal("the witness script is not last") } verifyContractSig(t, claimer, items[1], witnessScript, 0, 70_000) } // TestSignContractRefund: only the refunder's key may take the refund branch, and only once the // locktime has passed. The refund witness is the signature, an empty selector, then the script. func TestSignContractRefund(t *testing.T) { _, _, witnessScript, _, _ := contractFixture(t) refundKey, _ := btcec.PrivKeyFromBytes([]byte{31: 0x07}) refunder := refundKey.PubKey().SerializeCompressed() raw := contractPSBT(t, witnessScript, [32]byte{}, nil, 400) signed, _, err := SignWithContracts(raw, nil, map[string][]byte{ hex.EncodeToString(refunder): refundKey.Serialize(), }, Policy{}) if err != nil { t.Fatalf("refund: %v", err) } items := finalWitness(t, signed) if len(items) != 3 || len(items[1]) != 0 || !bytesEqual(items[2], witnessScript) { t.Fatalf("refund witness has %d items", len(items)) } verifyContractSig(t, refunder, items[0], witnessScript, 400, 70_000) // Before the locktime it is not spendable. early := contractPSBT(t, witnessScript, [32]byte{}, nil, 399) if _, _, err := SignWithContracts(early, nil, map[string][]byte{ hex.EncodeToString(refunder): refundKey.Serialize(), }, Policy{}); !errors.Is(err, ErrPolicy) { t.Fatalf("a refund before its locktime: %v", err) } } // TestSignContractRefusals: a claim without the preimage, and a contract whose keys the wallet // does not hold, are refused. func TestSignContractRefusals(t *testing.T) { claimer, claimSecret, witnessScript, terms, _ := contractFixture(t) keys := map[string][]byte{hex.EncodeToString(claimer): claimSecret} noPreimage := contractPSBT(t, witnessScript, terms.SecretHash, nil, 0) if _, _, err := SignWithContracts(noPreimage, nil, keys, Policy{}); !errors.Is(err, ErrPolicy) { t.Fatalf("a claim without the preimage: %v", err) } if _, _, err := SignWithContracts(noPreimage, nil, map[string][]byte{}, Policy{}); !errors.Is(err, ErrNoOwnedInput) { t.Fatalf("a contract we hold no key for: %v", err) } } // TestFinalWitnessReadsTheRecord: the exported reader returns the stack a signer finalised. func TestFinalWitnessReadsTheRecord(t *testing.T) { claimer, claimSecret, witnessScript, terms, preimage := contractFixture(t) raw := contractPSBT(t, witnessScript, terms.SecretHash, preimage, 0) signed, _, err := SignWithContracts(raw, nil, map[string][]byte{ hex.EncodeToString(claimer): claimSecret, }, Policy{}) if err != nil { t.Fatal(err) } items, err := FinalWitness(signed) if err != nil { t.Fatalf("FinalWitness: %v", err) } if len(items) != 4 || !bytesEqual(items[0], preimage) || !bytesEqual(items[3], witnessScript) { t.Fatalf("the witness is %d items", len(items)) } if _, err := FinalWitness(raw); err == nil { t.Fatal("an unsigned psbt reported a final witness") } } // TestParseHTLCReadsAPaddedLocktime: a locktime whose top byte has its high bit set is encoded // with a zero pad, and the parser must accept that form and report the value it means. func TestParseHTLCReadsAPaddedLocktime(t *testing.T) { address, _ := walletKey(t) refundKey, _ := btcec.PrivKeyFromBytes([]byte{31: 0x11}) var secretHash [32]byte secretHash[0] = 0x5a for _, locktime := range []uint32{127, 128, 43283, 0xffffffff} { witness, err := script.HTLC(address.Pubkey, refundKey.PubKey().SerializeCompressed(), secretHash, locktime) if err != nil { t.Fatalf("%d: %v", locktime, err) } terms, err := ParseHTLC(witness) if err != nil { t.Fatalf("%d: %v", locktime, err) } if terms.Locktime != locktime { t.Fatalf("locktime %d parsed as %d", locktime, terms.Locktime) } } }