package domain import ( "encoding/hex" "fmt" "git.smesh.lol/tinywallet/pkg/psbt" ) // SignPSBT signs a PSBT's wallet-owned inputs within an explicit policy. // // The policy is the caller's instruction, and the wallet derives the key material itself: the // caller never names a key, only the PSBT and the limits it will accept. Every input that pays // one of this wallet's receive or change scripts is signed; everything else is left for another // signer, which is what a PSBT is for. func (d *Domain) SignPSBT(name string, raw []byte, policy psbt.Policy) ([]byte, int, error) { derived, err := d.walletOf(name) if err != nil { return nil, 0, err } meta, err := d.meta(name) if err != nil { return nil, 0, err } owned := make(map[string]psbt.Key) // The contract keys are the same keys, indexed by public key: an HTLC names the wallet's // pubkey, so a contract spend is signed with a key this wallet already derives. contracts := make(map[string][]byte) // The lookahead is the same window the filters are matched over, so a PSBT paying an // address the wallet has already shown is inside it. 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 := derived.Address(branch.change, index) if err != nil { return nil, 0, err } secret, err := derived.Secret(branch.change, index) if err != nil { return nil, 0, err } owned[hex.EncodeToString(address.Script())] = psbt.Key{ Secret: secret, Program: address.Program, } contracts[hex.EncodeToString(address.Pubkey)] = secret } } var signed []byte var count int link, err := d.link(name) if err != nil { return nil, 0, fmt.Errorf("domain: %q: %w", name, err) } if link.Profile.UnifiedSighash() { signed, count, err = psbt.SignWithContractsUnified(raw, owned, contracts, policy) } else { signed, count, err = psbt.SignWithContracts(raw, owned, contracts, policy) } if err != nil { return nil, 0, fmt.Errorf("domain: %q: signing: %w", name, err) } return signed, count, nil }