sign.go raw

   1  package domain
   2  
   3  import (
   4  	"encoding/hex"
   5  	"fmt"
   6  
   7  	"git.smesh.lol/tinywallet/pkg/psbt"
   8  )
   9  
  10  // SignPSBT signs a PSBT's wallet-owned inputs within an explicit policy.
  11  //
  12  // The policy is the caller's instruction, and the wallet derives the key material itself: the
  13  // caller never names a key, only the PSBT and the limits it will accept. Every input that pays
  14  // one of this wallet's receive or change scripts is signed; everything else is left for another
  15  // signer, which is what a PSBT is for.
  16  func (d *Domain) SignPSBT(name string, raw []byte, policy psbt.Policy) ([]byte, int, error) {
  17  	derived, err := d.walletOf(name)
  18  
  19  	if err != nil {
  20  		return nil, 0, err
  21  	}
  22  
  23  	meta, err := d.meta(name)
  24  
  25  	if err != nil {
  26  		return nil, 0, err
  27  	}
  28  
  29  	owned := make(map[string]psbt.Key)
  30  	// The contract keys are the same keys, indexed by public key: an HTLC names the wallet's
  31  	// pubkey, so a contract spend is signed with a key this wallet already derives.
  32  	contracts := make(map[string][]byte)
  33  
  34  	// The lookahead is the same window the filters are matched over, so a PSBT paying an
  35  	// address the wallet has already shown is inside it.
  36  	for _, branch := range []struct {
  37  		change bool
  38  		count  uint32
  39  	}{
  40  		{change: false, count: meta.Receive + DefaultLookahead},
  41  		{change: true, count: meta.Change + DefaultLookahead},
  42  	} {
  43  		for index := uint32(0); index < branch.count; index++ {
  44  			address, err := derived.Address(branch.change, index)
  45  
  46  			if err != nil {
  47  				return nil, 0, err
  48  			}
  49  
  50  			secret, err := derived.Secret(branch.change, index)
  51  
  52  			if err != nil {
  53  				return nil, 0, err
  54  			}
  55  
  56  			owned[hex.EncodeToString(address.Script())] = psbt.Key{
  57  				Secret:  secret,
  58  				Program: address.Program,
  59  			}
  60  
  61  			contracts[hex.EncodeToString(address.Pubkey)] = secret
  62  		}
  63  	}
  64  
  65  	var signed []byte
  66  
  67  	var count int
  68  
  69  	link, err := d.link(name)
  70  
  71  	if err != nil {
  72  		return nil, 0, fmt.Errorf("domain: %q: %w", name, err)
  73  	}
  74  
  75  	if link.Profile.UnifiedSighash() {
  76  		signed, count, err = psbt.SignWithContractsUnified(raw, owned, contracts, policy)
  77  	} else {
  78  		signed, count, err = psbt.SignWithContracts(raw, owned, contracts, policy)
  79  	}
  80  
  81  	if err != nil {
  82  		return nil, 0, fmt.Errorf("domain: %q: signing: %w", name, err)
  83  	}
  84  
  85  	return signed, count, nil
  86  }
  87