package psbt import ( "encoding/binary" "encoding/hex" "errors" "fmt" "git.smesh.lol/tinywallet/pkg/tx" ) // The partial-signature record BIP174 defines. const inputPartialSig byte = 0x02 // Errors a signing request refuses. var ( // ErrNoOwnedInput is a PSBT with nothing in it that this wallet may sign. ErrNoOwnedInput = errors.New("psbt: no input pays this wallet") // ErrPolicy is a spend or fee above what the caller allowed. ErrPolicy = errors.New("psbt: the spend is above the policy") // ErrUnknownInput is an input whose value is not in the PSBT, which makes the fee // unknowable and therefore unenforceable. ErrUnknownInput = errors.New("psbt: an input has no witness utxo, so the fee is unknown") ) // Key is one address's signing material: the private key and the witness program it spends. type Key struct { // Secret is the 32-byte private key. Secret []byte // Program is the 20-byte P2WPKH witness program. Program [20]byte } // Policy is what a caller allows this signing request to do. // // The zero value refuses nothing except a PSBT with nothing of this wallet's in it, because a // caller that has not set a limit has not asked for one. A caller that sets a limit means it, // which is the point of passing one. type Policy struct { // MaxSpend is the largest total input value this wallet may contribute, in satoshis. MaxSpend uint64 // MaxFee is the largest fee the signed transaction may pay, in satoshis. MaxFee uint64 } // Sign signs every input of the PSBT whose witness UTXO pays one of the keys, and returns the // PSBT with those partial signatures added, and how many were added. // // The records it keeps are the ones this package writes — the unsigned transaction, each // input's witness UTXO, witness script and SHA-256 preimage — and the partial signatures it // adds. A record it does not understand is dropped rather than guessed at, which is why this // signer is for a PSBT this wallet or its own builder produced; another signer's proprietary // records belong to that signer. // // It does not finalise: a partial signature is what a PSBT carries, and finalising is the // caller's decision about fee and completeness. func Sign(raw []byte, owned map[string]Key, policy Policy) ([]byte, int, error) { return sign(raw, owned, nil, policy, false) } // SignUnified is Sign, but every signature opts into the XBT fork's unified // hash. The PSBT must carry every input's witness UTXO: the unified message // commits to every spent value and scriptPubKey. func SignUnified(raw []byte, owned map[string]Key, policy Policy) ([]byte, int, error) { return sign(raw, owned, nil, policy, true) } // SignWithContracts signs both the wallet's P2WPKH inputs and any contract input it can // finalise. contracts maps a compressed public key, as hex, to the secret that controls it. // // A contract input is finalised here rather than left for another signer: the claim needs the // preimage, which the caller put in the PSBT, and the refund needs the locktime to have passed, // and the wallet is the only party that can decide both. The result is a final scriptWitness // record, so a plain finalisepsbt assembles the transaction. func SignWithContracts(raw []byte, owned map[string]Key, contracts map[string][]byte, policy Policy) ([]byte, int, error) { return sign(raw, owned, contracts, policy, false) } // SignWithContractsUnified is SignWithContracts with the XBT unified hash. func SignWithContractsUnified( raw []byte, owned map[string]Key, contracts map[string][]byte, policy Policy, ) ([]byte, int, error) { return sign(raw, owned, contracts, policy, true) } func sign( raw []byte, owned map[string]Key, contracts map[string][]byte, policy Policy, unified bool, ) ([]byte, int, error) { file, err := Read(raw) if err != nil { return nil, 0, err } transaction, err := tx.Decode(file.Unsigned) if err != nil { return nil, 0, fmt.Errorf("psbt: unsigned transaction: %w", err) } if len(file.Inputs) != len(transaction.Inputs) { return nil, 0, fmt.Errorf( "psbt: %d input maps for %d inputs", len(file.Inputs), len(transaction.Inputs), ) } if unified { for index, input := range file.Inputs { if len(input.ScriptPubKey) == 0 { return nil, 0, fmt.Errorf( "%w: input %d has no witness utxo, which the unified digest commits to", ErrUnknownInput, index, ) } } } var partials []partialSignature var walletSpend, totalIn uint64 known := true // The unified digest commits to every input's value and scriptPubKey, not // just the input being signed. spent := make([]tx.SpentOutput, len(transaction.Inputs)) for index := range transaction.Inputs { input := file.Inputs[index] if len(input.ScriptPubKey) == 0 { known = false continue } spent[index] = tx.SpentOutput{Value: input.Amount, Script: input.ScriptPubKey} totalIn += input.Amount key, isOurs := owned[hex.EncodeToString(input.ScriptPubKey)] if !isOurs { continue } walletSpend += input.Amount var ( der []byte pubkey []byte err error ) if unified { digest, digestErr := transaction.SighashUnifiedV0( index, tx.P2WPKHScriptCode(key.Program), spent, tx.SighashAllUnified, ) if digestErr != nil { return nil, 0, fmt.Errorf("psbt: input %d unified sighash: %w", index, digestErr) } der, pubkey, err = tx.SignDigestWithType( key.Secret, digest, byte(tx.SighashAllUnified), ) } else { digest, digestErr := transaction.SighashV0( index, tx.P2WPKHScriptCode(key.Program), input.Amount, tx.SighashAll, ) if digestErr != nil { return nil, 0, fmt.Errorf("psbt: input %d sighash: %w", index, digestErr) } der, pubkey, err = tx.SignDigest(key.Secret, digest) } if err != nil { return nil, 0, fmt.Errorf("psbt: input %d: %w", index, err) } recordKey := append([]byte{inputPartialSig}, pubkey...) partials = append(partials, partialSignature{index: index, key: recordKey, value: der}) } // A contract input is ours when the contract names a key we hold and the branch is // available: a preimage that opens the hash claims, and only the refunder's key may take // the refund branch, after its locktime. for index := range transaction.Inputs { input := file.Inputs[index] if len(input.WitnessScript) == 0 || len(input.ScriptPubKey) == 0 { continue } if !bytesEqual(input.ScriptPubKey, p2wsh(input.WitnessScript)) { continue } terms, err := ParseHTLC(input.WitnessScript) if err != nil { continue } // The first pass already counted this input's value; only the wallet's share of the // spend is new here. if secret, ok := contracts[hex.EncodeToString(terms.Claimer)]; ok { preimage := opensContract(input.Preimages, terms.SecretHash) if preimage == nil { return nil, 0, fmt.Errorf("%w: input %d needs the preimage to claim", ErrPolicy, index) } if unified { if err := tx.SignHTLCClaimUnified(transaction, index, secret, input.WitnessScript, preimage, spent); err != nil { return nil, 0, fmt.Errorf("psbt: input %d unified claim: %w", index, err) } } else if err := tx.SignHTLCClaim(transaction, index, secret, input.WitnessScript, preimage, input.Amount); err != nil { return nil, 0, fmt.Errorf("psbt: input %d claim: %w", index, err) } } else if secret, ok := contracts[hex.EncodeToString(terms.Refunder)]; ok { if transaction.LockTime < terms.Locktime { return nil, 0, fmt.Errorf( "%w: input %d refunds at %d, the transaction's locktime is %d", ErrPolicy, index, terms.Locktime, transaction.LockTime, ) } if unified { if err := tx.SignHTLCRefundUnified(transaction, index, secret, input.WitnessScript, spent); err != nil { return nil, 0, fmt.Errorf("psbt: input %d unified refund: %w", index, err) } } else if err := tx.SignHTLCRefund(transaction, index, secret, input.WitnessScript, input.Amount); err != nil { return nil, 0, fmt.Errorf("psbt: input %d refund: %w", index, err) } } else { continue } walletSpend += input.Amount record, err := witnessRecord(transaction.Inputs[index].Witness) if err != nil { return nil, 0, err } partials = append(partials, partialSignature{index: index, key: []byte{inputFinalWitness}, value: record}) } if len(partials) == 0 { return nil, 0, ErrNoOwnedInput } if policy.MaxSpend > 0 && walletSpend > policy.MaxSpend { return nil, 0, fmt.Errorf( "%w: this wallet would spend %d sat, the limit is %d", ErrPolicy, walletSpend, policy.MaxSpend, ) } if policy.MaxFee > 0 { if !known { return nil, 0, ErrUnknownInput } var totalOut uint64 for _, output := range transaction.Outputs { totalOut += output.Value } if totalIn < totalOut { return nil, 0, fmt.Errorf("%w: inputs %d below outputs %d", ErrPolicy, totalIn, totalOut) } if fee := totalIn - totalOut; fee > policy.MaxFee { return nil, 0, fmt.Errorf( "%w: the fee is %d sat, the limit is %d", ErrPolicy, fee, policy.MaxFee, ) } } return encode(file, transaction, partials), len(partials), nil } // partialSignature is one signature to add to one input map. type partialSignature struct { index int key []byte value []byte } // encode writes the PSBT back with the partial signatures added. func encode(file *File, transaction *tx.Tx, partials []partialSignature) []byte { byInput := make(map[int][]partialSignature, len(partials)) for _, p := range partials { byInput[p.index] = append(byInput[p.index], p) } out := make([]byte, 0, len(file.Unsigned)+256) out = append(out, magic...) unsigned, err := transaction.Serialize() if err != nil { // Sign has already decoded these bytes; a transaction that encodes here cannot fail // for any reason the caller could act on, but the empty PSBT would be worse than the // original, so fall back to the bytes that were read. unsigned = file.Unsigned } out = appendRecord(out, globalUnsignedTx, unsigned) out = append(out, 0x00) // end of the global map for index := range transaction.Inputs { input := file.Inputs[index] if len(input.ScriptPubKey) > 0 { value := binary.LittleEndian.AppendUint64(nil, input.Amount) value = append(value, compactSize(len(input.ScriptPubKey))...) value = append(value, input.ScriptPubKey...) out = appendRecord(out, inputWitnessUTXO, value) } if len(input.WitnessScript) > 0 { out = appendRecord(out, inputWitnessScript, input.WitnessScript) } for _, preimage := range input.Preimages { key := append([]byte{inputSHA256Preimage}, preimage.SecretHash[:]...) out = appendKeyedRecord(out, key, preimage.Preimage) } for _, record := range byInput[index] { out = appendKeyedRecord(out, record.key, record.value) } out = append(out, 0x00) } for i := 0; i < file.Outputs; i++ { out = append(out, 0x00) } return out }