input

package
v0.17.4-beta.rc1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 30, 2024 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// P2WPKHSize 22 bytes
	//	- OP_0: 1 byte
	//	- OP_DATA: 1 byte (PublicKeyHASH160 length)
	//	- PublicKeyHASH160: 20 bytes
	P2WPKHSize = 1 + 1 + 20

	// NestedP2WPKHSize 23 bytes
	//      - OP_DATA: 1 byte (P2WPKHSize)
	//      - P2WPKHWitnessProgram: 22 bytes
	NestedP2WPKHSize = 1 + P2WPKHSize

	// P2WSHSize 34 bytes
	//	- OP_0: 1 byte
	//	- OP_DATA: 1 byte (WitnessScriptSHA256 length)
	//	- WitnessScriptSHA256: 32 bytes
	P2WSHSize = 1 + 1 + 32

	// NestedP2WSHSize 35 bytes
	//      - OP_DATA: 1 byte (P2WSHSize)
	//      - P2WSHWitnessProgram: 34 bytes
	NestedP2WSHSize = 1 + P2WSHSize

	// UnknownWitnessSize 42 bytes
	//      - OP_x: 1 byte
	//      - OP_DATA: 1 byte (max-size length)
	//      - max-size: 40 bytes
	UnknownWitnessSize = 1 + 1 + 40

	// P2PKHSize 25 bytes.
	P2PKHSize = 25

	// P2PKHOutputSize 34 bytes
	//      - value: 8 bytes
	//      - var_int: 1 byte (pkscript_length)
	//      - pkscript (p2pkh): 25 bytes
	P2PKHOutputSize = 8 + 1 + P2PKHSize

	// P2WKHOutputSize 31 bytes
	//      - value: 8 bytes
	//      - var_int: 1 byte (pkscript_length)
	//      - pkscript (p2wpkh): 22 bytes
	P2WKHOutputSize = 8 + 1 + P2WPKHSize

	// P2WSHOutputSize 43 bytes
	//      - value: 8 bytes
	//      - var_int: 1 byte (pkscript_length)
	//      - pkscript (p2wsh): 34 bytes
	P2WSHOutputSize = 8 + 1 + P2WSHSize

	// P2SHSize 23 bytes.
	P2SHSize = 23

	// P2SHOutputSize 32 bytes
	//      - value: 8 bytes
	//      - var_int: 1 byte (pkscript_length)
	//      - pkscript (p2sh): 23 bytes
	P2SHOutputSize = 8 + 1 + P2SHSize

	// P2TRSize 34 bytes
	//	- OP_0: 1 byte
	//	- OP_DATA: 1 byte (x-only public key length)
	//	- x-only public key length: 32 bytes
	P2TRSize = 34

	// P2TROutputSize 43 bytes
	//      - value: 8 bytes
	//      - var_int: 1 byte (pkscript_length)
	//      - pkscript (p2tr): 34 bytes
	P2TROutputSize = 8 + 1 + P2TRSize

	// P2PKHScriptSigSize 108 bytes
	//      - OP_DATA: 1 byte (signature length)
	//      - signature
	//      - OP_DATA: 1 byte (pubkey length)
	//      - pubkey
	P2PKHScriptSigSize = 1 + 73 + 1 + 33

	// P2WKHWitnessSize 109 bytes
	//      - number_of_witness_elements: 1 byte
	//      - signature_length: 1 byte
	//      - signature
	//      - pubkey_length: 1 byte
	//      - pubkey
	P2WKHWitnessSize = 1 + 1 + 73 + 1 + 33

	// MultiSigSize 71 bytes
	//	- OP_2: 1 byte
	//	- OP_DATA: 1 byte (pubKeyAlice length)
	//	- pubKeyAlice: 33 bytes
	//	- OP_DATA: 1 byte (pubKeyBob length)
	//	- pubKeyBob: 33 bytes
	//	- OP_2: 1 byte
	//	- OP_CHECKMULTISIG: 1 byte
	MultiSigSize = 1 + 1 + 33 + 1 + 33 + 1 + 1

	// MultiSigWitnessSize 222 bytes
	//	- NumberOfWitnessElements: 1 byte
	//	- NilLength: 1 byte
	//	- sigAliceLength: 1 byte
	//	- sigAlice: 73 bytes
	//	- sigBobLength: 1 byte
	//	- sigBob: 73 bytes
	//	- WitnessScriptLength: 1 byte
	//	- WitnessScript (MultiSig)
	MultiSigWitnessSize = 1 + 1 + 1 + 73 + 1 + 73 + 1 + MultiSigSize

	// InputSize 41 bytes
	//	- PreviousOutPoint:
	//		- Hash: 32 bytes
	//		- Index: 4 bytes
	//	- OP_DATA: 1 byte (ScriptSigLength)
	//	- ScriptSig: 0 bytes
	//	- Witness <----	we use "Witness" instead of "ScriptSig" for
	// 			transaction validation, but "Witness" is stored
	// 			separately and weight for it size is smaller. So
	// 			we separate the calculation of ordinary data
	// 			from witness data.
	//	- Sequence: 4 bytes
	InputSize = 32 + 4 + 1 + 4

	// FundingInputSize 41 bytes
	// FundingInputSize represents the size of an input to a funding
	// transaction, and is equivalent to the size of a standard segwit input
	// as calculated above.
	FundingInputSize = InputSize

	// CommitmentDelayOutput 43 bytes
	//	- Value: 8 bytes
	//	- VarInt: 1 byte (PkScript length)
	//	- PkScript (P2WSH)
	CommitmentDelayOutput = 8 + 1 + P2WSHSize

	// TaprootCommitmentOutput 43 bytes
	//	- Value: 8 bytes
	//	- VarInt: 1 byte (PkScript length)
	//	- PkScript (P2TR)
	TaprootCommitmentOutput = 8 + 1 + P2TRSize

	// CommitmentKeyHashOutput 31 bytes
	//	- Value: 8 bytes
	//	- VarInt: 1 byte (PkScript length)
	//	- PkScript (P2WPKH)
	CommitmentKeyHashOutput = 8 + 1 + P2WPKHSize

	// CommitmentAnchorOutput 43 bytes
	//	- Value: 8 bytes
	//	- VarInt: 1 byte (PkScript length)
	//	- PkScript (P2WSH)
	CommitmentAnchorOutput = 8 + 1 + P2WSHSize

	// TaprootCommitmentAnchorOutput 43 bytes
	//	- Value: 8 bytes
	//	- VarInt: 1 byte (PkScript length)
	//	- PkScript (P2TR)
	TaprootCommitmentAnchorOutput = 8 + 1 + P2TRSize

	// HTLCSize 43 bytes
	//	- Value: 8 bytes
	//	- VarInt: 1 byte (PkScript length)
	//	- PkScript (PW2SH)
	HTLCSize = 8 + 1 + P2WSHSize

	// WitnessHeaderSize 2 bytes
	//	- Flag: 1 byte
	//	- Marker: 1 byte
	WitnessHeaderSize = 1 + 1

	// BaseTxSize 8 bytes
	//      - Version: 4 bytes
	//      - LockTime: 4 bytes
	BaseTxSize = 4 + 4

	// BaseCommitmentTxSize 125 + 43 * num-htlc-outputs bytes
	//	- Version: 4 bytes
	//	- WitnessHeader <---- part of the witness data
	//	- CountTxIn: 1 byte
	//	- TxIn: 41 bytes
	//		FundingInput
	//	- CountTxOut: 1 byte
	//	- TxOut: 74 + 43 * num-htlc-outputs bytes
	//		OutputPayingToThem,
	//		OutputPayingToUs,
	//		....HTLCOutputs...
	//	- LockTime: 4 bytes
	BaseCommitmentTxSize = 4 + 1 + FundingInputSize + 1 +
		CommitmentDelayOutput + CommitmentKeyHashOutput + 4

	// BaseCommitmentTxWeight 500 weight
	BaseCommitmentTxWeight = witnessScaleFactor * BaseCommitmentTxSize

	// WitnessCommitmentTxWeight 224 weight
	WitnessCommitmentTxWeight = WitnessHeaderSize + MultiSigWitnessSize

	// BaseAnchorCommitmentTxSize 225 + 43 * num-htlc-outputs bytes
	//	- Version: 4 bytes
	//	- WitnessHeader <---- part of the witness data
	//	- CountTxIn: 1 byte
	//	- TxIn: 41 bytes
	//		FundingInput
	//	- CountTxOut: 3 byte
	//	- TxOut: 4*43 + 43 * num-htlc-outputs bytes
	//		OutputPayingToThem,
	//		OutputPayingToUs,
	//		AnchorPayingToThem,
	//		AnchorPayingToUs,
	//		....HTLCOutputs...
	//	- LockTime: 4 bytes
	BaseAnchorCommitmentTxSize = 4 + 1 + FundingInputSize + 3 +
		2*CommitmentDelayOutput + 2*CommitmentAnchorOutput + 4

	// BaseAnchorCommitmentTxWeight 900 weight.
	BaseAnchorCommitmentTxWeight = witnessScaleFactor * BaseAnchorCommitmentTxSize

	// BaseTaprootCommitmentTxWeight 225 + 43 * num-htlc-outputs bytes
	//	- Version: 4 bytes
	//	- WitnessHeader <---- part of the witness data
	//	- CountTxIn: 1 byte
	//	- TxIn: 41 bytes
	//		FundingInput
	//	- CountTxOut: 3 byte
	//	- TxOut: 172 + 43 * num-htlc-outputs bytes
	//		OutputPayingToThem,
	//		OutputPayingToUs,
	//		....HTLCOutputs...
	//	- LockTime: 4 bytes
	BaseTaprootCommitmentTxWeight = (4 + 1 + FundingInputSize + 3 +
		2*TaprootCommitmentOutput + 2*TaprootCommitmentAnchorOutput +
		4) * witnessScaleFactor

	// CommitWeight 724 weight.
	CommitWeight = BaseCommitmentTxWeight + WitnessCommitmentTxWeight

	// AnchorCommitWeight 1124 weight.
	AnchorCommitWeight = BaseAnchorCommitmentTxWeight + WitnessCommitmentTxWeight

	// TaprootCommitWeight 968 weight.
	TaprootCommitWeight = (BaseTaprootCommitmentTxWeight +
		WitnessHeaderSize + TaprootKeyPathWitnessSize)

	// HTLCWeight 172 weight.
	HTLCWeight = witnessScaleFactor * HTLCSize

	// HtlcTimeoutWeight 663 weight
	// HtlcTimeoutWeight is the weight of the HTLC timeout transaction
	// which will transition an outgoing HTLC to the delay-and-claim state.
	HtlcTimeoutWeight = 663

	// TaprootHtlcTimeoutWeight is the total weight of the taproot HTLC
	// timeout transaction.
	TaprootHtlcTimeoutWeight = 645

	// HtlcSuccessWeight 703 weight
	// HtlcSuccessWeight is the weight of the HTLC success transaction
	// which will transition an incoming HTLC to the delay-and-claim state.
	HtlcSuccessWeight = 703

	// TaprootHtlcSuccessWeight is the total weight of the taproot HTLC
	// success transaction.
	TaprootHtlcSuccessWeight = 705

	// HtlcConfirmedScriptOverhead 3 bytes
	// HtlcConfirmedScriptOverhead is the extra length of an HTLC script
	// that requires confirmation before it can be spent. These extra bytes
	// is a result of the extra CSV check.
	HtlcConfirmedScriptOverhead = 3

	// HtlcTimeoutWeightConfirmed 666 weight
	// HtlcTimeoutWeightConfirmed is the weight of the HTLC timeout
	// transaction which will transition an outgoing HTLC to the
	// delay-and-claim state, for the confirmed HTLC outputs. It is 3 bytes
	// larger because of the additional CSV check in the input script.
	HtlcTimeoutWeightConfirmed = HtlcTimeoutWeight + HtlcConfirmedScriptOverhead

	// HtlcSuccessWeightConfirmed 706 weight
	// HtlcSuccessWeightConfirmed is the weight of the HTLC success
	// transaction which will transition an incoming HTLC to the
	// delay-and-claim state, for the confirmed HTLC outputs. It is 3 bytes
	// larger because of the cdditional CSV check in the input script.
	HtlcSuccessWeightConfirmed = HtlcSuccessWeight + HtlcConfirmedScriptOverhead

	// MaxHTLCNumber 966
	// MaxHTLCNumber is the maximum number HTLCs which can be included in a
	// commitment transaction. This limit was chosen such that, in the case
	// of a contract breach, the punishment transaction is able to sweep
	// all the HTLC's yet still remain below the widely used standard
	// weight limits.
	MaxHTLCNumber = 966

	// ToLocalScriptSize 79 bytes
	//      - OP_IF: 1 byte
	//          - OP_DATA: 1 byte
	//          - revoke_key: 33 bytes
	//      - OP_ELSE: 1 byte
	//          - OP_DATA: 1 byte
	//          - csv_delay: 4 bytes
	//          - OP_CHECKSEQUENCEVERIFY: 1 byte
	//          - OP_DROP: 1 byte
	//          - OP_DATA: 1 byte
	//          - delay_key: 33 bytes
	//      - OP_ENDIF: 1 byte
	//      - OP_CHECKSIG: 1 byte
	ToLocalScriptSize = 1 + 1 + 33 + 1 + 1 + 4 + 1 + 1 + 1 + 33 + 1 + 1

	// LeaseWitnessScriptSizeOverhead represents the size overhead in bytes
	// of the witness scripts used within script enforced lease commitments.
	// This overhead results from the additional CLTV clause required to
	// spend.
	//
	//	- OP_DATA: 1 byte
	// 	- lease_expiry: 4 bytes
	// 	- OP_CHECKLOCKTIMEVERIFY: 1 byte
	// 	- OP_DROP: 1 byte
	LeaseWitnessScriptSizeOverhead = 1 + 4 + 1 + 1

	// ToLocalTimeoutWitnessSize 156 bytes
	//      - number_of_witness_elements: 1 byte
	//      - local_delay_sig_length: 1 byte
	//      - local_delay_sig: 73 bytes
	//      - zero_length: 1 byte
	//      - witness_script_length: 1 byte
	//      - witness_script (to_local_script)
	ToLocalTimeoutWitnessSize = 1 + 1 + 73 + 1 + 1 + ToLocalScriptSize

	// ToLocalPenaltyWitnessSize 157 bytes
	//      - number_of_witness_elements: 1 byte
	//      - revocation_sig_length: 1 byte
	//      - revocation_sig: 73 bytes
	//      - OP_TRUE_length: 1 byte
	//      - OP_TRUE: 1 byte
	//      - witness_script_length: 1 byte
	//      - witness_script (to_local_script)
	ToLocalPenaltyWitnessSize = 1 + 1 + 73 + 1 + 1 + 1 + ToLocalScriptSize

	// ToRemoteConfirmedScriptSize 37 bytes
	//      - OP_DATA: 1 byte
	//      - to_remote_key: 33 bytes
	//      - OP_CHECKSIGVERIFY: 1 byte
	//      - OP_1: 1 byte
	//      - OP_CHECKSEQUENCEVERIFY: 1 byte
	ToRemoteConfirmedScriptSize = 1 + 33 + 1 + 1 + 1

	// ToRemoteConfirmedWitnessSize 113 bytes
	//      - number_of_witness_elements: 1 byte
	//      - sig_length: 1 byte
	//      - sig: 73 bytes
	//      - witness_script_length: 1 byte
	//      - witness_script (to_remote_delayed_script)
	ToRemoteConfirmedWitnessSize = 1 + 1 + 73 + 1 + ToRemoteConfirmedScriptSize

	// AcceptedHtlcScriptSize 140 bytes
	//      - OP_DUP: 1 byte
	//      - OP_HASH160: 1 byte
	//      - OP_DATA: 1 byte (RIPEMD160(SHA256(revocationkey)) length)
	//      - RIPEMD160(SHA256(revocationkey)): 20 bytes
	//      - OP_EQUAL: 1 byte
	//      - OP_IF: 1 byte
	//              - OP_CHECKSIG: 1 byte
	//      - OP_ELSE: 1 byte
	//              - OP_DATA: 1 byte (remotekey length)
	//              - remotekey: 33 bytes
	//              - OP_SWAP: 1 byte
	//              - OP_SIZE: 1 byte
	//              - OP_DATA: 1 byte (32 length)
	//              - 32: 1 byte
	//              - OP_EQUAL: 1 byte
	//              - OP_IF: 1 byte
	//                      - OP_HASH160: 1 byte
	//                      - OP_DATA: 1 byte (RIPEMD160(payment_hash) length)
	//                      - RIPEMD160(payment_hash): 20 bytes
	//                      - OP_EQUALVERIFY: 1 byte
	//                      - 2: 1 byte
	//                      - OP_SWAP: 1 byte
	//                      - OP_DATA: 1 byte (localkey length)
	//                      - localkey: 33 bytes
	//                      - 2: 1 byte
	//                      - OP_CHECKMULTISIG: 1 byte
	//              - OP_ELSE: 1 byte
	//                      - OP_DROP: 1 byte
	//                      - OP_DATA: 1 byte (cltv_expiry length)
	//                      - cltv_expiry: 4 bytes
	//                      - OP_CHECKLOCKTIMEVERIFY: 1 byte
	//                      - OP_DROP: 1 byte
	//                      - OP_CHECKSIG: 1 byte
	//              - OP_ENDIF: 1 byte
	//              - OP_1: 1 byte		// These 3 extra bytes are only
	//              - OP_CSV: 1 byte	// present for the confirmed
	//              - OP_DROP: 1 byte	// HTLC script types.
	//      - OP_ENDIF: 1 byte
	AcceptedHtlcScriptSize = 3*1 + 20 + 5*1 + 33 + 8*1 + 20 + 4*1 +
		33 + 5*1 + 4 + 5*1

	// AcceptedHtlcScriptSizeConfirmed 143 bytes.
	AcceptedHtlcScriptSizeConfirmed = AcceptedHtlcScriptSize +
		HtlcConfirmedScriptOverhead

	// AcceptedHtlcTimeoutWitnessSize 217 bytes
	//      - number_of_witness_elements: 1 byte
	//      - sender_sig_length: 1 byte
	//      - sender_sig: 73 bytes
	//      - nil_length: 1 byte
	//      - witness_script_length: 1 byte
	//      - witness_script: (accepted_htlc_script)
	AcceptedHtlcTimeoutWitnessSize = 1 + 1 + 73 + 1 + 1 + AcceptedHtlcScriptSize

	// AcceptedHtlcTimeoutWitnessSizeConfirmed 220 bytes.
	AcceptedHtlcTimeoutWitnessSizeConfirmed = 1 + 1 + 73 + 1 + 1 +
		AcceptedHtlcScriptSizeConfirmed

	// AcceptedHtlcPenaltyWitnessSize 250 bytes
	//      - number_of_witness_elements: 1 byte
	//      - revocation_sig_length: 1 byte
	//      - revocation_sig: 73 bytes
	//      - revocation_key_length: 1 byte
	//      - revocation_key: 33 bytes
	//      - witness_script_length: 1 byte
	//      - witness_script (accepted_htlc_script)
	AcceptedHtlcPenaltyWitnessSize = 1 + 1 + 73 + 1 + 33 + 1 + AcceptedHtlcScriptSize

	// AcceptedHtlcPenaltyWitnessSizeConfirmed 253 bytes.
	AcceptedHtlcPenaltyWitnessSizeConfirmed = 1 + 1 + 73 + 1 + 33 + 1 +
		AcceptedHtlcScriptSizeConfirmed

	// AcceptedHtlcSuccessWitnessSize 324 bytes
	//      - number_of_witness_elements: 1 byte
	//      - nil_length: 1 byte
	//      - sig_alice_length: 1 byte
	//      - sig_alice: 73 bytes
	//      - sig_bob_length: 1 byte
	//      - sig_bob: 73 bytes
	//      - preimage_length: 1 byte
	//      - preimage: 32 bytes
	//      - witness_script_length: 1 byte
	//      - witness_script (accepted_htlc_script)
	//
	// Input to second level success tx, spending non-delayed HTLC output.
	AcceptedHtlcSuccessWitnessSize = 1 + 1 + 1 + 73 + 1 + 73 + 1 + 32 + 1 +
		AcceptedHtlcScriptSize

	// AcceptedHtlcSuccessWitnessSizeConfirmed 327 bytes
	//
	// Input to second level success tx, spending 1 CSV delayed HTLC output.
	AcceptedHtlcSuccessWitnessSizeConfirmed = 1 + 1 + 1 + 73 + 1 + 73 + 1 + 32 + 1 +
		AcceptedHtlcScriptSizeConfirmed

	// OfferedHtlcScriptSize 133 bytes
	//      - OP_DUP: 1 byte
	//      - OP_HASH160: 1 byte
	//      - OP_DATA: 1 byte (RIPEMD160(SHA256(revocationkey)) length)
	//      - RIPEMD160(SHA256(revocationkey)): 20 bytes
	//      - OP_EQUAL: 1 byte
	//      - OP_IF: 1 byte
	//              - OP_CHECKSIG: 1 byte
	//      - OP_ELSE: 1 byte
	//              - OP_DATA: 1 byte (remotekey length)
	//              - remotekey: 33 bytes
	//              - OP_SWAP: 1 byte
	//              - OP_SIZE: 1 byte
	//              - OP_DATA: 1 byte (32 length)
	//              - 32: 1 byte
	//              - OP_EQUAL: 1 byte
	//              - OP_NOTIF: 1 byte
	//                      - OP_DROP: 1 byte
	//                      - 2: 1 byte
	//                      - OP_SWAP: 1 byte
	//                      - OP_DATA: 1 byte (localkey length)
	//                      - localkey: 33 bytes
	//                      - 2: 1 byte
	//                      - OP_CHECKMULTISIG: 1 byte
	//              - OP_ELSE: 1 byte
	//                      - OP_HASH160: 1 byte
	//                      - OP_DATA: 1 byte (RIPEMD160(payment_hash) length)
	//                      - RIPEMD160(payment_hash): 20 bytes
	//                      - OP_EQUALVERIFY: 1 byte
	//                      - OP_CHECKSIG: 1 byte
	//              - OP_ENDIF: 1 byte
	//              - OP_1: 1 byte		// These 3 extra bytes are only
	//              - OP_CSV: 1 byte	// present for the confirmed
	//              - OP_DROP: 1 byte	// HTLC script types.
	//      - OP_ENDIF: 1 byte
	OfferedHtlcScriptSize = 3*1 + 20 + 5*1 + 33 + 10*1 + 33 + 5*1 + 20 + 4*1

	// OfferedHtlcScriptSizeConfirmed 136 bytes.
	OfferedHtlcScriptSizeConfirmed = OfferedHtlcScriptSize +
		HtlcConfirmedScriptOverhead

	// OfferedHtlcSuccessWitnessSize 242 bytes
	//      - number_of_witness_elements: 1 byte
	//      - receiver_sig_length: 1 byte
	//      - receiver_sig: 73 bytes
	//      - payment_preimage_length: 1 byte
	//      - payment_preimage: 32 bytes
	//      - witness_script_length: 1 byte
	//      - witness_script (offered_htlc_script)
	OfferedHtlcSuccessWitnessSize = 1 + 1 + 73 + 1 + 32 + 1 + OfferedHtlcScriptSize

	// OfferedHtlcSuccessWitnessSizeConfirmed 245 bytes.
	OfferedHtlcSuccessWitnessSizeConfirmed = 1 + 1 + 73 + 1 + 32 + 1 +
		OfferedHtlcScriptSizeConfirmed

	// OfferedHtlcTimeoutWitnessSize 285 bytes
	//      - number_of_witness_elements: 1 byte
	//      - nil_length: 1 byte
	//      - sig_alice_length: 1 byte
	//      - sig_alice: 73 bytes
	//      - sig_bob_length: 1 byte
	//      - sig_bob: 73 bytes
	//      - nil_length: 1 byte
	//      - witness_script_length: 1 byte
	//      - witness_script (offered_htlc_script)
	//
	// Input to second level timeout tx, spending non-delayed HTLC output.
	OfferedHtlcTimeoutWitnessSize = 1 + 1 + 1 + 73 + 1 + 73 + 1 + 1 +
		OfferedHtlcScriptSize

	// OfferedHtlcTimeoutWitnessSizeConfirmed 288 bytes
	//
	// Input to second level timeout tx, spending 1 CSV delayed HTLC output.
	OfferedHtlcTimeoutWitnessSizeConfirmed = 1 + 1 + 1 + 73 + 1 + 73 + 1 + 1 +
		OfferedHtlcScriptSizeConfirmed

	// OfferedHtlcPenaltyWitnessSize 243 bytes
	//      - number_of_witness_elements: 1 byte
	//      - revocation_sig_length: 1 byte
	//      - revocation_sig: 73 bytes
	//      - revocation_key_length: 1 byte
	//      - revocation_key: 33 bytes
	//      - witness_script_length: 1 byte
	//      - witness_script (offered_htlc_script)
	OfferedHtlcPenaltyWitnessSize = 1 + 1 + 73 + 1 + 33 + 1 + OfferedHtlcScriptSize

	// OfferedHtlcPenaltyWitnessSizeConfirmed 246 bytes.
	OfferedHtlcPenaltyWitnessSizeConfirmed = 1 + 1 + 73 + 1 + 33 + 1 +
		OfferedHtlcScriptSizeConfirmed

	// AnchorScriptSize 40 bytes
	//      - pubkey_length: 1 byte
	//      - pubkey: 33 bytes
	//      - OP_CHECKSIG: 1 byte
	//      - OP_IFDUP: 1 byte
	//      - OP_NOTIF: 1 byte
	//              - OP_16: 1 byte
	//              - OP_CSV 1 byte
	//      - OP_ENDIF: 1 byte
	AnchorScriptSize = 1 + 33 + 6*1

	// AnchorWitnessSize 116 bytes
	//      - number_of_witnes_elements: 1 byte
	//      - signature_length: 1 byte
	//      - signature: 73 bytes
	//      - witness_script_length: 1 byte
	//      - witness_script (anchor_script)
	AnchorWitnessSize = 1 + 1 + 73 + 1 + AnchorScriptSize

	// TaprootSignatureWitnessSize 65 bytes
	//	- sigLength: 1 byte
	//	- sig: 64 bytes
	TaprootSignatureWitnessSize = 1 + 64

	// TaprootKeyPathWitnessSize 66 bytes
	//	- NumberOfWitnessElements: 1 byte
	//	- sigLength: 1 byte
	//	- sig: 64 bytes
	TaprootKeyPathWitnessSize = 1 + TaprootSignatureWitnessSize

	// TaprootKeyPathCustomSighashWitnessSize 67 bytes
	//	- NumberOfWitnessElements: 1 byte
	//	- sigLength: 1 byte
	//	- sig: 64 bytes
	//      - sighashFlag: 1 byte
	TaprootKeyPathCustomSighashWitnessSize = TaprootKeyPathWitnessSize + 1

	// TaprootBaseControlBlockWitnessSize 33 bytes
	//      - leafVersionAndParity: 1 byte
	//      - schnorrPubKey: 32 byte
	TaprootBaseControlBlockWitnessSize = 33

	// TaprootToLocalScriptSize
	//      - OP_DATA: 1 byte (pub key len)
	//      - local_key: 32 bytes
	//      - OP_CHECKSIG: 1 byte
	//      - OP_DATA: 1 byte (csv delay)
	//      - csv_delay: 4 bytes (worst case estimate)
	//      - OP_CSV: 1 byte
	//      - OP_DROP: 1 byte
	TaprootToLocalScriptSize = 41

	// TaprootToLocalWitnessSize: 175 bytes
	//      - number_of_witness_elements: 1 byte
	//      - sig_len: 1 byte
	//      - sweep_sig: 65 bytes (worst case w/o sighash default)
	//      - script_len: 1 byte
	//      - taproot_to_local_script_size: 41 bytes
	//      - ctrl_block_len: 1 byte
	//      - base_control_block_size: 33 bytes
	//      - sibling_merkle_hash: 32 bytes
	TaprootToLocalWitnessSize = 1 + 1 + 65 + 1 + TaprootToLocalScriptSize +
		1 + TaprootBaseControlBlockWitnessSize + 32

	// TaprootToLocalRevokeScriptSize: 68 bytes
	//	- OP_DATA: 1 byte
	//	- local key: 32 bytes
	// 	- OP_DROP: 1 byte
	// 	- OP_DATA: 1 byte
	// 	- revocation key: 32 bytes
	// 	- OP_CHECKSIG: 1 byte
	TaprootToLocalRevokeScriptSize = 1 + 32 + 1 + 1 + 32 + 1

	// TaprootToLocalRevokeWitnessSize: 202 bytes
	// 	- NumberOfWitnessElements: 1 byte
	// 	- sigLength: 1 byte
	// 	- sweep sig: 65 bytes
	// 	- script len: 1 byte
	// 	- revocation script size: 68 bytes
	// 	- ctrl block size: 1 byte
	// 	- base control block: 33 bytes
	//	- merkle proof: 32
	TaprootToLocalRevokeWitnessSize = (1 + 1 + 65 + 1 +
		TaprootToLocalRevokeScriptSize + 1 + 33 + 32)

	// TaprootToRemoteScriptSize
	// 	- OP_DATA: 1 byte
	// 	- remote key: 32 bytes
	// 	- OP_CHECKSIG: 1 byte
	// 	- OP_1: 1 byte
	// 	- OP_CHECKSEQUENCEVERIFY: 1 byte
	// 	- OP_DROP: 1 byte
	TaprootToRemoteScriptSize = 1 + 32 + 1 + 1 + 1 + 1

	// TaprootToRemoteWitnessSize:
	//      - number_of_witness_elements: 1 byte
	//      - sig_len: 1 byte
	//      - sweep_sig: 65 bytes (worst case w/o sighash default)
	//      - script_len: 1 byte
	//      - taproot_to_local_script_size: 36 bytes
	//      - ctrl_block_len: 1 byte
	//      - base_control_block_size: 33 bytes
	TaprootToRemoteWitnessSize = (1 + 1 + 65 + 1 +
		TaprootToRemoteScriptSize + 1 +
		TaprootBaseControlBlockWitnessSize)

	// TaprootAnchorWitnessSize: 67 bytes
	//
	// In this case, we use the custom sighash size to give the most
	// pessemistic estimate.
	TaprootAnchorWitnessSize = TaprootKeyPathCustomSighashWitnessSize

	// TaprootSecondLevelHtlcScriptSize: 41 bytes
	//      - OP_DATA: 1 byte (pub key len)
	//      - local_key: 32 bytes
	//      - OP_CHECKSIG: 1 byte
	//      - OP_DATA: 1 byte (csv delay)
	//      - csv_delay: 4 bytes (worst case)
	//      - OP_CSV: 1 byte
	//      - OP_DROP: 1 byte
	TaprootSecondLevelHtlcScriptSize = 1 + 32 + 1 + 1 + 4 + 1 + 1

	// TaprootSecondLevelHtlcWitnessSize:
	//      - number_of_witness_elements: 1 byte
	//      - sig_len: 1 byte
	//      - sweep_sig: 65 bytes (worst case w/o sighash default)
	//      - script_len: 1 byte
	//      - taproot_second_level_htlc_script_size: 40 bytes
	//      - ctrl_block_len: 1 byte
	//      - base_control_block_size: 33 bytes
	TaprootSecondLevelHtlcWitnessSize = 1 + 1 + 65 + 1 +
		TaprootSecondLevelHtlcScriptSize + 1 +
		TaprootBaseControlBlockWitnessSize

	// TaprootSecondLevelRevokeWitnessSize
	//      - number_of_witness_elements: 1 byte
	//      - sig_len: 1 byte
	//      - sweep_sig: 65 bytes (worst case w/o sighash default)
	//nolint:lll
	TaprootSecondLevelRevokeWitnessSize = TaprootKeyPathCustomSighashWitnessSize

	// TaprootAcceptedRevokeWitnessSize:
	//      - number_of_witness_elements: 1 byte
	//      - sig_len: 1 byte
	//      - sweep_sig: 65 bytes (worst case w/o sighash default)
	//nolint:lll
	TaprootAcceptedRevokeWitnessSize = TaprootKeyPathCustomSighashWitnessSize

	// TaprootOfferedRevokeWitnessSize:
	//      - number_of_witness_elements: 1 byte
	//      - sig_len: 1 byte
	//      - sweep_sig: 65 bytes (worst case w/o sighash default)
	TaprootOfferedRevokeWitnessSize = TaprootKeyPathCustomSighashWitnessSize

	// TaprootHtlcOfferedRemoteTimeoutScriptSize: 42 bytes
	//	- OP_DATA: 1 byte (pub key len)
	//	- local_key: 32 bytes
	//	- OP_CHECKSIG: 1 byte
	//      - OP_1: 1 byte
	//      - OP_DROP: 1 byte
	//      - OP_CHECKSEQUENCEVERIFY: 1 byte
	//      - OP_DATA: 1 byte (cltv_expiry length)
	//      - cltv_expiry: 4 bytes
	//      - OP_CHECKLOCKTIMEVERIFY: 1 byte
	//      - OP_DROP: 1 byte
	TaprootHtlcOfferedRemoteTimeoutScriptSize = (1 + 32 + 1 + 1 + 1 + 1 +
		1 + 4 + 1 + 1)

	// TaprootHtlcOfferedRemoteTimeoutwitSize: 176 bytes
	//      - number_of_witness_elements: 1 byte
	//      - sig_len: 1 byte
	//      - sweep_sig: 65 bytes (worst case w/o sighash default)
	//      - script_len: 1 byte
	//      - taproot_offered_htlc_script_size: 42 bytes
	//      - ctrl_block_len: 1 byte
	//      - base_control_block_size: 33 bytes
	//      - sibilng_merkle_proof: 32 bytes
	TaprootHtlcOfferedRemoteTimeoutWitnessSize = 1 + 1 + 65 + 1 +
		TaprootHtlcOfferedRemoteTimeoutScriptSize + 1 +
		TaprootBaseControlBlockWitnessSize + 32

	// TaprootHtlcOfferedLocalTmeoutScriptSize:
	//	- OP_DATA: 1 byte (pub key len)
	//	- local_key: 32 bytes
	//	- OP_CHECKSIGVERIFY: 1 byte
	//	- OP_DATA: 1 byte (pub key len)
	//	- remote_key: 32 bytes
	//	- OP_CHECKSIG: 1 byte
	TaprootHtlcOfferedLocalTimeoutScriptSize = 1 + 32 + 1 + 1 + 32 + 1

	// TaprootOfferedLocalTimeoutWitnessSize
	//      - number_of_witness_elements: 1 byte
	//      - sig_len: 1 byte
	//      - sweep_sig: 65 bytes (worst case w/o sighash default)
	//      - sig_len: 1 byte
	//      - sweep_sig: 65 bytes (worst case w/o sighash default)
	//      - script_len: 1 byte
	//      - taproot_offered_htlc_script_timeout_size:
	//      - ctrl_block_len: 1 byte
	//      - base_control_block_size: 33 bytes
	//      - sibilng_merkle_proof: 32 bytes
	TaprootOfferedLocalTimeoutWitnessSize = 1 + 1 + 65 + 1 + 65 + 1 +
		TaprootHtlcOfferedLocalTimeoutScriptSize + 1 +
		TaprootBaseControlBlockWitnessSize + 32

	// TaprootHtlcAcceptedRemoteSuccessScriptSize:
	//      - OP_SIZE: 1 byte
	//      - OP_DATA: 1 byte
	//      - 32: 1 byte
	//      - OP_EQUALVERIFY: 1 byte
	//      - OP_HASH160: 1 byte
	//      - OP_DATA: 1 byte (RIPEMD160(payment_hash) length)
	//      - RIPEMD160(payment_hash): 20 bytes
	//      - OP_EQUALVERIFY: 1 byte
	//	- OP_DATA: 1 byte (pub key len)
	//	- remote_key: 32 bytes
	//	- OP_CHECKSIG: 1 byte
	//      - OP_1: 1 byte
	//      - OP_CSV: 1 byte
	//      - OP_DROP: 1 byte
	TaprootHtlcAcceptedRemoteSuccessScriptSize = 1 + 1 + 1 + 1 + 1 + 1 +
		1 + 20 + 1 + 32 + 1 + 1 + 1 + 1

	// TaprootHtlcAcceptedRemoteSuccessScriptSize:
	//      - number_of_witness_elements: 1 byte
	//      - sig_len: 1 byte
	//      - sweep_sig: 65 bytes (worst case w/o sighash default)
	//      - payment_preimage_length: 1 byte
	//      - payment_preimage: 32 bytes
	//      - script_len: 1 byte
	//      - taproot_offered_htlc_script_success_size:
	//      - ctrl_block_len: 1 byte
	//      - base_control_block_size: 33 bytes
	//      - sibilng_merkle_proof: 32 bytes
	TaprootHtlcAcceptedRemoteSuccessWitnessSize = 1 + 1 + 65 + 1 + 32 + 1 +
		TaprootHtlcAcceptedRemoteSuccessScriptSize + 1 +
		TaprootBaseControlBlockWitnessSize + 32

	// TaprootHtlcAcceptedLocalSuccessScriptSize:
	//      - OP_SIZE: 1 byte
	//      - OP_DATA: 1 byte
	//      - 32: 1 byte
	//      - OP_EQUALVERIFY: 1 byte
	//      - OP_HASH160: 1 byte
	//      - OP_DATA: 1 byte (RIPEMD160(payment_hash) length)
	//      - RIPEMD160(payment_hash): 20 bytes
	//      - OP_EQUALVERIFY: 1 byte
	//	- OP_DATA: 1 byte (pub key len)
	//	- local_key: 32 bytes
	//	- OP_CHECKSIGVERIFY: 1 byte
	//	- OP_DATA: 1 byte (pub key len)
	//	- remote_key: 32 bytes
	//	- OP_CHECKSIG: 1 byte
	TaprootHtlcAcceptedLocalSuccessScriptSize = 1 + 1 + 1 + 1 + 1 + 1 +
		20 + 1 + 1 + 32 + 1 + 1 + 32 + 1

	// TaprootHtlcAcceptedLocalSuccessWitnessSize:
	//      - number_of_witness_elements: 1 byte
	//      - sig_len: 1 byte
	//      - sweep_sig: 65 bytes (worst case w/o sighash default)
	//      - sig_len: 1 byte
	//      - sweep_sig: 65 bytes (worst case w/o sighash default)
	//      - payment_preimage_length: 1 byte
	//      - payment_preimage: 32 bytes
	//      - script_len: 1 byte
	//      - taproot_accepted_htlc_script_success_size:
	//      - ctrl_block_len: 1 byte
	//      - base_control_block_size: 33 bytes
	//      - sibilng_merkle_proof: 32 bytes
	TaprootHtlcAcceptedLocalSuccessWitnessSize = 1 + 1 + 65 + 1 + 65 + 1 +
		32 + 1 + TaprootHtlcAcceptedLocalSuccessScriptSize + 1 +
		TaprootBaseControlBlockWitnessSize + 32
)
View Source
const (
	// MuSig2PartialSigSize is the size of a MuSig2 partial signature.
	// Because a partial signature is just the s value, this corresponds to
	// the length of a scalar.
	MuSig2PartialSigSize = 32
)
View Source
const (
	// PubKeyFormatCompressedOdd is the identifier prefix byte for a public
	// key whose Y coordinate is odd when serialized in the compressed
	// format per section 2.3.4 of
	// [SEC1](https://secg.org/sec1-v2.pdf#subsubsection.2.3.4).
	// This is copied from the github.com/decred/dcrd/dcrec/secp256k1/v4 to
	// avoid needing to directly reference (and by accident pull in
	// incompatible crypto primitives) the package.
	PubKeyFormatCompressedOdd byte = 0x03
)
View Source
const TaprootNUMSHex = "02dca094751109d0bd055d03565874e8276dd53e926b44e3bd1bb" +
	"6bf4bc130a279"

TaprootNUMSHex is the hex encoded version of the taproot NUMs key.

Variables

View Source
var (
	// ErrTweakOverdose signals a SignDescriptor is invalid because both of its
	// SingleTweak and DoubleTweak are non-nil.
	ErrTweakOverdose = errors.New("sign descriptor should only have one tweak")
)
View Source
var ErrUnknownScriptType = errors.New("unknown script type")

ErrUnknownScriptType is returned when an unknown script type is encountered.

View Source
var (

	// SequenceLockTimeSeconds is the 22nd bit which indicates the lock
	// time is in seconds.
	SequenceLockTimeSeconds = uint32(1 << 22)
)
View Source
var (
	// TaprootNUMSKey is a NUMS key (nothing up my sleeves number) that has
	// no known private key. This was generated using the following script:
	// https://github.com/lightninglabs/lightning-node-connect/tree/
	// master/mailbox/numsgen, with the seed phrase "Lightning Simple
	// Taproot".
	TaprootNUMSKey = mustParsePubKey(TaprootNUMSHex)
)

Functions

func CommitScriptAnchor

func CommitScriptAnchor(key *btcec.PublicKey) ([]byte, error)

CommitScriptAnchor constructs the script for the anchor output spendable by the given key immediately, or by anyone after 16 confirmations.

Possible Input Scripts:

By owner:				<sig>
By anyone (after 16 conf):	<emptyvector>

Output Script:

<funding_pubkey> OP_CHECKSIG OP_IFDUP
OP_NOTIF
  OP_16 OP_CSV
OP_ENDIF

func CommitScriptToRemoteConfirmed

func CommitScriptToRemoteConfirmed(key *btcec.PublicKey) ([]byte, error)

CommitScriptToRemoteConfirmed constructs the script for the output on the commitment transaction paying to the remote party of said commitment transaction. The money can only be spend after one confirmation.

Possible Input Scripts:

SWEEP: <sig>

Output Script:

<key> OP_CHECKSIGVERIFY
1 OP_CHECKSEQUENCEVERIFY

func CommitScriptToSelf

func CommitScriptToSelf(csvTimeout uint32, selfKey, revokeKey *btcec.PublicKey) ([]byte, error)

CommitScriptToSelf constructs the public key script for the output on the commitment transaction paying to the "owner" of said commitment transaction. If the other party learns of the preimage to the revocation hash, then they can claim all the settled funds in the channel, plus the unsettled funds.

Possible Input Scripts:

REVOKE:     <sig> 1
SENDRSWEEP: <sig> <emptyvector>

Output Script:

OP_IF
    <revokeKey>
OP_ELSE
    <numRelativeBlocks> OP_CHECKSEQUENCEVERIFY OP_DROP
    <timeKey>
OP_ENDIF
OP_CHECKSIG

func CommitScriptUnencumbered

func CommitScriptUnencumbered(key *btcec.PublicKey) ([]byte, error)

CommitScriptUnencumbered constructs the public key script on the commitment transaction paying to the "other" party. The constructed output is a normal p2wkh output spendable immediately, requiring no contestation period.

func CommitSpendAnchor

func CommitSpendAnchor(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx) (wire.TxWitness, error)

CommitSpendAnchor constructs a valid witness allowing a node to spend their anchor output on the commitment transaction using their funding key. This is used for the anchor channel type.

func CommitSpendAnchorAnyone

func CommitSpendAnchorAnyone(script []byte) (wire.TxWitness, error)

CommitSpendAnchorAnyone constructs a witness allowing anyone to spend the anchor output after it has gotten 16 confirmations. Since no signing is required, only knowledge of the redeem script is necessary to spend it.

func CommitSpendNoDelay

func CommitSpendNoDelay(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx, tweakless bool) (wire.TxWitness, error)

CommitSpendNoDelay constructs a valid witness allowing a node to spend their settled no-delay output on the counterparty's commitment transaction. If the tweakless field is true, then we'll omit the set where we tweak the pubkey with a random set of bytes, and use it directly in the witness stack.

NOTE: The passed SignDescriptor should include the raw (untweaked) public key of the receiver and also the proper single tweak value based on the current commitment point.

func CommitSpendRevoke

func CommitSpendRevoke(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx) (wire.TxWitness, error)

CommitSpendRevoke constructs a valid witness allowing a node to sweep the settled output of a malicious counterparty who broadcasts a revoked commitment transaction.

NOTE: The passed SignDescriptor should include the raw (untweaked) revocation base public key of the receiver and also the proper double tweak value based on the commitment secret of the revoked commitment.

func CommitSpendTimeout

func CommitSpendTimeout(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx) (wire.TxWitness, error)

CommitSpendTimeout constructs a valid witness allowing the owner of a particular commitment transaction to spend the output returning settled funds back to themselves after a relative block timeout. In order to properly spend the transaction, the target input's sequence number should be set accordingly based off of the target relative block timeout within the redeem script. Additionally, OP_CSV requires that the version of the transaction spending a pkscript with OP_CSV within it *must* be >= 2.

func CommitSpendToRemoteConfirmed

func CommitSpendToRemoteConfirmed(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx) (wire.TxWitness, error)

CommitSpendToRemoteConfirmed constructs a valid witness allowing a node to spend their settled output on the counterparty's commitment transaction when it has one confirmetion. This is used for the anchor channel type. The spending key will always be non-tweaked for this output type.

func ComputeCommitmentPoint

func ComputeCommitmentPoint(commitSecret []byte) *btcec.PublicKey

ComputeCommitmentPoint generates a commitment point given a commitment secret. The commitment point for each state is used to randomize each key in the key-ring and also to used as a tweak to derive new public+private keys for the state.

func DeriveRevocationPrivKey

func DeriveRevocationPrivKey(revokeBasePriv *btcec.PrivateKey,
	commitSecret *btcec.PrivateKey) *btcec.PrivateKey

DeriveRevocationPrivKey derives the revocation private key given a node's commitment private key, and the preimage to a previously seen revocation hash. Using this derived private key, a node is able to claim the output within the commitment transaction of a node in the case that they broadcast a previously revoked commitment transaction.

The private key is derived as follows:

revokePriv := (revokeBasePriv * sha256(revocationBase || commitPoint)) +
              (commitSecret * sha256(commitPoint || revocationBase)) mod N

Where N is the order of the sub-group.

func DeriveRevocationPubkey

func DeriveRevocationPubkey(revokeBase,
	commitPoint *btcec.PublicKey) *btcec.PublicKey

DeriveRevocationPubkey derives the revocation public key given the counterparty's commitment key, and revocation preimage derived via a pseudo-random-function. In the event that we (for some reason) broadcast a revoked commitment transaction, then if the other party knows the revocation preimage, then they'll be able to derive the corresponding private key to this private key by exploiting the homomorphism in the elliptic curve group:

The derivation is performed as follows:

revokeKey := revokeBase * sha256(revocationBase || commitPoint) +
             commitPoint * sha256(commitPoint || revocationBase)

          := G*(revokeBasePriv * sha256(revocationBase || commitPoint)) +
             G*(commitSecret * sha256(commitPoint || revocationBase))

          := G*(revokeBasePriv * sha256(revocationBase || commitPoint) +
                commitSecret * sha256(commitPoint || revocationBase))

Therefore, once we divulge the revocation secret, the remote peer is able to compute the proper private key for the revokeKey by computing:

revokePriv := (revokeBasePriv * sha256(revocationBase || commitPoint)) +
              (commitSecret * sha256(commitPoint || revocationBase)) mod N

Where N is the order of the sub-group.

func DeserializePartialSignature

func DeserializePartialSignature(scalarBytes []byte) (*musig2.PartialSignature,
	error)

DeserializePartialSignature decodes a partial signature from a byte slice.

func EstimateCommitTxWeight

func EstimateCommitTxWeight(count int, prediction bool) int64

EstimateCommitTxWeight estimate commitment transaction weight depending on the precalculated weight of base transaction, witness data, which is needed for paying for funding tx, and htlc weight multiplied by their count.

func FindScriptOutputIndex

func FindScriptOutputIndex(tx *wire.MsgTx, script []byte) (bool, uint32)

FindScriptOutputIndex finds the index of the public key script output matching 'script'. Additionally, a boolean is returned indicating if a matching output was found at all.

NOTE: The search stops after the first matching script is found.

func GenFundingPkScript

func GenFundingPkScript(aPub, bPub []byte, amt int64) ([]byte, *wire.TxOut, error)

GenFundingPkScript creates a redeem script, and its matching p2wsh output for the funding transaction.

func GenMultiSigScript

func GenMultiSigScript(aPub, bPub []byte) ([]byte, error)

GenMultiSigScript generates the non-p2sh'd multisig script for 2 of 2 pubkeys.

func GenTaprootFundingScript

func GenTaprootFundingScript(aPub, bPub *btcec.PublicKey,
	amt int64) ([]byte, *wire.TxOut, error)

GenTaprootFundingScript constructs the taproot-native funding output that uses musig2 to create a single aggregated key to anchor the channel.

func GenerateP2PKH

func GenerateP2PKH(pubkey []byte) ([]byte, error)

GenerateP2PKH generates a pay-to-public-key-hash public key script paying to the passed serialized public key.

func GenerateP2SH

func GenerateP2SH(script []byte) ([]byte, error)

GenerateP2SH generates a pay-to-script-hash public key script paying to the passed redeem script.

func GenerateUnknownWitness

func GenerateUnknownWitness() ([]byte, error)

GenerateUnknownWitness generates the maximum-sized witness public key script consisting of a version push and a 40-byte data push.

func HtlcSecondLevelSpend

func HtlcSecondLevelSpend(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx) (wire.TxWitness, error)

HtlcSecondLevelSpend exposes the public witness generation function for spending an HTLC success transaction, either due to an expiring time lock or having had the payment preimage. This method is able to spend any second-level HTLC transaction, assuming the caller sets the locktime or seqno properly.

NOTE: The caller MUST set the txn version, sequence number, and sign descriptor's sig hash cache before invocation.

func HtlcSpendRevoke

func HtlcSpendRevoke(signer Signer, signDesc *SignDescriptor,
	revokeTx *wire.MsgTx) (wire.TxWitness, error)

HtlcSpendRevoke spends a second-level HTLC output. This function is to be used by the sender or receiver of an HTLC to claim the HTLC after a revoked commitment transaction was broadcast.

func HtlcSpendSuccess

func HtlcSpendSuccess(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx, csvDelay uint32) (wire.TxWitness, error)

HtlcSpendSuccess spends a second-level HTLC output. This function is to be used by the sender of an HTLC to claim the output after a relative timeout or the receiver of the HTLC to claim on-chain with the pre-image.

func IsHtlcSpendRevoke

func IsHtlcSpendRevoke(txIn *wire.TxIn, signDesc *SignDescriptor) (
	bool, error)

IsHtlcSpendRevoke is used to determine if the passed spend is spending a HTLC output using the revocation key.

func LeaseCommitScriptToRemoteConfirmed

func LeaseCommitScriptToRemoteConfirmed(key *btcec.PublicKey,
	leaseExpiry uint32) ([]byte, error)

LeaseCommitScriptToRemoteConfirmed constructs the script for the output on the commitment transaction paying to the remote party of said commitment transaction. The money can only be spend after one confirmation.

Possible Input Scripts:

SWEEP: <sig>

Output Script:

	<key> OP_CHECKSIGVERIFY
     <lease maturity in blocks> OP_CHECKLOCKTIMEVERIFY OP_DROP
	1 OP_CHECKSEQUENCEVERIFY

func LeaseCommitScriptToSelf

func LeaseCommitScriptToSelf(selfKey, revokeKey *btcec.PublicKey,
	csvTimeout, leaseExpiry uint32) ([]byte, error)

LeaseCommitScriptToSelf constructs the public key script for the output on the commitment transaction paying to the "owner" of said commitment transaction. If the other party learns of the preimage to the revocation hash, then they can claim all the settled funds in the channel, plus the unsettled funds.

Possible Input Scripts:

REVOKE:     <sig> 1
SENDRSWEEP: <sig> <emptyvector>

Output Script:

OP_IF
    <revokeKey>
OP_ELSE
    <absoluteLeaseExpiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
    <numRelativeBlocks> OP_CHECKSEQUENCEVERIFY OP_DROP
    <timeKey>
OP_ENDIF
OP_CHECKSIG

func LeaseSecondLevelHtlcScript

func LeaseSecondLevelHtlcScript(revocationKey, delayKey *btcec.PublicKey,
	csvDelay, cltvExpiry uint32) ([]byte, error)

LeaseSecondLevelHtlcScript is the uniform script that's used as the output for the second-level HTLC transactions. The second level transaction acts as a sort of covenant, ensuring that a 2-of-2 multi-sig output can only be spent in a particular way, and to a particular output.

Possible Input Scripts:

  • To revoke an HTLC output that has been transitioned to the claim+delay state: <revoke sig> 1

  • To claim an HTLC output, either with a pre-image or due to a timeout: <delay sig> 0

Output Script:

 OP_IF
	<revoke key>
 OP_ELSE
	<lease maturity in blocks>
	OP_CHECKLOCKTIMEVERIFY
	OP_DROP
	<delay in blocks>
	OP_CHECKSEQUENCEVERIFY
	OP_DROP
	<delay key>
 OP_ENDIF
 OP_CHECKSIG.

func LockTimeToSequence

func LockTimeToSequence(isSeconds bool, locktime uint32) uint32

LockTimeToSequence converts the passed relative locktime to a sequence number in accordance to BIP-68. See: https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki

  • (Compatibility)

func MakeTaprootCtrlBlock

func MakeTaprootCtrlBlock(leafScript []byte, internalKey *btcec.PublicKey,
	scriptTree *txscript.IndexedTapScriptTree) txscript.ControlBlock

MakeTaprootSCtrlBlock takes a leaf script, the internal key (usually the revoke key), and a script tree and creates a valid control block for a spend of the leaf.

func MuSig2CombineKeys

func MuSig2CombineKeys(bipVersion MuSig2Version,
	allSignerPubKeys []*btcec.PublicKey, sortKeys bool,
	tweaks *MuSig2Tweaks) (*musig2.AggregateKey, error)

MuSig2CombineKeys combines the given set of public keys into a single combined MuSig2 combined public key, applying the given tweaks.

func MuSig2CombineSig

func MuSig2CombineSig(session MuSig2Session,
	otherPartialSig *musig2.PartialSignature) (bool, error)

MuSig2CombineSig calls the CombineSig() method on the given versioned signing session and returns the result in the most recent version of the MuSig2 API.

func MuSig2CreateContext

func MuSig2CreateContext(bipVersion MuSig2Version, privKey *btcec.PrivateKey,
	allSignerPubKeys []*btcec.PublicKey, tweaks *MuSig2Tweaks,
	localNonces *musig2.Nonces,
) (MuSig2Context, MuSig2Session, error)

MuSig2CreateContext creates a new MuSig2 signing context.

func MuSig2ParsePubKeys

func MuSig2ParsePubKeys(bipVersion MuSig2Version,
	rawPubKeys [][]byte) ([]*btcec.PublicKey, error)

MuSig2ParsePubKeys parses a list of raw public keys as the signing keys of a MuSig2 signing session.

func MuSig2Sign

func MuSig2Sign(session MuSig2Session, msg [32]byte,
	withSortedKeys bool) (*musig2.PartialSignature, error)

MuSig2Sign calls the Sign() method on the given versioned signing session and returns the result in the most recent version of the MuSig2 API.

func MultiPrevOutFetcher

func MultiPrevOutFetcher(inputs []Input) (*txscript.MultiPrevOutFetcher, error)

MultiPrevOutFetcher returns a txscript.MultiPrevOutFetcher for the given set of inputs.

func NewTxSigHashesV0Only

func NewTxSigHashesV0Only(tx *wire.MsgTx) *txscript.TxSigHashes

NewTxSigHashesV0Only returns a new txscript.TxSigHashes instance that will only calculate the sighash midstate values for segwit v0 inputs and can therefore never be used for transactions that want to spend segwit v1 (taproot) inputs.

func PayToTaprootScript

func PayToTaprootScript(taprootKey *btcec.PublicKey) ([]byte, error)

PayToTaprootScript creates a new script to pay to a version 1 (taproot) witness program. The passed public key will be serialized as an x-only key to create the witness program.

func ReadSignDescriptor

func ReadSignDescriptor(r io.Reader, sd *SignDescriptor) error

ReadSignDescriptor deserializes a SignDescriptor struct from the passed io.Reader stream.

func ReceiverHTLCScript

func ReceiverHTLCScript(cltvExpiry uint32, senderHtlcKey,
	receiverHtlcKey, revocationKey *btcec.PublicKey,
	paymentHash []byte, confirmedSpend bool) ([]byte, error)

ReceiverHTLCScript constructs the public key script for an incoming HTLC output payment for the receiver's version of the commitment transaction. The possible execution paths from this script include:

  • The receiver of the HTLC uses its second level HTLC transaction to advance the state of the HTLC into the delay+claim state.
  • The sender of the HTLC sweeps all the funds of the HTLC as a breached commitment was broadcast.
  • The sender of the HTLC sweeps the HTLC on-chain after the timeout period of the HTLC has passed.

If confirmedSpend=true, a 1 OP_CSV check will be added to the non-revocation cases, to allow sweeping only after confirmation.

Possible Input Scripts:

RECVR: <0> <sender sig> <recvr sig> <preimage> (spend using HTLC success transaction)
REVOK: <sig> <key>
SENDR: <sig> 0

Received HTLC Output Script:

 OP_DUP OP_HASH160 <revocation key hash160> OP_EQUAL
 OP_IF
 	OP_CHECKSIG
 OP_ELSE
	<sendr htlc key>
	OP_SWAP OP_SIZE 32 OP_EQUAL
	OP_IF
	    OP_HASH160 <ripemd160(payment hash)> OP_EQUALVERIFY
	    2 OP_SWAP <recvr htlc key> 2 OP_CHECKMULTISIG
	OP_ELSE
	    OP_DROP <cltv expiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
	    OP_CHECKSIG
	OP_ENDIF
	[1 OP_CHECKSEQUENCEVERIFY OP_DROP] <- if allowing confirmed
	spend only.
 OP_ENDIF

func ReceiverHTLCScriptTaprootRedeem

func ReceiverHTLCScriptTaprootRedeem(senderSig Signature,
	senderSigHash txscript.SigHashType, paymentPreimage []byte,
	signer Signer, signDesc *SignDescriptor,
	htlcSuccessTx *wire.MsgTx, revokeKey *btcec.PublicKey,
	tapscriptTree *txscript.IndexedTapScriptTree) (wire.TxWitness, error)

ReceiverHTLCScriptTaprootRedeem creates a valid witness needed to redeem a receiver taproot HTLC with the pre-image. The returned witness is valid and includes the control block required to spend the output.

func ReceiverHTLCScriptTaprootRevoke

func ReceiverHTLCScriptTaprootRevoke(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx) (wire.TxWitness, error)

ReceiverHTLCScriptTaprootRevoke creates a valid witness needed to spend the revocation path of the HTLC from the PoV of the sender (offerer) of the HTLC. This uses a plain keyspend using the specified revocation key.

func ReceiverHTLCScriptTaprootTimeout

func ReceiverHTLCScriptTaprootTimeout(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx, cltvExpiry int32, revokeKey *btcec.PublicKey,
	tapscriptTree *txscript.IndexedTapScriptTree) (wire.TxWitness, error)

ReceiverHTLCScriptTaprootTimeout creates a valid witness needed to timeout an HTLC on the receiver's commitment transaction after the timeout has elapsed.

func ReceiverHtlcSpendRedeem

func ReceiverHtlcSpendRedeem(senderSig Signature,
	senderSigHash txscript.SigHashType, paymentPreimage []byte,
	signer Signer, signDesc *SignDescriptor, htlcSuccessTx *wire.MsgTx) (
	wire.TxWitness, error)

ReceiverHtlcSpendRedeem constructs a valid witness allowing the receiver of an HTLC to redeem the conditional payment in the event that their commitment transaction is broadcast. This clause transitions the state of the HLTC output into the delay+claim state by activating the off-chain covenant bound by the 2-of-2 multi-sig output. The HTLC success timeout transaction being signed has a relative timelock delay enforced by its sequence number. This delay give the sender of the HTLC enough time to revoke the output if this is a breach commitment transaction.

func ReceiverHtlcSpendRevoke

func ReceiverHtlcSpendRevoke(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx) (wire.TxWitness, error)

ReceiverHtlcSpendRevoke constructs a valid witness allowing the sender of an HTLC within a previously revoked commitment transaction to re-claim the pending funds in the case that the receiver broadcasts this revoked commitment transaction. This method first derives the appropriate revocation key, and requires that the provided SignDescriptor has a local revocation basepoint and commitment secret in the PubKey and DoubleTweak fields, respectively.

func ReceiverHtlcSpendRevokeWithKey

func ReceiverHtlcSpendRevokeWithKey(signer Signer, signDesc *SignDescriptor,
	revokeKey *btcec.PublicKey, sweepTx *wire.MsgTx) (wire.TxWitness, error)

ReceiverHtlcSpendRevokeWithKey constructs a valid witness allowing the sender of an HTLC within a previously revoked commitment transaction to re-claim the pending funds in the case that the receiver broadcasts this revoked commitment transaction.

func ReceiverHtlcSpendTimeout

func ReceiverHtlcSpendTimeout(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx, cltvExpiry int32) (wire.TxWitness, error)

ReceiverHtlcSpendTimeout constructs a valid witness allowing the sender of an HTLC to recover the pending funds after an absolute timeout in the scenario that the receiver of the HTLC broadcasts their version of the commitment transaction. If the caller has already set the lock time on the spending transaction, than a value of -1 can be passed for the cltvExpiry value.

NOTE: The target input of the passed transaction MUST NOT have a final sequence number. Otherwise, the OP_CHECKLOCKTIMEVERIFY check will fail.

func ReceiverHtlcTapLeafSuccess

func ReceiverHtlcTapLeafSuccess(receiverHtlcKey *btcec.PublicKey,
	senderHtlcKey *btcec.PublicKey,
	paymentHash []byte) (txscript.TapLeaf, error)

ReceiverHtlcTapLeafSuccess returns the full tapscript leaf for the success path for an HTLC on the receiver's commitment transaction. This script allows the receiver to redeem an HTLC with knowledge of the preimage:

OP_SIZE 32 OP_EQUALVERIFY OP_HASH160
<RIPEMD160(payment_hash)> OP_EQUALVERIFY
<receiver_htlcpubkey> OP_CHECKSIGVERIFY
<sender_htlcpubkey> OP_CHECKSIG

func ReceiverHtlcTapLeafTimeout

func ReceiverHtlcTapLeafTimeout(senderHtlcKey *btcec.PublicKey,
	cltvExpiry uint32) (txscript.TapLeaf, error)

ReceiverHtlcTapLeafTimeout returns the full tapscript leaf for the timeout path of the sender HTLC. This is a small script that allows the sender timeout the HTLC after expiry:

<sender_htlcpubkey> OP_CHECKSIG
1 OP_CHECKSEQUENCEVERIFY OP_DROP
<cltv_expiry> OP_CHECKLOCKTIMEVERIFY OP_DROP

func Ripemd160H

func Ripemd160H(d []byte) []byte

Ripemd160H calculates the ripemd160 of the passed byte slice. This is used to calculate the intermediate hash for payment pre-images. Payment hashes are the result of ripemd160(sha256(paymentPreimage)). As a result, the value passed in should be the sha256 of the payment hash.

func SecondLevelHtlcScript

func SecondLevelHtlcScript(revocationKey, delayKey *btcec.PublicKey,
	csvDelay uint32) ([]byte, error)

SecondLevelHtlcScript is the uniform script that's used as the output for the second-level HTLC transactions. The second level transaction act as a sort of covenant, ensuring that a 2-of-2 multi-sig output can only be spent in a particular way, and to a particular output.

Possible Input Scripts:

  • To revoke an HTLC output that has been transitioned to the claim+delay state: <revoke sig> 1

  • To claim and HTLC output, either with a pre-image or due to a timeout: <delay sig> 0

Output Script:

 OP_IF
	<revoke key>
 OP_ELSE
	<delay in blocks>
	OP_CHECKSEQUENCEVERIFY
	OP_DROP
	<delay key>
 OP_ENDIF
 OP_CHECKSIG

TODO(roasbeef): possible renames for second-level

  • transition?
  • covenant output

func SecondLevelHtlcTapscriptTree

func SecondLevelHtlcTapscriptTree(delayKey *btcec.PublicKey,
	csvDelay uint32) (*txscript.IndexedTapScriptTree, error)

SecondLevelHtlcTapscriptTree construct the indexed tapscript tree needed to generate the taptweak to create the final output and also control block.

func SenderHTLCScript

func SenderHTLCScript(senderHtlcKey, receiverHtlcKey,
	revocationKey *btcec.PublicKey, paymentHash []byte,
	confirmedSpend bool) ([]byte, error)

SenderHTLCScript constructs the public key script for an outgoing HTLC output payment for the sender's version of the commitment transaction. The possible script paths from this output include:

  • The sender timing out the HTLC using the second level HTLC timeout transaction.
  • The receiver of the HTLC claiming the output on-chain with the payment preimage.
  • The receiver of the HTLC sweeping all the funds in the case that a revoked commitment transaction bearing this HTLC was broadcast.

If confirmedSpend=true, a 1 OP_CSV check will be added to the non-revocation cases, to allow sweeping only after confirmation.

Possible Input Scripts:

SENDR: <0> <sendr sig>  <recvr sig> <0> (spend using HTLC timeout transaction)
RECVR: <recvr sig>  <preimage>
REVOK: <revoke sig> <revoke key>
 * receiver revoke

Offered HTLC Output Script:

 OP_DUP OP_HASH160 <revocation key hash160> OP_EQUAL
 OP_IF
	OP_CHECKSIG
 OP_ELSE
	<recv htlc key>
	OP_SWAP OP_SIZE 32 OP_EQUAL
	OP_NOTIF
	    OP_DROP 2 OP_SWAP <sender htlc key> 2 OP_CHECKMULTISIG
	OP_ELSE
	    OP_HASH160 <ripemd160(payment hash)> OP_EQUALVERIFY
	    OP_CHECKSIG
	OP_ENDIF
	[1 OP_CHECKSEQUENCEVERIFY OP_DROP] <- if allowing confirmed
	spend only.
 OP_ENDIF

func SenderHTLCScriptTaprootRedeem

func SenderHTLCScriptTaprootRedeem(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx, preimage []byte, revokeKey *btcec.PublicKey,
	tapscriptTree *txscript.IndexedTapScriptTree) (wire.TxWitness, error)

SenderHTLCScriptTaprootRedeem creates a valid witness needed to redeem a sender taproot HTLC with the pre-image. The returned witness is valid and includes the control block required to spend the output. This is the offered HTLC claimed by the remote party.

func SenderHTLCScriptTaprootRevoke

func SenderHTLCScriptTaprootRevoke(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx) (wire.TxWitness, error)

SenderHTLCScriptTaprootRevoke creates a valid witness needed to spend the revocation path of the HTLC. This uses a plain keyspend using the specified revocation key.

func SenderHTLCScriptTaprootTimeout

func SenderHTLCScriptTaprootTimeout(receiverSig Signature,
	receiverSigHash txscript.SigHashType, signer Signer,
	signDesc *SignDescriptor, htlcTimeoutTx *wire.MsgTx,
	revokeKey *btcec.PublicKey,
	tapscriptTree *txscript.IndexedTapScriptTree) (wire.TxWitness, error)

SenderHTLCScriptTaprootTimeout creates a valid witness needed to timeout an HTLC on the sender's commitment transaction. The returned witness is valid and includes the control block required to spend the output. This is a timeout of the offered HTLC by the sender.

func SenderHTLCTapLeafSuccess

func SenderHTLCTapLeafSuccess(receiverHtlcKey *btcec.PublicKey,
	paymentHash []byte) (txscript.TapLeaf, error)

SenderHTLCTapLeafSuccess returns the full tapscript leaf for the success path of the sender HTLC. This is a small script that allows the receiver to redeem the HTLC with a pre-image:

OP_SIZE 32 OP_EQUALVERIFY OP_HASH160
<RIPEMD160(payment_hash)> OP_EQUALVERIFY
<remote_htlcpubkey> OP_CHECKSIG
1 OP_CHECKSEQUENCEVERIFY OP_DROP

func SenderHTLCTapLeafTimeout

func SenderHTLCTapLeafTimeout(senderHtlcKey,
	receiverHtlcKey *btcec.PublicKey) (txscript.TapLeaf, error)

SenderHTLCTapLeafTimeout returns the full tapscript leaf for the timeout path of the sender HTLC. This is a small script that allows the sender to timeout the HTLC after a period of time:

<local_key> OP_CHECKSIGVERIFY
<remote_key> OP_CHECKSIG

func SenderHtlcSpendRedeem

func SenderHtlcSpendRedeem(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx, paymentPreimage []byte) (wire.TxWitness, error)

SenderHtlcSpendRedeem constructs a valid witness allowing the receiver of an HTLC to redeem the pending output in the scenario that the sender broadcasts their version of the commitment transaction. A valid spend requires knowledge of the payment preimage, and a valid signature under the receivers public key.

func SenderHtlcSpendRevoke

func SenderHtlcSpendRevoke(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx) (wire.TxWitness, error)

SenderHtlcSpendRevoke constructs a valid witness allowing the receiver of an HTLC to claim the output with knowledge of the revocation private key in the scenario that the sender of the HTLC broadcasts a previously revoked commitment transaction. This method first derives the appropriate revocation key, and requires that the provided SignDescriptor has a local revocation basepoint and commitment secret in the PubKey and DoubleTweak fields, respectively.

func SenderHtlcSpendRevokeWithKey

func SenderHtlcSpendRevokeWithKey(signer Signer, signDesc *SignDescriptor,
	revokeKey *btcec.PublicKey, sweepTx *wire.MsgTx) (wire.TxWitness, error)

SenderHtlcSpendRevokeWithKey constructs a valid witness allowing the receiver of an HTLC to claim the output with knowledge of the revocation private key in the scenario that the sender of the HTLC broadcasts a previously revoked commitment transaction. A valid spend requires knowledge of the private key that corresponds to their revocation base point and also the private key from the per commitment point, and a valid signature under the combined public key.

func SenderHtlcSpendTimeout

func SenderHtlcSpendTimeout(receiverSig Signature,
	receiverSigHash txscript.SigHashType, signer Signer,
	signDesc *SignDescriptor, htlcTimeoutTx *wire.MsgTx) (
	wire.TxWitness, error)

SenderHtlcSpendTimeout constructs a valid witness allowing the sender of an HTLC to activate the time locked covenant clause of a soon to be expired HTLC. This script simply spends the multi-sig output using the pre-generated HTLC timeout transaction.

func SerializePartialSignature

func SerializePartialSignature(
	sig *musig2.PartialSignature) ([MuSig2PartialSigSize]byte, error)

SerializePartialSignature encodes the partial signature to a fixed size byte array.

func SingleTweakBytes

func SingleTweakBytes(commitPoint, basePoint *btcec.PublicKey) []byte

SingleTweakBytes computes set of bytes we call the single tweak. The purpose of the single tweak is to randomize all regular delay and payment base points. To do this, we generate a hash that binds the commitment point to the pay/delay base point. The end end results is that the basePoint is tweaked as follows:

  • key = basePoint + sha256(commitPoint || basePoint)*G

func SpendMultiSig

func SpendMultiSig(witnessScript, pubA []byte, sigA Signature,
	pubB []byte, sigB Signature) [][]byte

SpendMultiSig generates the witness stack required to redeem the 2-of-2 p2wsh multi-sig output.

func TaprootAnchorSpend

func TaprootAnchorSpend(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx) (wire.TxWitness, error)

TaprootAnchorSpend constructs a valid witness allowing a node to sweep their anchor output.

func TaprootAnchorSpendAny

func TaprootAnchorSpendAny(anchorKey *btcec.PublicKey) (wire.TxWitness, error)

TaprootAnchorSpendAny constructs a valid witness allowing anyone to sweep the anchor output after 16 blocks.

func TaprootCommitRemoteSpend

func TaprootCommitRemoteSpend(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx,
	scriptTree *txscript.IndexedTapScriptTree) (wire.TxWitness, error)

TaprootCommitRemoteSpend allows the remote party to sweep their output into their wallet after an enforced 1 block delay.

func TaprootCommitScriptToRemote

func TaprootCommitScriptToRemote(remoteKey *btcec.PublicKey,
) (*btcec.PublicKey, error)

TaprootCommitScriptToRemote constructs a taproot witness program for the output on the commitment transaction for the remote party. For the top level key spend, we'll use a NUMs key to ensure that only the script path can be taken. Using a set NUMs key here also means that recovery solutions can scan the chain given knowledge of the public key for the remote party. We then commit to a single tapscript leaf that holds the normal CSV 1 delay script.

Our single tapleaf will use the following script:

<remotepubkey> OP_CHECKSIG
1 OP_CHECKSEQUENCEVERIFY OP_DROP

func TaprootCommitScriptToSelf

func TaprootCommitScriptToSelf(csvTimeout uint32,
	selfKey, revokeKey *btcec.PublicKey) (*btcec.PublicKey, error)

TaprootCommitScriptToSelf creates the taproot witness program that commits to the revocation (script path) and delay path (script path) in a single taproot output key. Both the delay script and the revocation script are part of the tapscript tree to ensure that the internal key (the local delay key) is always revealed. This ensures that a 3rd party can always sweep the set of anchor outputs.

For the delay path we have the following tapscript leaf script:

<local_delayedpubkey> OP_CHECKSIG
<to_self_delay> OP_CHECKSEQUENCEVERIFY OP_DROP

This can then be spent with just:

<local_delayedsig> <to_delay_script> <delay_control_block>

Where the to_delay_script is listed above, and the delay_control_block computed as:

delay_control_block = (output_key_y_parity | 0xc0) || taproot_nums_key

The revocation path is simply:

<local_delayedpubkey> OP_DROP
<revocationkey> OP_CHECKSIG

The revocation path can be spent with a control block similar to the above (but contains the hash of the other script), and with the following witness:

<revocation_sig>

We use a noop data push to ensure that the local public key is also revealed on chain, which enables the anchor output to be swept.

func TaprootCommitSpendRevoke

func TaprootCommitSpendRevoke(signer Signer, signDesc *SignDescriptor,
	revokeTx *wire.MsgTx,
	scriptTree *txscript.IndexedTapScriptTree) (wire.TxWitness, error)

TaprootCommitSpendRevoke constructs a valid witness allowing a node to sweep the revoked taproot output of a malicious peer.

func TaprootCommitSpendSuccess

func TaprootCommitSpendSuccess(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx,
	scriptTree *txscript.IndexedTapScriptTree) (wire.TxWitness, error)

TaprootCommitSpendSuccess constructs a valid witness allowing a node to sweep the settled taproot output after the delay has passed for a force close.

func TaprootHtlcSpendRevoke

func TaprootHtlcSpendRevoke(signer Signer, signDesc *SignDescriptor,
	revokeTx *wire.MsgTx) (wire.TxWitness, error)

TaprootHtlcSpendRevoke spends a second-level HTLC output via the revocation path. This uses the top level keyspend path to redeem the contested output.

The passed SignDescriptor MUST have the proper witness script and also the proper top-level tweak derived from the tapscript tree for the second level output.

func TaprootHtlcSpendSuccess

func TaprootHtlcSpendSuccess(signer Signer, signDesc *SignDescriptor,
	sweepTx *wire.MsgTx, revokeKey *btcec.PublicKey,
	tapscriptTree *txscript.IndexedTapScriptTree) (wire.TxWitness, error)

TaprootHtlcSpendSuccess spends a second-level HTLC output via the redemption path. This should be used to sweep funds after the pre-image is known.

NOTE: The caller MUST set the txn version, sequence number, and sign descriptor's sig hash cache before invocation.

func TaprootOutputKeyAnchor

func TaprootOutputKeyAnchor(key *btcec.PublicKey) (*btcec.PublicKey, error)

TaprootOutputKeyAnchor returns the segwit v1 (taproot) witness program that encodes the anchor output spending conditions: the passed key can be used for keyspend, with the OP_CSV 16 clause living within an internal tapscript leaf.

Spend paths:

  • Key spend: <key_signature>
  • Script spend: OP_16 CSV <control_block>

func TaprootSecondLevelHtlcScript

func TaprootSecondLevelHtlcScript(revokeKey, delayKey *btcec.PublicKey,
	csvDelay uint32) (*btcec.PublicKey, error)

TaprootSecondLevelHtlcScript is the uniform script that's used as the output for the second-level HTLC transaction. The second level transaction acts as an off-chain 2-of-2 covenant that can only be spent a particular way and to a particular output.

Possible Input Scripts:

  • revocation sig
  • <local_delay_sig>

The script main script lets the broadcaster spend after a delay the script path:

<local_delay_key> OP_CHECKSIG
<to_self_delay> OP_CHECKSEQUENCEVERIFY OP_DROP

The keyspend path require knowledge of the top level revocation private key.

func TaprootSecondLevelTapLeaf

func TaprootSecondLevelTapLeaf(delayKey *btcec.PublicKey,
	csvDelay uint32) (txscript.TapLeaf, error)

TaprootSecondLevelTapLeaf constructs the tap leaf used as the sole script path for a second level HTLC spend.

The final script used is:

<local_delay_key> OP_CHECKSIG
<to_self_delay> OP_CHECKSEQUENCEVERIFY OP_DROP

func TapscriptFullKeyOnly

func TapscriptFullKeyOnly(taprootKey *btcec.PublicKey) *waddrmgr.Tapscript

TapscriptFullKeyOnly creates a waddrmgr.Tapscript for the given full Taproot key.

func TapscriptFullTree

func TapscriptFullTree(internalKey *btcec.PublicKey,
	allTreeLeaves ...txscript.TapLeaf) *waddrmgr.Tapscript

TapscriptFullTree creates a waddrmgr.Tapscript for the given internal key and tree leaves.

func TapscriptPartialReveal

func TapscriptPartialReveal(internalKey *btcec.PublicKey,
	revealedLeaf txscript.TapLeaf,
	inclusionProof []byte) *waddrmgr.Tapscript

TapscriptPartialReveal creates a waddrmgr.Tapscript for the given internal key and revealed script.

func TapscriptRootHashOnly

func TapscriptRootHashOnly(internalKey *btcec.PublicKey,
	rootHash []byte) *waddrmgr.Tapscript

TapscriptRootHashOnly creates a waddrmgr.Tapscript for the given internal key and root hash.

func TweakPrivKey

func TweakPrivKey(basePriv *btcec.PrivateKey,
	commitTweak []byte) *btcec.PrivateKey

TweakPrivKey tweaks the private key of a public base point given a per commitment point. The per commitment secret is the revealed revocation secret for the commitment state in question. This private key will only need to be generated in the case that a channel counter party broadcasts a revoked state. Precisely, the following operation is used to derive a tweaked private key:

  • tweakPriv := basePriv + sha256(commitment || basePub) mod N

Where N is the order of the sub-group.

func TweakPubKey

func TweakPubKey(basePoint, commitPoint *btcec.PublicKey) *btcec.PublicKey

TweakPubKey tweaks a public base point given a per commitment point. The per commitment point is a unique point on our target curve for each commitment transaction. When tweaking a local base point for use in a remote commitment transaction, the remote party's current per commitment point is to be used. The opposite applies for when tweaking remote keys. Precisely, the following operation is used to "tweak" public keys:

tweakPub := basePoint + sha256(commitPoint || basePoint) * G
         := G*k + sha256(commitPoint || basePoint)*G
         := G*(k + sha256(commitPoint || basePoint))

Therefore, if a party possess the value k, the private key of the base point, then they are able to derive the proper private key for the revokeKey by computing:

revokePriv := k + sha256(commitPoint || basePoint) mod N

Where N is the order of the sub-group.

The rationale for tweaking all public keys used within the commitment contracts is to ensure that all keys are properly delinearized to avoid any funny business when jointly collaborating to compute public and private keys. Additionally, the use of the per commitment point ensures that each commitment state houses a unique set of keys which is useful when creating blinded channel outsourcing protocols.

TODO(roasbeef): should be using double-scalar mult here

func TweakPubKeyWithTweak

func TweakPubKeyWithTweak(pubKey *btcec.PublicKey,
	tweakBytes []byte) *btcec.PublicKey

TweakPubKeyWithTweak is the exact same as the TweakPubKey function, however it accepts the raw tweak bytes directly rather than the commitment point.

func WitnessPubKeyHash

func WitnessPubKeyHash(pubkey []byte) ([]byte, error)

WitnessPubKeyHash generates a pay-to-witness-pubkey-hash public key script paying to a version 0 witness program containing the passed serialized public key.

func WitnessScriptHash

func WitnessScriptHash(witnessScript []byte) ([]byte, error)

WitnessScriptHash generates a pay-to-witness-script-hash public key script paying to a version 0 witness program paying to the passed redeem script.

func WriteSignDescriptor

func WriteSignDescriptor(w io.Writer, sd *SignDescriptor) error

WriteSignDescriptor serializes a SignDescriptor struct into the passed io.Writer stream.

NOTE: We assume the SigHashes and InputIndex fields haven't been assigned yet, since that is usually done just before broadcast by the witness generator.

Types

type AnchorScriptTree

type AnchorScriptTree struct {
	ScriptTree

	// SweepLeaf is the leaf used to settle the output after the delay.
	SweepLeaf txscript.TapLeaf
}

AnchorScriptTree holds all the contents needed to sweep a taproot anchor output on chain.

func NewAnchorScriptTree

func NewAnchorScriptTree(anchorKey *btcec.PublicKey,
) (*AnchorScriptTree, error)

NewAnchorScriptTree makes a new script tree for an anchor output with the passed anchor key.

func (*AnchorScriptTree) CtrlBlockForPath

func (a *AnchorScriptTree) CtrlBlockForPath(path ScriptPath,
) (*txscript.ControlBlock, error)

CtrlBlockForPath returns the control block for the given spending path. For script types that don't have a control block, nil is returned.

func (*AnchorScriptTree) WitnessScriptForPath

func (a *AnchorScriptTree) WitnessScriptForPath(path ScriptPath,
) ([]byte, error)

WitnessScriptForPath returns the witness script for the given spending path. An error is returned if the path is unknown.

func (*AnchorScriptTree) WitnessScriptToSign

func (a *AnchorScriptTree) WitnessScriptToSign() []byte

WitnessScript returns the witness script that we'll use when signing for the remote party, and also verifying signatures on our transactions. As an example, when we create an outgoing HTLC for the remote party, we want to sign their success path.

type BaseInput

type BaseInput struct {
	// contains filtered or unexported fields
}

BaseInput contains all the information needed to sweep a basic output (CSV/CLTV/no time lock).

func MakeBaseInput

func MakeBaseInput(outpoint *wire.OutPoint, witnessType WitnessType,
	signDescriptor *SignDescriptor, heightHint uint32,
	unconfParent *TxInfo) BaseInput

MakeBaseInput assembles a new BaseInput that can be used to construct a sweep transaction.

func NewBaseInput

func NewBaseInput(outpoint *wire.OutPoint, witnessType WitnessType,
	signDescriptor *SignDescriptor, heightHint uint32) *BaseInput

NewBaseInput allocates and assembles a new *BaseInput that can be used to construct a sweep transaction.

func NewCsvInput

func NewCsvInput(outpoint *wire.OutPoint, witnessType WitnessType,
	signDescriptor *SignDescriptor, heightHint uint32,
	blockToMaturity uint32) *BaseInput

NewCsvInput assembles a new csv-locked input that can be used to construct a sweep transaction.

func NewCsvInputWithCltv

func NewCsvInputWithCltv(outpoint *wire.OutPoint, witnessType WitnessType,
	signDescriptor *SignDescriptor, heightHint uint32,
	csvDelay uint32, cltvExpiry uint32) *BaseInput

NewCsvInputWithCltv assembles a new csv and cltv locked input that can be used to construct a sweep transaction.

func (*BaseInput) BlocksToMaturity

func (i *BaseInput) BlocksToMaturity() uint32

BlocksToMaturity returns the relative timelock, as a number of blocks, that must be built on top of the confirmation height before the output can be spent. For non-CSV locked inputs this is always zero.

func (*BaseInput) CraftInputScript

func (bi *BaseInput) CraftInputScript(signer Signer, txn *wire.MsgTx,
	hashCache *txscript.TxSigHashes,
	prevOutputFetcher txscript.PrevOutputFetcher, txinIdx int) (*Script,
	error)

CraftInputScript returns a valid set of input scripts allowing this output to be spent. The returned input scripts should target the input at location txIndex within the passed transaction. The input scripts generated by this method support spending p2wkh, p2wsh, and also nested p2sh outputs.

func (*BaseInput) HeightHint

func (i *BaseInput) HeightHint() uint32

HeightHint returns the minimum height at which a confirmed spending tx can occur.

func (*BaseInput) OutPoint

func (i *BaseInput) OutPoint() *wire.OutPoint

OutPoint returns the breached output's identifier that is to be included as a transaction input.

func (*BaseInput) RequiredLockTime

func (i *BaseInput) RequiredLockTime() (uint32, bool)

RequiredLockTime returns whether this input commits to a tx locktime that must be used in the transaction including it. This will be false for the base input type since we can re-sign for any lock time.

func (*BaseInput) RequiredTxOut

func (i *BaseInput) RequiredTxOut() *wire.TxOut

RequiredTxOut returns a nil for the base input type.

func (*BaseInput) SignDesc

func (i *BaseInput) SignDesc() *SignDescriptor

SignDesc returns the breached output's SignDescriptor, which is used during signing to compute the witness.

func (*BaseInput) UnconfParent

func (i *BaseInput) UnconfParent() *TxInfo

Cpfp returns information about a possibly unconfirmed parent tx.

func (*BaseInput) WitnessType

func (i *BaseInput) WitnessType() WitnessType

WitnessType returns the type of witness that must be generated to spend the breached output.

type CommitScriptTree

type CommitScriptTree struct {
	ScriptTree

	// SettleLeaf is the leaf used to settle the output after the delay.
	SettleLeaf txscript.TapLeaf

	// RevocationLeaf is the leaf used to spend the output with the
	// revocation key signature.
	RevocationLeaf txscript.TapLeaf
}

CommitScriptTree holds the taproot output key (in this case the revocation key, or a NUMs point for the remote output) along with the tapscript leaf that can spend the output after a delay.

func NewLocalCommitScriptTree

func NewLocalCommitScriptTree(csvTimeout uint32,
	selfKey, revokeKey *btcec.PublicKey) (*CommitScriptTree, error)

NewLocalCommitScriptTree returns a new CommitScript tree that can be used to create and spend the commitment output for the local party.

func NewRemoteCommitScriptTree

func NewRemoteCommitScriptTree(remoteKey *btcec.PublicKey,
) (*CommitScriptTree, error)

NewRemoteCommitScriptTree constructs a new script tree for the remote party to sweep their funds after a hard coded 1 block delay.

func (*CommitScriptTree) CtrlBlockForPath

func (c *CommitScriptTree) CtrlBlockForPath(path ScriptPath,
) (*txscript.ControlBlock, error)

CtrlBlockForPath returns the control block for the given spending path. For script types that don't have a control block, nil is returned.

func (*CommitScriptTree) WitnessScriptForPath

func (c *CommitScriptTree) WitnessScriptForPath(path ScriptPath,
) ([]byte, error)

WitnessScriptForPath returns the witness script for the given spending path. An error is returned if the path is unknown.

func (*CommitScriptTree) WitnessScriptToSign

func (c *CommitScriptTree) WitnessScriptToSign() []byte

WitnessScript returns the witness script that we'll use when signing for the remote party, and also verifying signatures on our transactions. As an example, when we create an outgoing HTLC for the remote party, we want to sign their success path.

type HtlcScriptTree

type HtlcScriptTree struct {
	ScriptTree

	// SuccessTapLeaf is the tapleaf for the redemption path.
	SuccessTapLeaf txscript.TapLeaf

	// TimeoutTapLeaf is the tapleaf for the timeout path.
	TimeoutTapLeaf txscript.TapLeaf
	// contains filtered or unexported fields
}

HtlcScriptTree holds the taproot output key, as well as the two script path leaves that every taproot HTLC script depends on.

func ReceiverHTLCScriptTaproot

func ReceiverHTLCScriptTaproot(cltvExpiry uint32,
	senderHtlcKey, receiverHtlcKey, revocationKey *btcec.PublicKey,
	payHash []byte, ourCommit bool) (*HtlcScriptTree, error)

ReceiverHTLCScriptTaproot constructs the taproot witness program (schnor key) for an incoming HTLC on the receiver's version of the commitment transaction. This method returns the top level tweaked public key that commits to both the script paths. From the PoV of the receiver, this is an accepted HTLC.

The returned key commits to a tapscript tree with two possible paths:

  • The timeout path: <remote_htlcpubkey> OP_CHECKSIG 1 OP_CHECKSEQUENCEVERIFY OP_DROP <cltv_expiry> OP_CHECKLOCKTIMEVERIFY OP_DROP

  • Success path: OP_SIZE 32 OP_EQUALVERIFY OP_HASH160 <RIPEMD160(payment_hash)> OP_EQUALVERIFY <local_htlcpubkey> OP_CHECKSIGVERIFY <remote_htlcpubkey> OP_CHECKSIG

The timeout path can be spent with a witness of:

  • <sender sig> <timeout_script> <control_block>

The success path can be spent with a witness of:

  • <sender sig> <receiver sig> <preimage> <success_script> <control_block>

The top level keyspend key is the revocation key, which allows a defender to unilaterally spend the created output. Both the final output key as well as the tap leaf are returned.

func SenderHTLCScriptTaproot

func SenderHTLCScriptTaproot(senderHtlcKey, receiverHtlcKey,
	revokeKey *btcec.PublicKey, payHash []byte,
	localCommit bool) (*HtlcScriptTree, error)

SenderHTLCScriptTaproot constructs the taproot witness program (schnorr key) for an outgoing HTLC on the sender's version of the commitment transaction. This method returns the top level tweaked public key that commits to both the script paths. This is also known as an offered HTLC.

The returned key commits to a tapscript tree with two possible paths:

  • Timeout path: <local_key> OP_CHECKSIGVERIFY <remote_key> OP_CHECKSIG

  • Success path: OP_SIZE 32 OP_EQUALVERIFY OP_HASH160 <RIPEMD160(payment_hash)> OP_EQUALVERIFY <remote_htlcpubkey> OP_CHECKSIG 1 OP_CHECKSEQUENCEVERIFY OP_DROP

The timeout path can be spent with a witness of (sender timeout):

<receiver sig> <local sig> <timeout_script> <control_block>

The success path can be spent with a valid control block, and a witness of (receiver redeem):

<receiver sig> <preimage> <success_script> <control_block>

The top level keyspend key is the revocation key, which allows a defender to unilaterally spend the created output.

func (*HtlcScriptTree) CtrlBlockForPath

func (h *HtlcScriptTree) CtrlBlockForPath(path ScriptPath,
) (*txscript.ControlBlock, error)

CtrlBlockForPath returns the control block for the given spending path. For script types that don't have a control block, nil is returned.

func (*HtlcScriptTree) WitnessScriptForPath

func (h *HtlcScriptTree) WitnessScriptForPath(path ScriptPath) ([]byte, error)

WitnessScriptForPath returns the witness script for the given spending path. An error is returned if the path is unknown.

func (*HtlcScriptTree) WitnessScriptToSign

func (h *HtlcScriptTree) WitnessScriptToSign() []byte

WitnessScriptToSign returns the witness script that we'll use when signing for the remote party, and also verifying signatures on our transactions. As an example, when we create an outgoing HTLC for the remote party, we want to sign the success path for them, so we'll return the success path leaf.

type HtlcSecondLevelAnchorInput

type HtlcSecondLevelAnchorInput struct {

	// SignedTx is the original second level transaction signed by the
	// channel peer.
	SignedTx *wire.MsgTx
	// contains filtered or unexported fields
}

HtlcsSecondLevelAnchorInput is an input type used to spend HTLC outputs using a re-signed second level transaction, either via the timeout or success paths.

func MakeHtlcSecondLevelSuccessAnchorInput

func MakeHtlcSecondLevelSuccessAnchorInput(signedTx *wire.MsgTx,
	signDetails *SignDetails, preimage lntypes.Preimage,
	heightHint uint32) HtlcSecondLevelAnchorInput

MakeHtlcSecondLevelSuccessAnchorInput creates an input allowing the sweeper to spend the HTLC output on our commit using the second level success transaction.

func MakeHtlcSecondLevelSuccessTaprootInput

func MakeHtlcSecondLevelSuccessTaprootInput(signedTx *wire.MsgTx,
	signDetails *SignDetails, preimage lntypes.Preimage,
	heightHint uint32) HtlcSecondLevelAnchorInput

MakeHtlcSecondLevelSuccessTaprootInput creates an input that allows the sweeper to spend an HTLC output to the second level on our taproot commitment transaction.

func MakeHtlcSecondLevelTimeoutAnchorInput

func MakeHtlcSecondLevelTimeoutAnchorInput(signedTx *wire.MsgTx,
	signDetails *SignDetails, heightHint uint32) HtlcSecondLevelAnchorInput

MakeHtlcSecondLevelTimeoutAnchorInput creates an input allowing the sweeper to spend the HTLC output on our commit using the second level timeout transaction.

func MakeHtlcSecondLevelTimeoutTaprootInput

func MakeHtlcSecondLevelTimeoutTaprootInput(signedTx *wire.MsgTx,
	signDetails *SignDetails,
	heightHint uint32) HtlcSecondLevelAnchorInput

MakeHtlcSecondLevelTimeoutTaprootInput creates an input that allows the sweeper to spend an HTLC output to the second level on our commitment transaction. The sweeper is also able to generate witnesses on demand to sweep the second level HTLC aggregated with other transactions.

func (*HtlcSecondLevelAnchorInput) BlocksToMaturity

func (i *HtlcSecondLevelAnchorInput) BlocksToMaturity() uint32

BlocksToMaturity returns the relative timelock, as a number of blocks, that must be built on top of the confirmation height before the output can be spent. For non-CSV locked inputs this is always zero.

func (*HtlcSecondLevelAnchorInput) CraftInputScript

func (i *HtlcSecondLevelAnchorInput) CraftInputScript(signer Signer,
	txn *wire.MsgTx, hashCache *txscript.TxSigHashes,
	prevOutputFetcher txscript.PrevOutputFetcher, txinIdx int) (*Script,
	error)

CraftInputScript returns a valid set of input scripts allowing this output to be spent. The returns input scripts should target the input at location txIndex within the passed transaction. The input scripts generated by this method support spending p2wkh, p2wsh, and also nested p2sh outputs.

func (*HtlcSecondLevelAnchorInput) HeightHint

func (i *HtlcSecondLevelAnchorInput) HeightHint() uint32

HeightHint returns the minimum height at which a confirmed spending tx can occur.

func (*HtlcSecondLevelAnchorInput) OutPoint

func (i *HtlcSecondLevelAnchorInput) OutPoint() *wire.OutPoint

OutPoint returns the breached output's identifier that is to be included as a transaction input.

func (*HtlcSecondLevelAnchorInput) RequiredLockTime

func (i *HtlcSecondLevelAnchorInput) RequiredLockTime() (uint32, bool)

RequiredLockTime returns the locktime needed for the sweep tx for the spend of the input to be valid. For a second level HTLC timeout this will be the CLTV expiry, for HTLC success it will be zero.

func (*HtlcSecondLevelAnchorInput) RequiredTxOut

func (i *HtlcSecondLevelAnchorInput) RequiredTxOut() *wire.TxOut

RequiredTxOut returns the tx out needed to be present on the sweep tx for the spend of the input to be valid.

func (*HtlcSecondLevelAnchorInput) SignDesc

func (i *HtlcSecondLevelAnchorInput) SignDesc() *SignDescriptor

SignDesc returns the breached output's SignDescriptor, which is used during signing to compute the witness.

func (*HtlcSecondLevelAnchorInput) UnconfParent

func (i *HtlcSecondLevelAnchorInput) UnconfParent() *TxInfo

Cpfp returns information about a possibly unconfirmed parent tx.

func (*HtlcSecondLevelAnchorInput) WitnessType

func (i *HtlcSecondLevelAnchorInput) WitnessType() WitnessType

WitnessType returns the type of witness that must be generated to spend the breached output.

type HtlcSucceedInput

type HtlcSucceedInput struct {
	// contains filtered or unexported fields
}

HtlcSucceedInput constitutes a sweep input that needs a pre-image. The input is expected to reside on the commitment tx of the remote party and should not be a second level tx output.

func MakeHtlcSucceedInput

func MakeHtlcSucceedInput(outpoint *wire.OutPoint,
	signDescriptor *SignDescriptor, preimage []byte, heightHint,
	blocksToMaturity uint32) HtlcSucceedInput

MakeHtlcSucceedInput assembles a new redeem input that can be used to construct a sweep transaction.

func MakeTaprootHtlcSucceedInput

func MakeTaprootHtlcSucceedInput(op *wire.OutPoint, signDesc *SignDescriptor,
	preimage []byte, heightHint, blocksToMaturity uint32) HtlcSucceedInput

MakeTaprootHtlcSucceedInput creates a new HtlcSucceedInput that can be used to spend an HTLC output for a taproot channel on the remote party's commitment transaction.

func (*HtlcSucceedInput) BlocksToMaturity

func (i *HtlcSucceedInput) BlocksToMaturity() uint32

BlocksToMaturity returns the relative timelock, as a number of blocks, that must be built on top of the confirmation height before the output can be spent. For non-CSV locked inputs this is always zero.

func (*HtlcSucceedInput) CraftInputScript

func (h *HtlcSucceedInput) CraftInputScript(signer Signer, txn *wire.MsgTx,
	hashCache *txscript.TxSigHashes,
	prevOutputFetcher txscript.PrevOutputFetcher, txinIdx int) (*Script,
	error)

CraftInputScript returns a valid set of input scripts allowing this output to be spent. The returns input scripts should target the input at location txIndex within the passed transaction. The input scripts generated by this method support spending p2wkh, p2wsh, and also nested p2sh outputs.

func (*HtlcSucceedInput) HeightHint

func (i *HtlcSucceedInput) HeightHint() uint32

HeightHint returns the minimum height at which a confirmed spending tx can occur.

func (*HtlcSucceedInput) OutPoint

func (i *HtlcSucceedInput) OutPoint() *wire.OutPoint

OutPoint returns the breached output's identifier that is to be included as a transaction input.

func (*HtlcSucceedInput) RequiredLockTime

func (i *HtlcSucceedInput) RequiredLockTime() (uint32, bool)

RequiredLockTime returns whether this input commits to a tx locktime that must be used in the transaction including it. This will be false for the base input type since we can re-sign for any lock time.

func (*HtlcSucceedInput) RequiredTxOut

func (i *HtlcSucceedInput) RequiredTxOut() *wire.TxOut

RequiredTxOut returns a nil for the base input type.

func (*HtlcSucceedInput) SignDesc

func (i *HtlcSucceedInput) SignDesc() *SignDescriptor

SignDesc returns the breached output's SignDescriptor, which is used during signing to compute the witness.

func (*HtlcSucceedInput) UnconfParent

func (i *HtlcSucceedInput) UnconfParent() *TxInfo

Cpfp returns information about a possibly unconfirmed parent tx.

func (*HtlcSucceedInput) WitnessType

func (i *HtlcSucceedInput) WitnessType() WitnessType

WitnessType returns the type of witness that must be generated to spend the breached output.

type Input

type Input interface {
	// Outpoint returns the reference to the output being spent, used to
	// construct the corresponding transaction input.
	OutPoint() *wire.OutPoint

	// RequiredTxOut returns a non-nil TxOut if input commits to a certain
	// transaction output. This is used in the SINGLE|ANYONECANPAY case to
	// make sure any presigned input is still valid by including the
	// output.
	RequiredTxOut() *wire.TxOut

	// RequiredLockTime returns whether this input commits to a tx locktime
	// that must be used in the transaction including it.
	RequiredLockTime() (uint32, bool)

	// WitnessType returns an enum specifying the type of witness that must
	// be generated in order to spend this output.
	WitnessType() WitnessType

	// SignDesc returns a reference to a spendable output's sign
	// descriptor, which is used during signing to compute a valid witness
	// that spends this output.
	SignDesc() *SignDescriptor

	// CraftInputScript returns a valid set of input scripts allowing this
	// output to be spent. The returns input scripts should target the
	// input at location txIndex within the passed transaction. The input
	// scripts generated by this method support spending p2wkh, p2wsh, and
	// also nested p2sh outputs.
	CraftInputScript(signer Signer, txn *wire.MsgTx,
		hashCache *txscript.TxSigHashes,
		prevOutputFetcher txscript.PrevOutputFetcher,
		txinIdx int) (*Script, error)

	// BlocksToMaturity returns the relative timelock, as a number of
	// blocks, that must be built on top of the confirmation height before
	// the output can be spent. For non-CSV locked inputs this is always
	// zero.
	BlocksToMaturity() uint32

	// HeightHint returns the minimum height at which a confirmed spending
	// tx can occur.
	HeightHint() uint32

	// UnconfParent returns information about a possibly unconfirmed parent
	// tx.
	UnconfParent() *TxInfo
}

Input represents an abstract UTXO which is to be spent using a sweeping transaction. The method provided give the caller all information needed to construct a valid input within a sweeping transaction to sweep this lingering UTXO.

type MockSigner

type MockSigner struct {
	Privkeys  []*btcec.PrivateKey
	NetParams *chaincfg.Params

	*MusigSessionManager
}

MockSigner is a simple implementation of the Signer interface. Each one has a set of private keys in a slice and can sign messages using the appropriate one.

func NewMockSigner

func NewMockSigner(privKeys []*btcec.PrivateKey,
	netParams *chaincfg.Params) *MockSigner

NewMockSigner returns a new instance of the MockSigner given a set of backing private keys.

func (*MockSigner) ComputeInputScript

func (m *MockSigner) ComputeInputScript(tx *wire.MsgTx, signDesc *SignDescriptor) (*Script, error)

ComputeInputScript generates a complete InputIndex for the passed transaction with the signature as defined within the passed SignDescriptor. This method should be capable of generating the proper input script for both regular p2wkh output and p2wkh outputs nested within a regular p2sh output.

func (*MockSigner) SignOutputRaw

func (m *MockSigner) SignOutputRaw(tx *wire.MsgTx,
	signDesc *SignDescriptor) (Signature, error)

SignOutputRaw generates a signature for the passed transaction according to the data within the passed SignDescriptor.

type MuSig2Context

type MuSig2Context interface {
	// SigningKeys returns the set of keys used for signing.
	SigningKeys() []*btcec.PublicKey

	// CombinedKey returns the combined public key that will be used to
	// generate multi-signatures  against.
	CombinedKey() (*btcec.PublicKey, error)

	// TaprootInternalKey returns the internal taproot key, which is the
	// aggregated key _before_ the tweak is applied. If a taproot tweak was
	// specified, then CombinedKey() will return the fully tweaked output
	// key, with this method returning the internal key. If a taproot tweak
	// wasn't specified, then this method will return an error.
	TaprootInternalKey() (*btcec.PublicKey, error)
}

MuSig2Context is an interface that is an abstraction over the MuSig2 signing context. This interface does not contain all of the methods the underlying implementations have because those use package specific types which cannot easily be made compatible. Those calls (such as NewSession) are implemented in this package instead and do the necessary type switch (see MuSig2CreateContext).

type MuSig2Session

type MuSig2Session interface {
	// FinalSig returns the final combined multi-signature, if present.
	FinalSig() *schnorr.Signature

	// PublicNonce returns the public nonce for a signer. This should be
	// sent to other parties before signing begins, so they can compute the
	// aggregated public nonce.
	PublicNonce() [musig2.PubNonceSize]byte

	// NumRegisteredNonces returns the total number of nonces that have been
	// registered so far.
	NumRegisteredNonces() int

	// RegisterPubNonce should be called for each public nonce from the set
	// of signers. This method returns true once all the public nonces have
	// been accounted for.
	RegisterPubNonce(nonce [musig2.PubNonceSize]byte) (bool, error)
}

MuSig2Session is an interface that is an abstraction over the MuSig2 signing session. This interface does not contain all of the methods the underlying implementations have because those use package specific types which cannot easily be made compatible. Those calls (such as CombineSig or Sign) are implemented in this package instead and do the necessary type switch (see MuSig2CombineSig or MuSig2Sign).

type MuSig2SessionID

type MuSig2SessionID [sha256.Size]byte

MuSig2SessionID is a type for a session ID that is just a hash of the MuSig2 combined key and the local public nonces.

func NewMuSig2SessionID

func NewMuSig2SessionID(combinedKey *btcec.PublicKey,
	publicNonces [musig2.PubNonceSize]byte) MuSig2SessionID

NewMuSig2SessionID returns the unique ID of a MuSig2 session by using the combined key and the local public nonces and hashing that data.

type MuSig2SessionInfo

type MuSig2SessionInfo struct {
	// SessionID is the wallet's internal unique ID of this session. The ID
	// is the hash over the combined public key and the local public nonces.
	SessionID [32]byte

	// Version is the version of the MuSig2 BIP this signing session is
	// using.
	Version MuSig2Version

	// PublicNonce contains the public nonce of the local signer session.
	PublicNonce [musig2.PubNonceSize]byte

	// CombinedKey is the combined public key with all tweaks applied to it.
	CombinedKey *btcec.PublicKey

	// TaprootTweak indicates whether a taproot tweak (BIP-0086 or script
	// path) was used. The TaprootInternalKey will only be set if this is
	// set to true.
	TaprootTweak bool

	// TaprootInternalKey is the raw combined public key without any tweaks
	// applied to it. This is only set if TaprootTweak is true.
	TaprootInternalKey *btcec.PublicKey

	// HaveAllNonces indicates whether this session already has all nonces
	// of all other signing participants registered.
	HaveAllNonces bool

	// HaveAllSigs indicates whether this session already has all partial
	// signatures of all other signing participants registered.
	HaveAllSigs bool
}

MuSig2SessionInfo is a struct for keeping track of a signing session information in memory.

type MuSig2Signer

type MuSig2Signer interface {
	// MuSig2CreateSession creates a new MuSig2 signing session using the
	// local key identified by the key locator. The complete list of all
	// public keys of all signing parties must be provided, including the
	// public key of the local signing key. If nonces of other parties are
	// already known, they can be submitted as well to reduce the number of
	// method calls necessary later on.
	//
	// The localNonces field is optional. If it is set, then the specified
	// nonces will be used instead of generating from scratch.  This is
	// useful in instances where the nonces are generated ahead of time
	// before the set of signers is known.
	MuSig2CreateSession(MuSig2Version, keychain.KeyLocator,
		[]*btcec.PublicKey, *MuSig2Tweaks, [][musig2.PubNonceSize]byte,
		*musig2.Nonces) (*MuSig2SessionInfo, error)

	// MuSig2RegisterNonces registers one or more public nonces of other
	// signing participants for a session identified by its ID. This method
	// returns true once we have all nonces for all other signing
	// participants.
	MuSig2RegisterNonces(MuSig2SessionID,
		[][musig2.PubNonceSize]byte) (bool, error)

	// MuSig2Sign creates a partial signature using the local signing key
	// that was specified when the session was created. This can only be
	// called when all public nonces of all participants are known and have
	// been registered with the session. If this node isn't responsible for
	// combining all the partial signatures, then the cleanup parameter
	// should be set, indicating that the session can be removed from memory
	// once the signature was produced.
	MuSig2Sign(MuSig2SessionID, [sha256.Size]byte,
		bool) (*musig2.PartialSignature, error)

	// MuSig2CombineSig combines the given partial signature(s) with the
	// local one, if it already exists. Once a partial signature of all
	// participants is registered, the final signature will be combined and
	// returned.
	MuSig2CombineSig(MuSig2SessionID,
		[]*musig2.PartialSignature) (*schnorr.Signature, bool, error)

	// MuSig2Cleanup removes a session from memory to free up resources.
	MuSig2Cleanup(MuSig2SessionID) error
}

MuSig2Signer is an interface that declares all methods that a MuSig2 compatible signer needs to implement.

type MuSig2State

type MuSig2State struct {
	// MuSig2SessionInfo is the associated meta information of the signing
	// session.
	MuSig2SessionInfo
	// contains filtered or unexported fields
}

MuSig2State is a struct that holds on to the internal signing session state of a MuSig2 session.

type MuSig2Tweaks

type MuSig2Tweaks struct {
	// GenericTweaks is a list of normal tweaks to apply to the combined
	// public key (and to the private key when signing).
	GenericTweaks []musig2.KeyTweakDesc

	// TaprootBIP0086Tweak indicates that the final key should use the
	// taproot tweak as defined in BIP 341, with the BIP 86 modification:
	//     outputKey = internalKey + h_tapTweak(internalKey)*G.
	// In this case, the aggregated key before the tweak will be used as the
	// internal key. If this is set to true then TaprootTweak will be
	// ignored.
	TaprootBIP0086Tweak bool

	// TaprootTweak specifies that the final key should use the taproot
	// tweak as defined in BIP 341:
	//     outputKey = internalKey + h_tapTweak(internalKey || scriptRoot).
	// In this case, the aggregated key before the tweak will be used as the
	// internal key. Will be ignored if TaprootBIP0086Tweak is set to true.
	TaprootTweak []byte
}

MuSig2Tweaks is a struct that contains all tweaks that can be applied to a MuSig2 combined public key.

func (*MuSig2Tweaks) HasTaprootTweak

func (t *MuSig2Tweaks) HasTaprootTweak() bool

HasTaprootTweak returns true if either a taproot BIP0086 tweak or a taproot script root tweak is set.

func (*MuSig2Tweaks) ToContextOptions

func (t *MuSig2Tweaks) ToContextOptions() []musig2.ContextOption

ToContextOptions converts the tweak descriptor to context options.

func (*MuSig2Tweaks) ToV040ContextOptions

func (t *MuSig2Tweaks) ToV040ContextOptions() []musig2v040.ContextOption

ToV040ContextOptions converts the tweak descriptor to v0.4.0 context options.

type MuSig2Version

type MuSig2Version uint8

MuSig2Version is a type that defines the different versions of the MuSig2 as defined in the BIP draft: (https://github.com/jonasnick/bips/blob/musig2/bip-musig2.mediawiki)

const (
	// MuSig2Version040 is version 0.4.0 of the MuSig2 BIP draft. This will
	// use the lnd internal/musig2v040 package.
	MuSig2Version040 MuSig2Version = 0

	// MuSig2Version100RC2 is version 1.0.0rc2 of the MuSig2 BIP draft. This
	// uses the github.com/btcsuite/btcd/btcec/v2/schnorr/musig2 package
	// at git tag `btcec/v2.3.1`.
	MuSig2Version100RC2 MuSig2Version = 1
)

type MusigSessionManager

type MusigSessionManager struct {
	// contains filtered or unexported fields
}

MusigSessionMusigSessionManager houses the state needed to manage concurrent musig sessions. Each session is identified by a unique session ID which is used by callers to interact with a given session.

func NewMusigSessionManager

func NewMusigSessionManager(keyFetcher PrivKeyFetcher) *MusigSessionManager

NewMusigSessionManager creates a new musig manager given an abstract key fetcher.

func (*MusigSessionManager) MuSig2Cleanup

func (m *MusigSessionManager) MuSig2Cleanup(sessionID MuSig2SessionID) error

MuSig2Cleanup removes a session from memory to free up resources.

func (*MusigSessionManager) MuSig2CombineSig

func (m *MusigSessionManager) MuSig2CombineSig(sessionID MuSig2SessionID,
	partialSigs []*musig2.PartialSignature) (*schnorr.Signature, bool,
	error)

MuSig2CombineSig combines the given partial signature(s) with the local one, if it already exists. Once a partial signature of all participants is registered, the final signature will be combined and returned.

func (*MusigSessionManager) MuSig2CreateSession

func (m *MusigSessionManager) MuSig2CreateSession(bipVersion MuSig2Version,
	keyLoc keychain.KeyLocator, allSignerPubKeys []*btcec.PublicKey,
	tweaks *MuSig2Tweaks, otherSignerNonces [][musig2.PubNonceSize]byte,
	localNonces *musig2.Nonces) (*MuSig2SessionInfo, error)

MuSig2CreateSession creates a new MuSig2 signing session using the local key identified by the key locator. The complete list of all public keys of all signing parties must be provided, including the public key of the local signing key. If nonces of other parties are already known, they can be submitted as well to reduce the number of method calls necessary later on.

The set of sessionOpts are _optional_ and allow a caller to modify the generated sessions. As an example the local nonce might already be generated ahead of time.

func (*MusigSessionManager) MuSig2RegisterNonces

func (m *MusigSessionManager) MuSig2RegisterNonces(sessionID MuSig2SessionID,
	otherSignerNonces [][musig2.PubNonceSize]byte) (bool, error)

MuSig2RegisterNonces registers one or more public nonces of other signing participants for a session identified by its ID. This method returns true once we have all nonces for all other signing participants.

func (*MusigSessionManager) MuSig2Sign

func (m *MusigSessionManager) MuSig2Sign(sessionID MuSig2SessionID,
	msg [sha256.Size]byte, cleanUp bool) (*musig2.PartialSignature, error)

MuSig2Sign creates a partial signature using the local signing key that was specified when the session was created. This can only be called when all public nonces of all participants are known and have been registered with the session. If this node isn't responsible for combining all the partial signatures, then the cleanup parameter should be set, indicating that the session can be removed from memory once the signature was produced.

type PrivKeyFetcher

type PrivKeyFetcher func(*keychain.KeyDescriptor) (*btcec.PrivateKey, error)

PrivKeyFetcher is used to fetch a private key that matches a given key desc.

type Script

type Script struct {
	// Witness is the full witness stack required to unlock this output.
	Witness wire.TxWitness

	// SigScript will only be populated if this is an input script sweeping
	// a nested p2sh output.
	SigScript []byte
}

Script represents any script inputs required to redeem a previous output. This struct is used rather than just a witness, or scripSig in order to accommodate nested p2sh which utilizes both types of input scripts.

type ScriptDescriptor

type ScriptDescriptor interface {
	// PkScript is the public key script that commits to the final
	// contract.
	PkScript() []byte

	// WitnessScript returns the witness script that we'll use when signing
	// for the remote party, and also verifying signatures on our
	// transactions. As an example, when we create an outgoing HTLC for the
	// remote party, we want to sign their success path.
	//
	// TODO(roasbeef): break out into HTLC specific desc? or Branching Desc
	// w/ the below?
	WitnessScriptToSign() []byte

	// WitnessScriptForPath returns the witness script for the given
	// spending path. An error is returned if the path is unknown. This is
	// useful as when constructing a control block for a given path, one
	// also needs witness script being signed.
	WitnessScriptForPath(path ScriptPath) ([]byte, error)
}

ScriptDesciptor is an interface that abstracts over the various ways a pkScript can be spent from an output. This supports both normal p2wsh (witness script, etc), and also tapscript paths which have distinct tapscript leaves.

type ScriptPath

type ScriptPath uint8

ScriptPath is used to indicate the spending path of a given script. Possible paths include: timeout, success, revocation, and others.

const (
	// ScriptPathTimeout is a script path that can be taken only after a
	// timeout has elapsed.
	ScriptPathTimeout ScriptPath = iota

	// ScriptPathSuccess is a script path that can be taken only with some
	// secret data.
	ScriptPathSuccess

	// ScriptPathRevocation is a script path used when a contract has been
	// breached.
	ScriptPathRevocation

	// ScriptPathDelay is a script path used when a contract has relative
	// delay that must elapse before it can be swept.
	ScriptPathDelay
)

type ScriptTree

type ScriptTree struct {
	// InternalKey is the internal key of the Taproot output key.
	InternalKey *btcec.PublicKey

	// TaprootKey is the key that will be used to generate the taproot
	// output.
	TaprootKey *btcec.PublicKey

	// TapscriptTree is the full tapscript tree that also includes the
	// control block needed to spend each of the leaves.
	TapscriptTree *txscript.IndexedTapScriptTree

	// TapscriptTreeRoot is the root hash of the tapscript tree.
	TapscriptRoot []byte
}

ScriptTree holds the contents needed to spend a script within a tapscript tree.

func (*ScriptTree) PkScript

func (s *ScriptTree) PkScript() []byte

PkScript is the public key script that commits to the final contract.

func (*ScriptTree) TapScriptTree

func (s *ScriptTree) TapScriptTree() *txscript.IndexedTapScriptTree

TapScriptTree returns the underlying tapscript tree.

func (*ScriptTree) TapTweak

func (s *ScriptTree) TapTweak() []byte

TapTweak returns the top-level taproot tweak for the script.

type SecondLevelScriptTree

type SecondLevelScriptTree struct {
	ScriptTree

	// SuccessTapLeaf is the tapleaf for the redemption path.
	SuccessTapLeaf txscript.TapLeaf
}

SecondLevelScriptTree is a tapscript tree used to spend the second level HTLC output after the CSV delay has passed.

func TaprootSecondLevelScriptTree

func TaprootSecondLevelScriptTree(revokeKey, delayKey *btcec.PublicKey,
	csvDelay uint32) (*SecondLevelScriptTree, error)

TaprootSecondLevelScriptTree constructs the tapscript tree used to spend the second level HTLC output.

func (*SecondLevelScriptTree) CtrlBlockForPath

func (s *SecondLevelScriptTree) CtrlBlockForPath(path ScriptPath,
) (*txscript.ControlBlock, error)

CtrlBlockForPath returns the control block for the given spending path. For script types that don't have a control block, nil is returned.

func (*SecondLevelScriptTree) WitnessScriptForPath

func (s *SecondLevelScriptTree) WitnessScriptForPath(path ScriptPath,
) ([]byte, error)

WitnessScriptForPath returns the witness script for the given spending path. An error is returned if the path is unknown.

func (*SecondLevelScriptTree) WitnessScriptToSign

func (s *SecondLevelScriptTree) WitnessScriptToSign() []byte

WitnessScript returns the witness script that we'll use when signing for the remote party, and also verifying signatures on our transactions. As an example, when we create an outgoing HTLC for the remote party, we want to sign their success path.

type SignDescriptor

type SignDescriptor struct {
	// KeyDesc is a descriptor that precisely describes *which* key to use
	// for signing. This may provide the raw public key directly, or
	// require the Signer to re-derive the key according to the populated
	// derivation path.
	KeyDesc keychain.KeyDescriptor

	// SingleTweak is a scalar value that will be added to the private key
	// corresponding to the above public key to obtain the private key to
	// be used to sign this input. This value is typically derived via the
	// following computation:
	//
	//  * derivedKey = privkey + sha256(perCommitmentPoint || pubKey) mod N
	//
	// NOTE: If this value is nil, then the input can be signed using only
	// the above public key. Either a SingleTweak should be set or a
	// DoubleTweak, not both.
	SingleTweak []byte

	// DoubleTweak is a private key that will be used in combination with
	// its corresponding private key to derive the private key that is to
	// be used to sign the target input. Within the Lightning protocol,
	// this value is typically the commitment secret from a previously
	// revoked commitment transaction. This value is in combination with
	// two hash values, and the original private key to derive the private
	// key to be used when signing.
	//
	//  * k = (privKey*sha256(pubKey || tweakPub) +
	//        tweakPriv*sha256(tweakPub || pubKey)) mod N
	//
	// NOTE: If this value is nil, then the input can be signed using only
	// the above public key. Either a SingleTweak should be set or a
	// DoubleTweak, not both.
	DoubleTweak *btcec.PrivateKey

	// TapTweak is a 32-byte value that will be used to derive a taproot
	// output public key (or the corresponding private key) from an
	// internal key and this tweak. The transformation applied is:
	//  * outputKey = internalKey +
	//        tagged_hash("tapTweak", internalKey || tapTweak)
	//
	// When attempting to sign an output derived via BIP 86, then this
	// field should be an empty byte array.
	//
	// When attempting to sign for the key spend path of an output key that
	// commits to an actual script tree, the script root should be used.
	TapTweak []byte

	// WitnessScript is the full script required to properly redeem the
	// output. This field should be set to the full script if a p2wsh
	// output is being signed. For p2wkh it should be set to the hashed
	// script (PkScript).
	WitnessScript []byte

	// SignMethod specifies how the input should be signed. Depending on the
	// selected method, either the TapTweak, WitnessScript or both need to
	// be specified.
	SignMethod SignMethod

	// Output is the target output which should be signed. The PkScript and
	// Value fields within the output should be properly populated,
	// otherwise an invalid signature may be generated.
	Output *wire.TxOut

	// HashType is the target sighash type that should be used when
	// generating the final sighash, and signature.
	HashType txscript.SigHashType

	// SigHashes is the pre-computed sighash midstate to be used when
	// generating the final sighash for signing.
	SigHashes *txscript.TxSigHashes

	// PrevOutputFetcher is an interface that can return the output
	// information on all UTXOs that are being spent in this transaction.
	// This MUST be set when spending Taproot outputs.
	PrevOutputFetcher txscript.PrevOutputFetcher

	// ControlBlock is a fully serialized control block that contains the
	// merkle proof necessary to spend a taproot output. This may
	// optionally be set if the SignMethod is
	// input.TaprootScriptSpendSignMethod. In which case, this should be an
	// inclusion proof for the WitnessScript.
	ControlBlock []byte

	// InputIndex is the target input within the transaction that should be
	// signed.
	InputIndex int
}

SignDescriptor houses the necessary information required to successfully sign a given segwit output. This struct is used by the Signer interface in order to gain access to critical data needed to generate a valid signature.

type SignDetails

type SignDetails struct {
	// SignDesc is the sign descriptor needed for us to sign the input.
	SignDesc SignDescriptor

	// PeerSig is the peer's signature for this input.
	PeerSig Signature

	// SigHashType is the sighash signed by the peer.
	SigHashType txscript.SigHashType
}

SignDetails is a struct containing information needed to resign certain inputs. It is used to re-sign 2nd level HTLC transactions that uses the SINGLE|ANYONECANPAY sighash type, as we have a signature provided by our peer, but we can aggregate multiple of these 2nd level transactions into a new transaction, that needs to be signed by us.

type SignMethod

type SignMethod uint8

SignMethod defines the different ways a signer can sign, given a specific input.

const (
	// WitnessV0SignMethod denotes that a SegWit v0 (p2wkh, np2wkh, p2wsh)
	// input script should be signed.
	WitnessV0SignMethod SignMethod = 0

	// TaprootKeySpendBIP0086SignMethod denotes that a SegWit v1 (p2tr)
	// input should be signed by using the BIP0086 method (commit to
	// internal key only).
	TaprootKeySpendBIP0086SignMethod SignMethod = 1

	// TaprootKeySpendSignMethod denotes that a SegWit v1 (p2tr)
	// input should be signed by using a given taproot hash to commit to in
	// addition to the internal key.
	TaprootKeySpendSignMethod SignMethod = 2

	// TaprootScriptSpendSignMethod denotes that a SegWit v1 (p2tr) input
	// should be spent using the script path and that a specific leaf script
	// should be signed for.
	TaprootScriptSpendSignMethod SignMethod = 3
)

func (SignMethod) PkScriptCompatible

func (s SignMethod) PkScriptCompatible(pkScript []byte) bool

PkScriptCompatible returns true if the given public key script is compatible with the sign method.

func (SignMethod) String

func (s SignMethod) String() string

String returns a human-readable representation of the signing method.

type Signature

type Signature interface {
	// Serialize returns a DER-encoded ECDSA signature.
	Serialize() []byte

	// Verify return true if the ECDSA signature is valid for the passed
	// message digest under the provided public key.
	Verify([]byte, *btcec.PublicKey) bool
}

Signature is an interface for objects that can populate signatures during witness construction.

func ParseSignature

func ParseSignature(rawSig []byte) (Signature, error)

ParseSignature parses a raw signature into an input.Signature instance. This routine supports parsing normal ECDSA DER encoded signatures, as well as schnorr signatures.

type Signer

type Signer interface {
	// MuSig2Signer is an embedded interface to make sure all our signers
	// also support MuSig2 signing, so we can forward calls to a remote
	// signer as well.
	MuSig2Signer

	// SignOutputRaw generates a signature for the passed transaction
	// according to the data within the passed SignDescriptor.
	//
	// NOTE: The resulting signature should be void of a sighash byte.
	SignOutputRaw(tx *wire.MsgTx, signDesc *SignDescriptor) (Signature,
		error)

	// ComputeInputScript generates a complete InputIndex for the passed
	// transaction with the signature as defined within the passed
	// SignDescriptor. This method should be capable of generating the
	// proper input script for both regular p2wkh/p2tr outputs and p2wkh
	// outputs nested within a regular p2sh output.
	//
	// NOTE: This method will ignore any tweak parameters set within the
	// passed SignDescriptor as it assumes a set of typical script
	// templates (p2wkh, p2tr, np2wkh, etc).
	ComputeInputScript(tx *wire.MsgTx, signDesc *SignDescriptor) (*Script,
		error)
}

Signer represents an abstract object capable of generating raw signatures as well as full complete input scripts given a valid SignDescriptor and transaction. This interface fully abstracts away signing paving the way for Signer implementations such as hardware wallets, hardware tokens, HSM's, or simply a regular wallet.

type StandardWitnessType

type StandardWitnessType uint16

StandardWitnessType is a numeric representation of standard pre-defined types of witness configurations.

const (
	// CommitmentTimeLock is a witness that allows us to spend our output
	// on our local commitment transaction after a relative lock-time
	// lockout.
	CommitmentTimeLock StandardWitnessType = 0

	// CommitmentNoDelay is a witness that allows us to spend a settled
	// no-delay output immediately on a counterparty's commitment
	// transaction.
	CommitmentNoDelay StandardWitnessType = 1

	// CommitmentRevoke is a witness that allows us to sweep the settled
	// output of a malicious counterparty's who broadcasts a revoked
	// commitment transaction.
	CommitmentRevoke StandardWitnessType = 2

	// HtlcOfferedRevoke is a witness that allows us to sweep an HTLC which
	// we offered to the remote party in the case that they broadcast a
	// revoked commitment state.
	HtlcOfferedRevoke StandardWitnessType = 3

	// HtlcAcceptedRevoke is a witness that allows us to sweep an HTLC
	// output sent to us in the case that the remote party broadcasts a
	// revoked commitment state.
	HtlcAcceptedRevoke StandardWitnessType = 4

	// HtlcOfferedTimeoutSecondLevel is a witness that allows us to sweep
	// an HTLC output that we extended to a party, but was never fulfilled.
	// This HTLC output isn't directly on the commitment transaction, but
	// is the result of a confirmed second-level HTLC transaction. As a
	// result, we can only spend this after a CSV delay.
	HtlcOfferedTimeoutSecondLevel StandardWitnessType = 5

	// HtlcOfferedTimeoutSecondLevelInputConfirmed is a witness that allows
	// us to sweep an HTLC output that we extended to a party, but was
	// never fulfilled. This _is_ the HTLC output directly on our
	// commitment transaction, and the input to the second-level HTLC
	// timeout transaction. It can only be spent after CLTV expiry, and
	// commitment confirmation.
	HtlcOfferedTimeoutSecondLevelInputConfirmed StandardWitnessType = 15

	// HtlcAcceptedSuccessSecondLevel is a witness that allows us to sweep
	// an HTLC output that was offered to us, and for which we have a
	// payment preimage. This HTLC output isn't directly on our commitment
	// transaction, but is the result of confirmed second-level HTLC
	// transaction. As a result, we can only spend this after a CSV delay.
	HtlcAcceptedSuccessSecondLevel StandardWitnessType = 6

	// HtlcAcceptedSuccessSecondLevelInputConfirmed is a witness that
	// allows us to sweep an HTLC output that was offered to us, and for
	// which we have a payment preimage. This _is_ the HTLC output directly
	// on our commitment transaction, and the input to the second-level
	// HTLC success transaction.  It can only be spent after the commitment
	// has confirmed.
	HtlcAcceptedSuccessSecondLevelInputConfirmed StandardWitnessType = 16

	// HtlcOfferedRemoteTimeout is a witness that allows us to sweep an
	// HTLC that we offered to the remote party which lies in the
	// commitment transaction of the remote party. We can spend this output
	// after the absolute CLTV timeout of the HTLC as passed.
	HtlcOfferedRemoteTimeout StandardWitnessType = 7

	// HtlcAcceptedRemoteSuccess is a witness that allows us to sweep an
	// HTLC that was offered to us by the remote party. We use this witness
	// in the case that the remote party goes to chain, and we know the
	// pre-image to the HTLC. We can sweep this without any additional
	// timeout.
	HtlcAcceptedRemoteSuccess StandardWitnessType = 8

	// HtlcSecondLevelRevoke is a witness that allows us to sweep an HTLC
	// from the remote party's commitment transaction in the case that the
	// broadcast a revoked commitment, but then also immediately attempt to
	// go to the second level to claim the HTLC.
	HtlcSecondLevelRevoke StandardWitnessType = 9

	// WitnessKeyHash is a witness type that allows us to spend a regular
	// p2wkh output that's sent to an output which is under complete
	// control of the backing wallet.
	WitnessKeyHash StandardWitnessType = 10

	// NestedWitnessKeyHash is a witness type that allows us to sweep an
	// output that sends to a nested P2SH script that pays to a key solely
	// under our control. The witness generated needs to include the
	NestedWitnessKeyHash StandardWitnessType = 11

	// CommitSpendNoDelayTweakless is similar to the CommitSpendNoDelay
	// type, but it omits the tweak that randomizes the key we need to
	// spend with a channel peer supplied set of randomness.
	CommitSpendNoDelayTweakless StandardWitnessType = 12

	// CommitmentToRemoteConfirmed is a witness that allows us to spend our
	// output on the counterparty's commitment transaction after a
	// confirmation.
	CommitmentToRemoteConfirmed StandardWitnessType = 13

	// CommitmentAnchor is a witness that allows us to spend our anchor on
	// the commitment transaction.
	CommitmentAnchor StandardWitnessType = 14

	// LeaseCommitmentTimeLock is a witness that allows us to spend our
	// output on our local commitment transaction after a relative and
	// absolute lock-time lockout as part of the script enforced lease
	// commitment type.
	LeaseCommitmentTimeLock StandardWitnessType = 17

	// LeaseCommitmentToRemoteConfirmed is a witness that allows us to spend
	// our output on the counterparty's commitment transaction after a
	// confirmation and absolute locktime as part of the script enforced
	// lease commitment type.
	LeaseCommitmentToRemoteConfirmed StandardWitnessType = 18

	// LeaseHtlcOfferedTimeoutSecondLevel is a witness that allows us to
	// sweep an HTLC output that we extended to a party, but was never
	// fulfilled. This HTLC output isn't directly on the commitment
	// transaction, but is the result of a confirmed second-level HTLC
	// transaction. As a result, we can only spend this after a CSV delay
	// and CLTV locktime as part of the script enforced lease commitment
	// type.
	LeaseHtlcOfferedTimeoutSecondLevel StandardWitnessType = 19

	// LeaseHtlcAcceptedSuccessSecondLevel is a witness that allows us to
	// sweep an HTLC output that was offered to us, and for which we have a
	// payment preimage. This HTLC output isn't directly on our commitment
	// transaction, but is the result of confirmed second-level HTLC
	// transaction. As a result, we can only spend this after a CSV delay
	// and CLTV locktime as part of the script enforced lease commitment
	// type.
	LeaseHtlcAcceptedSuccessSecondLevel StandardWitnessType = 20

	// TaprootPubKeySpend is a witness type that allows us to spend a
	// regular p2tr output that's sent to an output which is under complete
	// control of the backing wallet.
	TaprootPubKeySpend StandardWitnessType = 21

	// TaprootLocalCommitSpend is a witness type that allows us to spend
	// our settled local commitment after a CSV delay when we force close
	// the channel.
	TaprootLocalCommitSpend StandardWitnessType = 22

	// TaprootRemoteCommitSpend is a witness type that allows us to spend
	// our settled local commitment after a CSV delay when the remote party
	// has force closed the channel.
	TaprootRemoteCommitSpend StandardWitnessType = 23

	// TaprootAnchorSweepSpend is the witness type we'll use for spending
	// our own anchor output.
	TaprootAnchorSweepSpend StandardWitnessType = 24

	// TaprootHtlcOfferedTimeoutSecondLevel is a witness that allows us to
	// timeout an HTLC we offered to the remote party on our commitment
	// transaction. We use this when we need to go on chain to time out an
	// HTLC.
	TaprootHtlcOfferedTimeoutSecondLevel StandardWitnessType = 25

	// TaprootHtlcAcceptedSuccessSecondLevel is a witness that allows us to
	// sweep an HTLC we accepted on our commitment transaction after we go
	// to the second level on chain.
	TaprootHtlcAcceptedSuccessSecondLevel StandardWitnessType = 26

	// TaprootHtlcSecondLevelRevoke is a witness that allows us to sweep an
	// HTLC on the revoked transaction of the remote party that goes to the
	// second level.
	TaprootHtlcSecondLevelRevoke StandardWitnessType = 27

	// TaprootHtlcAcceptedRevoke is a witness that allows us to sweep an
	// HTLC sent to us by the remote party in the event that they broadcast
	// a revoked state.
	TaprootHtlcAcceptedRevoke StandardWitnessType = 28

	// TaprootHtlcOfferedRevoke is a witness that allows us to sweep an
	// HTLC we offered to the remote party if they broadcast a revoked
	// commitment.
	TaprootHtlcOfferedRevoke StandardWitnessType = 29

	// TaprootHtlcOfferedRemoteTimeout is a witness that allows us to sweep
	// an HTLC we offered to the remote party that lies on the commitment
	// transaction for the remote party. We can spend this output after the
	// absolute CLTV timeout of the HTLC as passed.
	TaprootHtlcOfferedRemoteTimeout StandardWitnessType = 30

	// TaprootHtlcLocalOfferedTimeout is a witness type that allows us to
	// sign the second level HTLC timeout transaction when spending from an
	// HTLC residing on our local commitment transaction.
	//
	// This is used by the sweeper to re-sign inputs if it needs to
	// aggregate several second level HTLCs.
	TaprootHtlcLocalOfferedTimeout StandardWitnessType = 31

	// TaprootHtlcAcceptedRemoteSuccess is a witness that allows us to
	// sweep an HTLC that was offered to us by the remote party for a
	// taproot channels. We use this witness in the case that the remote
	// party goes to chain, and we know the pre-image to the HTLC. We can
	// sweep this without any additional timeout.
	TaprootHtlcAcceptedRemoteSuccess StandardWitnessType = 32

	// TaprootHtlcAcceptedLocalSuccess is a witness type that allows us to
	// sweep the HTLC offered to us on our local commitment transaction.
	// We'll use this when we need to go on chain to sweep the HTLC. In
	// this case, this is the second level HTLC success transaction.
	TaprootHtlcAcceptedLocalSuccess StandardWitnessType = 33

	// TaprootCommitmentRevoke is a witness that allows us to sweep the
	// settled output of a malicious counterparty's who broadcasts a
	// revoked taproot commitment transaction.
	TaprootCommitmentRevoke StandardWitnessType = 34
)

NOTE: When adding a new `StandardWitnessType`, also update the `WitnessType` protobuf enum and the `allWitnessTypes` map in the `walletrpc` package.

func (StandardWitnessType) AddWeightEstimation

func (wt StandardWitnessType) AddWeightEstimation(e *TxWeightEstimator) error

AddWeightEstimation adds the estimated size of the witness in bytes to the given weight estimator.

NOTE: This is part of the WitnessType interface.

func (StandardWitnessType) SizeUpperBound

func (wt StandardWitnessType) SizeUpperBound() (int, bool, error)

SizeUpperBound returns the maximum length of the witness of this witness type if it would be included in a tx. We also return if the output itself is a nested p2sh output, if so then we need to take into account the extra sigScript data size.

NOTE: This is part of the WitnessType interface.

func (StandardWitnessType) String

func (wt StandardWitnessType) String() string

String returns a human readable version of the target WitnessType.

NOTE: This is part of the WitnessType interface.

func (StandardWitnessType) WitnessGenerator

func (wt StandardWitnessType) WitnessGenerator(signer Signer,
	descriptor *SignDescriptor) WitnessGenerator

WitnessGenerator will return a WitnessGenerator function that an output uses to generate the witness and optionally the sigScript for a sweep transaction. The sigScript will be generated if the witness type warrants one for spending, such as the NestedWitnessKeyHash witness type.

NOTE: This is part of the WitnessType interface.

type TapscriptDescriptor

type TapscriptDescriptor interface {
	ScriptDescriptor

	// CtrlBlockForPath returns the control block for the given spending
	// path. For unknown paths, an error is returned.
	CtrlBlockForPath(path ScriptPath) (*txscript.ControlBlock, error)

	// TapTweak returns the top-level taproot tweak for the script.
	TapTweak() []byte

	// TapScriptTree returns the underlying tapscript tree.
	TapScriptTree() *txscript.IndexedTapScriptTree
}

TapscriptDescriptor is a super-set of the normal script multiplexer that adds in taproot specific details such as the control block, or top-level tap tweak.

type TxInfo

type TxInfo struct {
	// Fee is the fee of the tx.
	Fee btcutil.Amount

	// Weight is the weight of the tx.
	Weight int64
}

TxInfo describes properties of a parent tx that are relevant for CPFP.

func (*TxInfo) String

func (t *TxInfo) String() string

String returns a human readable version of the tx info.

type TxWeightEstimator

type TxWeightEstimator struct {
	// contains filtered or unexported fields
}

TxWeightEstimator is able to calculate weight estimates for transactions based on the input and output types. For purposes of estimation, all signatures are assumed to be of the maximum possible size, 73 bytes. Each method of the estimator returns an instance with the estimate applied. This allows callers to chain each of the methods

func (*TxWeightEstimator) AddNestedP2WKHInput

func (twe *TxWeightEstimator) AddNestedP2WKHInput() *TxWeightEstimator

AddNestedP2WKHInput updates the weight estimate to account for an additional input spending a P2SH output with a nested P2WKH redeem script.

func (*TxWeightEstimator) AddNestedP2WSHInput

func (twe *TxWeightEstimator) AddNestedP2WSHInput(witnessSize int) *TxWeightEstimator

AddNestedP2WSHInput updates the weight estimate to account for an additional input spending a P2SH output with a nested P2WSH redeem script.

func (*TxWeightEstimator) AddP2PKHInput

func (twe *TxWeightEstimator) AddP2PKHInput() *TxWeightEstimator

AddP2PKHInput updates the weight estimate to account for an additional input spending a P2PKH output.

func (*TxWeightEstimator) AddP2PKHOutput

func (twe *TxWeightEstimator) AddP2PKHOutput() *TxWeightEstimator

AddP2PKHOutput updates the weight estimate to account for an additional P2PKH output.

func (*TxWeightEstimator) AddP2SHOutput

func (twe *TxWeightEstimator) AddP2SHOutput() *TxWeightEstimator

AddP2SHOutput updates the weight estimate to account for an additional P2SH output.

func (*TxWeightEstimator) AddP2TROutput

func (twe *TxWeightEstimator) AddP2TROutput() *TxWeightEstimator

AddP2TROutput updates the weight estimate to account for an additional native SegWit v1 P2TR output.

func (*TxWeightEstimator) AddP2WKHInput

func (twe *TxWeightEstimator) AddP2WKHInput() *TxWeightEstimator

AddP2WKHInput updates the weight estimate to account for an additional input spending a native P2PWKH output.

func (*TxWeightEstimator) AddP2WKHOutput

func (twe *TxWeightEstimator) AddP2WKHOutput() *TxWeightEstimator

AddP2WKHOutput updates the weight estimate to account for an additional native P2WKH output.

func (*TxWeightEstimator) AddP2WSHOutput

func (twe *TxWeightEstimator) AddP2WSHOutput() *TxWeightEstimator

AddP2WSHOutput updates the weight estimate to account for an additional native P2WSH output.

func (*TxWeightEstimator) AddTaprootKeySpendInput

func (twe *TxWeightEstimator) AddTaprootKeySpendInput(
	hashType txscript.SigHashType) *TxWeightEstimator

AddTaprootKeySpendInput updates the weight estimate to account for an additional input spending a segwit v1 pay-to-taproot output using the key spend path. This accepts the sighash type being used since that has an influence on the total size of the signature.

func (*TxWeightEstimator) AddTapscriptInput

func (twe *TxWeightEstimator) AddTapscriptInput(leafWitnessSize int,
	tapscript *waddrmgr.Tapscript) *TxWeightEstimator

AddTapscriptInput updates the weight estimate to account for an additional input spending a segwit v1 pay-to-taproot output using the script path. This accepts the total size of the witness for the script leaf that is executed and adds the size of the control block to the total witness size.

NOTE: The leaf witness size must be calculated without the byte that accounts for the number of witness elements, only the total size of all elements on the stack that are consumed by the revealed script should be counted.

func (*TxWeightEstimator) AddTxOutput

func (twe *TxWeightEstimator) AddTxOutput(txOut *wire.TxOut) *TxWeightEstimator

AddTxOutput adds a known TxOut to the weight estimator.

func (*TxWeightEstimator) AddWitnessInput

func (twe *TxWeightEstimator) AddWitnessInput(witnessSize int) *TxWeightEstimator

AddWitnessInput updates the weight estimate to account for an additional input spending a native pay-to-witness output. This accepts the total size of the witness as a parameter.

func (*TxWeightEstimator) VSize

func (twe *TxWeightEstimator) VSize() int

VSize gets the estimated virtual size of the transactions, in vbytes.

func (*TxWeightEstimator) Weight

func (twe *TxWeightEstimator) Weight() int

Weight gets the estimated weight of the transaction.

type WitnessGenerator

type WitnessGenerator func(tx *wire.MsgTx, hc *txscript.TxSigHashes,
	inputIndex int) (*Script, error)

WitnessGenerator represents a function that is able to generate the final witness for a particular public key script. Additionally, if required, this function will also return the sigScript for spending nested P2SH witness outputs. This function acts as an abstraction layer, hiding the details of the underlying script.

type WitnessType

type WitnessType interface {
	// String returns a human readable version of the WitnessType.
	String() string

	// WitnessGenerator will return a WitnessGenerator function that an
	// output uses to generate the witness and optionally the sigScript for
	// a sweep transaction.
	WitnessGenerator(signer Signer,
		descriptor *SignDescriptor) WitnessGenerator

	// SizeUpperBound returns the maximum length of the witness of this
	// WitnessType if it would be included in a tx. It also returns if the
	// output itself is a nested p2sh output, if so then we need to take
	// into account the extra sigScript data size.
	SizeUpperBound() (int, bool, error)

	// AddWeightEstimation adds the estimated size of the witness in bytes
	// to the given weight estimator.
	AddWeightEstimation(e *TxWeightEstimator) error
}

WitnessType determines how an output's witness will be generated. This interface can be implemented to be used for custom sweep scripts if the pre-defined StandardWitnessType list doesn't provide a suitable one.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL