input

package
v0.0.0-...-9dd16ae Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2021 License: MIT Imports: 17 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

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

	// 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

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

	// 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 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

	// 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

	// 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

	// CommitWeight 724 weight
	CommitWeight = BaseCommitmentTxWeight + WitnessCommitmentTxWeight

	// AnchorCommitWeight 1124 weight
	AnchorCommitWeight = BaseAnchorCommitmentTxWeight + WitnessCommitmentTxWeight

	// HTLCWeight 172 weight
	HTLCWeight = witnessScaleFactor * HTLCSize

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

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

	// 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 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 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 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

	// 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 143 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 used for both confirmed and regular
	//              - OP_CSV: 1 byte	// HTLC script types. The size won't be correct in all cases,
	//              - OP_DROP: 1 byte	// but it is just an upper bound used for fee estimation in any case.
	//      - OP_ENDIF: 1 byte
	AcceptedHtlcScriptSize = 3*1 + 20 + 5*1 + 33 + 8*1 + 20 + 4*1 +
		33 + 5*1 + 4 + 8*1

	// AcceptedHtlcTimeoutWitnessSize 219
	//      - 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

	// AcceptedHtlcPenaltyWitnessSize 252 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

	// AcceptedHtlcSuccessWitnessSize 322 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)
	AcceptedHtlcSuccessWitnessSize = 1 + 1 + 1 + 73 + 1 + 73 + 1 + 32 + 1 +
		AcceptedHtlcScriptSize

	// OfferedHtlcScriptSize 136 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
	//              - OP_CSV: 1 byte
	//              - OP_DROP: 1 byte
	//      - OP_ENDIF: 1 byte
	OfferedHtlcScriptSize = 3*1 + 20 + 5*1 + 33 + 10*1 + 33 + 5*1 + 20 + 7*1

	// OfferedHtlcSuccessWitnessSize 245 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

	// 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)
	OfferedHtlcTimeoutWitnessSize = 1 + 1 + 1 + 73 + 1 + 73 + 1 + 1 + OfferedHtlcScriptSize

	// OfferedHtlcPenaltyWitnessSize 246 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

	// 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
)

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 (

	// SequenceLockTimeSeconds is the 22nd bit which indicates the lock
	// time is in seconds.
	SequenceLockTimeSeconds = uint32(1 << 22)
)

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 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 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 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 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

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 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 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

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 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

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 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 fro 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 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 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 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 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) 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 (*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, 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) SignDesc

func (i *BaseInput) SignDesc() *SignDescriptor

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

func (*BaseInput) WitnessType

func (i *BaseInput) 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 (*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, 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) SignDesc

func (i *HtlcSucceedInput) SignDesc() *SignDescriptor

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

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

	// 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,
		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
}

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
}

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 (*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 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 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

	// 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

	// 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

	// 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 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.

type Signer

type Signer interface {
	// 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 output 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, 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

	// 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

	// 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
)

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 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) 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) 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