sign.go raw

   1  package psbt
   2  
   3  import (
   4  	"encoding/binary"
   5  	"encoding/hex"
   6  	"errors"
   7  	"fmt"
   8  
   9  	"git.smesh.lol/tinywallet/pkg/tx"
  10  )
  11  
  12  // The partial-signature record BIP174 defines.
  13  const inputPartialSig byte = 0x02
  14  
  15  // Errors a signing request refuses.
  16  var (
  17  	// ErrNoOwnedInput is a PSBT with nothing in it that this wallet may sign.
  18  	ErrNoOwnedInput = errors.New("psbt: no input pays this wallet")
  19  	// ErrPolicy is a spend or fee above what the caller allowed.
  20  	ErrPolicy = errors.New("psbt: the spend is above the policy")
  21  	// ErrUnknownInput is an input whose value is not in the PSBT, which makes the fee
  22  	// unknowable and therefore unenforceable.
  23  	ErrUnknownInput = errors.New("psbt: an input has no witness utxo, so the fee is unknown")
  24  )
  25  
  26  // Key is one address's signing material: the private key and the witness program it spends.
  27  type Key struct {
  28  	// Secret is the 32-byte private key.
  29  	Secret []byte
  30  	// Program is the 20-byte P2WPKH witness program.
  31  	Program [20]byte
  32  }
  33  
  34  // Policy is what a caller allows this signing request to do.
  35  //
  36  // The zero value refuses nothing except a PSBT with nothing of this wallet's in it, because a
  37  // caller that has not set a limit has not asked for one. A caller that sets a limit means it,
  38  // which is the point of passing one.
  39  type Policy struct {
  40  	// MaxSpend is the largest total input value this wallet may contribute, in satoshis.
  41  	MaxSpend uint64
  42  	// MaxFee is the largest fee the signed transaction may pay, in satoshis.
  43  	MaxFee uint64
  44  }
  45  
  46  // Sign signs every input of the PSBT whose witness UTXO pays one of the keys, and returns the
  47  // PSBT with those partial signatures added, and how many were added.
  48  //
  49  // The records it keeps are the ones this package writes — the unsigned transaction, each
  50  // input's witness UTXO, witness script and SHA-256 preimage — and the partial signatures it
  51  // adds. A record it does not understand is dropped rather than guessed at, which is why this
  52  // signer is for a PSBT this wallet or its own builder produced; another signer's proprietary
  53  // records belong to that signer.
  54  //
  55  // It does not finalise: a partial signature is what a PSBT carries, and finalising is the
  56  // caller's decision about fee and completeness.
  57  func Sign(raw []byte, owned map[string]Key, policy Policy) ([]byte, int, error) {
  58  	return sign(raw, owned, nil, policy, false)
  59  }
  60  
  61  // SignUnified is Sign, but every signature opts into the XBT fork's unified
  62  // hash. The PSBT must carry every input's witness UTXO: the unified message
  63  // commits to every spent value and scriptPubKey.
  64  func SignUnified(raw []byte, owned map[string]Key, policy Policy) ([]byte, int, error) {
  65  	return sign(raw, owned, nil, policy, true)
  66  }
  67  
  68  // SignWithContracts signs both the wallet's P2WPKH inputs and any contract input it can
  69  // finalise. contracts maps a compressed public key, as hex, to the secret that controls it.
  70  //
  71  // A contract input is finalised here rather than left for another signer: the claim needs the
  72  // preimage, which the caller put in the PSBT, and the refund needs the locktime to have passed,
  73  // and the wallet is the only party that can decide both. The result is a final scriptWitness
  74  // record, so a plain finalisepsbt assembles the transaction.
  75  func SignWithContracts(raw []byte, owned map[string]Key, contracts map[string][]byte, policy Policy) ([]byte, int, error) {
  76  	return sign(raw, owned, contracts, policy, false)
  77  }
  78  
  79  // SignWithContractsUnified is SignWithContracts with the XBT unified hash.
  80  func SignWithContractsUnified(
  81  	raw []byte, owned map[string]Key, contracts map[string][]byte, policy Policy,
  82  ) ([]byte, int, error) {
  83  	return sign(raw, owned, contracts, policy, true)
  84  }
  85  
  86  func sign(
  87  	raw []byte, owned map[string]Key, contracts map[string][]byte, policy Policy, unified bool,
  88  ) ([]byte, int, error) {
  89  	file, err := Read(raw)
  90  
  91  	if err != nil {
  92  		return nil, 0, err
  93  	}
  94  
  95  	transaction, err := tx.Decode(file.Unsigned)
  96  
  97  	if err != nil {
  98  		return nil, 0, fmt.Errorf("psbt: unsigned transaction: %w", err)
  99  	}
 100  
 101  	if len(file.Inputs) != len(transaction.Inputs) {
 102  		return nil, 0, fmt.Errorf(
 103  			"psbt: %d input maps for %d inputs", len(file.Inputs), len(transaction.Inputs),
 104  		)
 105  	}
 106  
 107  	if unified {
 108  		for index, input := range file.Inputs {
 109  			if len(input.ScriptPubKey) == 0 {
 110  				return nil, 0, fmt.Errorf(
 111  					"%w: input %d has no witness utxo, which the unified digest commits to",
 112  					ErrUnknownInput, index,
 113  				)
 114  			}
 115  		}
 116  	}
 117  
 118  	var partials []partialSignature
 119  
 120  	var walletSpend, totalIn uint64
 121  	known := true
 122  
 123  	// The unified digest commits to every input's value and scriptPubKey, not
 124  	// just the input being signed.
 125  	spent := make([]tx.SpentOutput, len(transaction.Inputs))
 126  
 127  	for index := range transaction.Inputs {
 128  		input := file.Inputs[index]
 129  
 130  		if len(input.ScriptPubKey) == 0 {
 131  			known = false
 132  
 133  			continue
 134  		}
 135  
 136  		spent[index] = tx.SpentOutput{Value: input.Amount, Script: input.ScriptPubKey}
 137  		totalIn += input.Amount
 138  
 139  		key, isOurs := owned[hex.EncodeToString(input.ScriptPubKey)]
 140  
 141  		if !isOurs {
 142  			continue
 143  		}
 144  
 145  		walletSpend += input.Amount
 146  
 147  		var (
 148  			der    []byte
 149  			pubkey []byte
 150  			err    error
 151  		)
 152  
 153  		if unified {
 154  			digest, digestErr := transaction.SighashUnifiedV0(
 155  				index, tx.P2WPKHScriptCode(key.Program), spent, tx.SighashAllUnified,
 156  			)
 157  			if digestErr != nil {
 158  				return nil, 0, fmt.Errorf("psbt: input %d unified sighash: %w", index, digestErr)
 159  			}
 160  
 161  			der, pubkey, err = tx.SignDigestWithType(
 162  				key.Secret, digest, byte(tx.SighashAllUnified),
 163  			)
 164  		} else {
 165  			digest, digestErr := transaction.SighashV0(
 166  				index, tx.P2WPKHScriptCode(key.Program), input.Amount, tx.SighashAll,
 167  			)
 168  			if digestErr != nil {
 169  				return nil, 0, fmt.Errorf("psbt: input %d sighash: %w", index, digestErr)
 170  			}
 171  
 172  			der, pubkey, err = tx.SignDigest(key.Secret, digest)
 173  		}
 174  
 175  		if err != nil {
 176  			return nil, 0, fmt.Errorf("psbt: input %d: %w", index, err)
 177  		}
 178  
 179  		recordKey := append([]byte{inputPartialSig}, pubkey...)
 180  		partials = append(partials, partialSignature{index: index, key: recordKey, value: der})
 181  	}
 182  
 183  	// A contract input is ours when the contract names a key we hold and the branch is
 184  	// available: a preimage that opens the hash claims, and only the refunder's key may take
 185  	// the refund branch, after its locktime.
 186  	for index := range transaction.Inputs {
 187  		input := file.Inputs[index]
 188  
 189  		if len(input.WitnessScript) == 0 || len(input.ScriptPubKey) == 0 {
 190  			continue
 191  		}
 192  
 193  		if !bytesEqual(input.ScriptPubKey, p2wsh(input.WitnessScript)) {
 194  			continue
 195  		}
 196  
 197  		terms, err := ParseHTLC(input.WitnessScript)
 198  
 199  		if err != nil {
 200  			continue
 201  		}
 202  
 203  		// The first pass already counted this input's value; only the wallet's share of the
 204  		// spend is new here.
 205  		if secret, ok := contracts[hex.EncodeToString(terms.Claimer)]; ok {
 206  			preimage := opensContract(input.Preimages, terms.SecretHash)
 207  
 208  			if preimage == nil {
 209  				return nil, 0, fmt.Errorf("%w: input %d needs the preimage to claim", ErrPolicy, index)
 210  			}
 211  
 212  			if unified {
 213  				if err := tx.SignHTLCClaimUnified(transaction, index, secret, input.WitnessScript, preimage, spent); err != nil {
 214  					return nil, 0, fmt.Errorf("psbt: input %d unified claim: %w", index, err)
 215  				}
 216  			} else if err := tx.SignHTLCClaim(transaction, index, secret, input.WitnessScript, preimage, input.Amount); err != nil {
 217  				return nil, 0, fmt.Errorf("psbt: input %d claim: %w", index, err)
 218  			}
 219  		} else if secret, ok := contracts[hex.EncodeToString(terms.Refunder)]; ok {
 220  			if transaction.LockTime < terms.Locktime {
 221  				return nil, 0, fmt.Errorf(
 222  					"%w: input %d refunds at %d, the transaction's locktime is %d",
 223  					ErrPolicy, index, terms.Locktime, transaction.LockTime,
 224  				)
 225  			}
 226  
 227  			if unified {
 228  				if err := tx.SignHTLCRefundUnified(transaction, index, secret, input.WitnessScript, spent); err != nil {
 229  					return nil, 0, fmt.Errorf("psbt: input %d unified refund: %w", index, err)
 230  				}
 231  			} else if err := tx.SignHTLCRefund(transaction, index, secret, input.WitnessScript, input.Amount); err != nil {
 232  				return nil, 0, fmt.Errorf("psbt: input %d refund: %w", index, err)
 233  			}
 234  		} else {
 235  			continue
 236  		}
 237  
 238  		walletSpend += input.Amount
 239  
 240  		record, err := witnessRecord(transaction.Inputs[index].Witness)
 241  
 242  		if err != nil {
 243  			return nil, 0, err
 244  		}
 245  
 246  		partials = append(partials, partialSignature{index: index, key: []byte{inputFinalWitness}, value: record})
 247  	}
 248  
 249  	if len(partials) == 0 {
 250  		return nil, 0, ErrNoOwnedInput
 251  	}
 252  
 253  	if policy.MaxSpend > 0 && walletSpend > policy.MaxSpend {
 254  		return nil, 0, fmt.Errorf(
 255  			"%w: this wallet would spend %d sat, the limit is %d", ErrPolicy, walletSpend, policy.MaxSpend,
 256  		)
 257  	}
 258  
 259  	if policy.MaxFee > 0 {
 260  		if !known {
 261  			return nil, 0, ErrUnknownInput
 262  		}
 263  
 264  		var totalOut uint64
 265  
 266  		for _, output := range transaction.Outputs {
 267  			totalOut += output.Value
 268  		}
 269  
 270  		if totalIn < totalOut {
 271  			return nil, 0, fmt.Errorf("%w: inputs %d below outputs %d", ErrPolicy, totalIn, totalOut)
 272  		}
 273  
 274  		if fee := totalIn - totalOut; fee > policy.MaxFee {
 275  			return nil, 0, fmt.Errorf(
 276  				"%w: the fee is %d sat, the limit is %d", ErrPolicy, fee, policy.MaxFee,
 277  			)
 278  		}
 279  	}
 280  
 281  	return encode(file, transaction, partials), len(partials), nil
 282  }
 283  
 284  // partialSignature is one signature to add to one input map.
 285  type partialSignature struct {
 286  	index int
 287  	key   []byte
 288  	value []byte
 289  }
 290  
 291  // encode writes the PSBT back with the partial signatures added.
 292  func encode(file *File, transaction *tx.Tx, partials []partialSignature) []byte {
 293  	byInput := make(map[int][]partialSignature, len(partials))
 294  
 295  	for _, p := range partials {
 296  		byInput[p.index] = append(byInput[p.index], p)
 297  	}
 298  
 299  	out := make([]byte, 0, len(file.Unsigned)+256)
 300  	out = append(out, magic...)
 301  
 302  	unsigned, err := transaction.Serialize()
 303  
 304  	if err != nil {
 305  		// Sign has already decoded these bytes; a transaction that encodes here cannot fail
 306  		// for any reason the caller could act on, but the empty PSBT would be worse than the
 307  		// original, so fall back to the bytes that were read.
 308  		unsigned = file.Unsigned
 309  	}
 310  
 311  	out = appendRecord(out, globalUnsignedTx, unsigned)
 312  	out = append(out, 0x00) // end of the global map
 313  
 314  	for index := range transaction.Inputs {
 315  		input := file.Inputs[index]
 316  
 317  		if len(input.ScriptPubKey) > 0 {
 318  			value := binary.LittleEndian.AppendUint64(nil, input.Amount)
 319  			value = append(value, compactSize(len(input.ScriptPubKey))...)
 320  			value = append(value, input.ScriptPubKey...)
 321  
 322  			out = appendRecord(out, inputWitnessUTXO, value)
 323  		}
 324  
 325  		if len(input.WitnessScript) > 0 {
 326  			out = appendRecord(out, inputWitnessScript, input.WitnessScript)
 327  		}
 328  
 329  		for _, preimage := range input.Preimages {
 330  			key := append([]byte{inputSHA256Preimage}, preimage.SecretHash[:]...)
 331  			out = appendKeyedRecord(out, key, preimage.Preimage)
 332  		}
 333  
 334  		for _, record := range byInput[index] {
 335  			out = appendKeyedRecord(out, record.key, record.value)
 336  		}
 337  
 338  		out = append(out, 0x00)
 339  	}
 340  
 341  	for i := 0; i < file.Outputs; i++ {
 342  		out = append(out, 0x00)
 343  	}
 344  
 345  	return out
 346  }
 347