github.com/decred/dcrlnd@v0.7.6/input/script_utils.go (about)

     1  package input
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/sha256"
     6  	"fmt"
     7  	"math/big"
     8  
     9  	"golang.org/x/crypto/ripemd160"
    10  
    11  	"github.com/decred/dcrd/dcrec/secp256k1/v4"
    12  	"github.com/decred/dcrd/dcrutil/v4"
    13  	"github.com/decred/dcrd/txscript/v4"
    14  	"github.com/decred/dcrd/wire"
    15  )
    16  
    17  // ScriptVerifyFlags are the flags used in script VMs when testing LN-related
    18  // scripts. These need to correspond to the current state of consensus rules
    19  // necessary for LN operation and the overall standard mempool settings.
    20  const ScriptVerifyFlags = txscript.ScriptDiscourageUpgradableNops | // standardness
    21  	txscript.ScriptVerifyCleanStack | // consensus
    22  	txscript.ScriptVerifyCheckLockTimeVerify | // consensus
    23  	txscript.ScriptVerifyCheckSequenceVerify | // consensus (lnfeatures)
    24  	txscript.ScriptVerifySHA256 // consensus (lnfeatures)
    25  
    26  // LNTxVersion is the version that transactions need to be defined to use so
    27  // that they are usable as ln transactions.
    28  const LNTxVersion uint16 = 2
    29  
    30  // TxWitness represents the witness data for a transaction.
    31  type TxWitness [][]byte
    32  
    33  // WitnessSerializeSize returns the number of bytes it would take to serialize
    34  // the given slice as if it were a bitcoin witness program.
    35  //
    36  // Note: this is only used as an acessory in certain tests in Decred.
    37  func (t TxWitness) WitnessSerializeSize() int {
    38  	// A varint to signal the number of elements the witness has.
    39  	n := wire.VarIntSerializeSize(uint64(len(t)))
    40  
    41  	// For each element in the witness, we'll need a varint to signal the
    42  	// size of the element, then finally the number of bytes the element
    43  	// itself comprises.
    44  	for _, witItem := range t {
    45  		n += wire.VarIntSerializeSize(uint64(len(witItem)))
    46  		n += len(witItem)
    47  	}
    48  
    49  	return n
    50  }
    51  
    52  var (
    53  	// TODO(roasbeef): remove these and use the one's defined in txscript
    54  	// within testnet-L.
    55  
    56  	// SequenceLockTimeSeconds is the 22nd bit which indicates the lock
    57  	// time is in seconds.
    58  	SequenceLockTimeSeconds = uint32(1 << 22)
    59  )
    60  
    61  // Signature is an interface for objects that can populate signatures during
    62  // witness construction.
    63  type Signature interface {
    64  	// Serialize returns a DER-encoded ECDSA signature.
    65  	Serialize() []byte
    66  
    67  	// Verify return true if the ECDSA signature is valid for the passed
    68  	// message digest under the provided public key.
    69  	Verify([]byte, *secp256k1.PublicKey) bool
    70  }
    71  
    72  // ScriptHashPkScript returns the p2sh pkscript for a given redeem script. This
    73  // is ready to be included in a transaction output.
    74  func ScriptHashPkScript(redeemScript []byte) ([]byte, error) {
    75  	scriptHash := dcrutil.Hash160(redeemScript)
    76  	bldr := txscript.NewScriptBuilder()
    77  
    78  	bldr.AddOp(txscript.OP_HASH160).AddData(scriptHash).AddOp(txscript.OP_EQUAL)
    79  	return bldr.Script()
    80  }
    81  
    82  // GenerateP2SH generates a pay-to-script-hash public key script paying to the
    83  // passed redeem script.
    84  func GenerateP2SH(script []byte) ([]byte, error) {
    85  	bldr := txscript.NewScriptBuilder()
    86  
    87  	bldr.AddOp(txscript.OP_HASH160)
    88  	scripthash := dcrutil.Hash160(script)
    89  	bldr.AddData(scripthash)
    90  	bldr.AddOp(txscript.OP_EQUAL)
    91  	return bldr.Script()
    92  }
    93  
    94  // GenerateP2PKH generates a pay-to-public-key-hash public key script paying to
    95  // the passed serialized public key.
    96  func GenerateP2PKH(pubkey []byte) ([]byte, error) {
    97  	bldr := txscript.NewScriptBuilder()
    98  
    99  	bldr.AddOp(txscript.OP_DUP)
   100  	bldr.AddOp(txscript.OP_HASH160)
   101  	pkhash := dcrutil.Hash160(pubkey)
   102  	bldr.AddData(pkhash)
   103  	bldr.AddOp(txscript.OP_EQUALVERIFY)
   104  	bldr.AddOp(txscript.OP_CHECKSIG)
   105  	return bldr.Script()
   106  }
   107  
   108  // GenMultiSigScript generates the non-p2sh'd multisig script for 2 of 2
   109  // pubkeys.
   110  func GenMultiSigScript(aPub, bPub []byte) ([]byte, error) {
   111  	if len(aPub) != 33 || len(bPub) != 33 {
   112  		return nil, fmt.Errorf("pubkey size error: compressed pubkeys only")
   113  	}
   114  
   115  	// Swap to sort pubkeys if needed. Keys are sorted in lexicographical
   116  	// order. The signatures within the scriptSig must also adhere to the
   117  	// order, ensuring that the signatures for each public key appears in
   118  	// the proper order on the stack.
   119  	if bytes.Compare(aPub, bPub) == 1 {
   120  		aPub, bPub = bPub, aPub
   121  	}
   122  
   123  	bldr := txscript.NewScriptBuilder()
   124  	bldr.AddOp(txscript.OP_2)
   125  	bldr.AddData(aPub) // Add both pubkeys (sorted).
   126  	bldr.AddData(bPub)
   127  	bldr.AddOp(txscript.OP_2)
   128  	bldr.AddOp(txscript.OP_CHECKMULTISIG)
   129  	return bldr.Script()
   130  }
   131  
   132  // WitnessStackToSigScript converts a witness stack, which is essentially just
   133  // an array of byte slices, to the equivalent signature script such that each
   134  // element in the witness stack is a data push.
   135  func WitnessStackToSigScript(witness [][]byte) ([]byte, error) {
   136  	bldr := txscript.NewScriptBuilder()
   137  	for _, data := range witness {
   138  		bldr.AddData(data)
   139  	}
   140  	return bldr.Script()
   141  }
   142  
   143  // SigScriptToWitnessStack converts a signatureScript to a slice of data pushes
   144  // (a witness stack). This is the inverse of the WitnessStackToSigScript
   145  // operation.
   146  //
   147  // This is currently restricted to a version 0 signature script.
   148  func SigScriptToWitnessStack(sigScript []byte) ([][]byte, error) {
   149  	const scriptVersion = 0
   150  
   151  	var data [][]byte
   152  	tokenizer := txscript.MakeScriptTokenizer(scriptVersion, sigScript)
   153  	for tokenizer.Next() {
   154  		op := tokenizer.Opcode()
   155  
   156  		if tokenizer.Data() != nil {
   157  			data = append(data, tokenizer.Data())
   158  		} else if op == txscript.OP_0 {
   159  			data = append(data, nil)
   160  		} else if op >= txscript.OP_1 && op <= txscript.OP_16 {
   161  			data = append(data, []byte{op - txscript.OP_1 + 1})
   162  		} else if op == txscript.OP_1NEGATE {
   163  			data = append(data, []byte{txscript.OP_1NEGATE})
   164  		}
   165  	}
   166  	if err := tokenizer.Err(); err != nil {
   167  		return nil, err
   168  	}
   169  	return data, nil
   170  
   171  }
   172  
   173  // GenFundingPkScript creates a redeem script, and its matching p2sh
   174  // output for the funding transaction.
   175  func GenFundingPkScript(aPub, bPub []byte, amt int64) ([]byte, *wire.TxOut, error) {
   176  	// As a sanity check, ensure that the passed amount is above zero.
   177  	if amt <= 0 {
   178  		return nil, nil, fmt.Errorf("can't create FundTx script with " +
   179  			"zero, or negative coins")
   180  	}
   181  
   182  	// First, create the 2-of-2 multi-sig script itself.
   183  	witnessScript, err := GenMultiSigScript(aPub, bPub)
   184  	if err != nil {
   185  		return nil, nil, err
   186  	}
   187  
   188  	// With the 2-of-2 script in had, generate a p2sh script which pays
   189  	// to the funding script.
   190  	pkScript, err := ScriptHashPkScript(witnessScript)
   191  	if err != nil {
   192  		return nil, nil, err
   193  	}
   194  
   195  	return witnessScript, wire.NewTxOut(amt, pkScript), nil
   196  }
   197  
   198  // SpendMultiSig generates the witness stack required to redeem the 2-of-2 p2sh
   199  // multi-sig output.
   200  func SpendMultiSig(witnessScript, pubA []byte, sigA Signature,
   201  	pubB []byte, sigB Signature) [][]byte {
   202  
   203  	witness := make([][]byte, 3)
   204  
   205  	// When initially generating the witnessScript, we sorted the
   206  	// serialized public keys in descending order. So we do a quick
   207  	// comparison in order ensure the signatures appear on the Script
   208  	// Virtual Machine stack in the correct order.
   209  	if bytes.Compare(pubA, pubB) == 1 {
   210  		witness[0] = append(sigB.Serialize(), byte(txscript.SigHashAll))
   211  		witness[1] = append(sigA.Serialize(), byte(txscript.SigHashAll))
   212  	} else {
   213  		witness[0] = append(sigA.Serialize(), byte(txscript.SigHashAll))
   214  		witness[1] = append(sigB.Serialize(), byte(txscript.SigHashAll))
   215  	}
   216  
   217  	// Finally, add the preimage as the last witness element.
   218  	witness[2] = witnessScript
   219  
   220  	return witness
   221  }
   222  
   223  // FindScriptOutputIndex finds the index of the public key script output
   224  // matching 'script'. Additionally, a boolean is returned indicating if a
   225  // matching output was found at all.
   226  //
   227  // NOTE: The search stops after the first matching script is found.
   228  func FindScriptOutputIndex(tx *wire.MsgTx, script []byte) (bool, uint32) {
   229  	found := false
   230  	index := uint32(0)
   231  	for i, txOut := range tx.TxOut {
   232  		if bytes.Equal(txOut.PkScript, script) {
   233  			found = true
   234  			index = uint32(i)
   235  			break
   236  		}
   237  	}
   238  
   239  	return found, index
   240  }
   241  
   242  // Ripemd160H calculates the ripemd160 of the passed byte slice. This is used to
   243  // calculate the intermediate hash for payment pre-images. Payment hashes are
   244  // the result of ripemd160(sha256(paymentPreimage)). As a result, the value
   245  // passed in should be the sha256 of the payment hash.
   246  func Ripemd160H(d []byte) []byte {
   247  	h := ripemd160.New()
   248  	h.Write(d)
   249  	return h.Sum(nil)
   250  }
   251  
   252  // SenderHTLCScript constructs the public key script for an outgoing HTLC
   253  // output payment for the sender's version of the commitment transaction. The
   254  // possible script paths from this output include:
   255  //
   256  //   - The sender timing out the HTLC using the second level HTLC timeout
   257  //     transaction.
   258  //   - The receiver of the HTLC claiming the output on-chain with the payment
   259  //     preimage.
   260  //   - The receiver of the HTLC sweeping all the funds in the case that a
   261  //     revoked commitment transaction bearing this HTLC was broadcast.
   262  //
   263  // If confirmedSpend=true, a 1 OP_CSV check will be added to the non-revocation
   264  // cases, to allow sweeping only after confirmation.
   265  //
   266  // Possible Input Scripts:
   267  //
   268  //	SENDR: <sendr sig> <recvr sig> <0> (spend using HTLC timeout transaction)
   269  //	RECVR: <recvr sig> <preimage>
   270  //	REVOK: <revoke sig> <revoke key>
   271  //	 * receiver revoke
   272  //
   273  // OP_DUP OP_HASH160 <revocation key hash160> OP_EQUAL
   274  // OP_IF
   275  //
   276  //	OP_CHECKSIG
   277  //
   278  // OP_ELSE
   279  //
   280  //	<recv htlc key>
   281  //	OP_SWAP OP_SIZE 32 OP_EQUAL
   282  //	OP_NOTIF
   283  //	    OP_DROP 2 OP_SWAP <sender htlc key> 2 OP_CHECKMULTISIG
   284  //	OP_ELSE
   285  //	    OP_SHA256 OP_RIPEMD160 <ripemd160(payment hash)> OP_EQUALVERIFY
   286  //	    OP_CHECKSIG
   287  //	OP_ENDIF
   288  //	[1 OP_CHECKSEQUENCEVERIFY OP_DROP] <- if allowing confirmed spend only.
   289  //
   290  // OP_ENDIF
   291  func SenderHTLCScript(senderHtlcKey, receiverHtlcKey,
   292  	revocationKey *secp256k1.PublicKey, paymentHash []byte,
   293  	confirmedSpend bool) ([]byte, error) {
   294  
   295  	builder := txscript.NewScriptBuilder()
   296  
   297  	// The opening operations are used to determine if this is the receiver
   298  	// of the HTLC attempting to sweep all the funds due to a contract
   299  	// breach. In this case, they'll place the revocation key at the top of
   300  	// the stack.
   301  	builder.AddOp(txscript.OP_DUP)
   302  	builder.AddOp(txscript.OP_HASH160)
   303  	builder.AddData(dcrutil.Hash160(revocationKey.SerializeCompressed()))
   304  	builder.AddOp(txscript.OP_EQUAL)
   305  
   306  	// If the hash matches, then this is the revocation clause. The output
   307  	// can be spent if the check sig operation passes.
   308  	builder.AddOp(txscript.OP_IF)
   309  	builder.AddOp(txscript.OP_CHECKSIG)
   310  
   311  	// Otherwise, this may either be the receiver of the HTLC claiming with
   312  	// the pre-image, or the sender of the HTLC sweeping the output after
   313  	// it has timed out.
   314  	builder.AddOp(txscript.OP_ELSE)
   315  
   316  	// We'll do a bit of set up by pushing the receiver's key on the top of
   317  	// the stack. This will be needed later if we decide that this is the
   318  	// sender activating the time out clause with the HTLC timeout
   319  	// transaction.
   320  	builder.AddData(receiverHtlcKey.SerializeCompressed())
   321  
   322  	// Atm, the top item of the stack is the receiverKey's so we use a swap
   323  	// to expose what is either the payment pre-image or a signature.
   324  	builder.AddOp(txscript.OP_SWAP)
   325  
   326  	// With the top item swapped, check if it's 32 bytes. If so, then this
   327  	// *may* be the payment pre-image.
   328  	builder.AddOp(txscript.OP_SIZE)
   329  	builder.AddInt64(32)
   330  	builder.AddOp(txscript.OP_EQUAL)
   331  
   332  	// If it isn't then this might be the sender of the HTLC activating the
   333  	// time out clause.
   334  	builder.AddOp(txscript.OP_NOTIF)
   335  
   336  	// We'll drop the OP_IF return value off the top of the stack so we can
   337  	// reconstruct the multi-sig script used as an off-chain covenant. If
   338  	// two valid signatures are provided, ten then output will be deemed as
   339  	// spendable.
   340  	builder.AddOp(txscript.OP_DROP)
   341  	builder.AddOp(txscript.OP_2)
   342  	builder.AddOp(txscript.OP_SWAP)
   343  	builder.AddData(senderHtlcKey.SerializeCompressed())
   344  	builder.AddOp(txscript.OP_2)
   345  	builder.AddOp(txscript.OP_CHECKMULTISIG)
   346  
   347  	// Otherwise, then the only other case is that this is the receiver of
   348  	// the HTLC sweeping it on-chain with the payment pre-image.
   349  	builder.AddOp(txscript.OP_ELSE)
   350  
   351  	// Hash the top item of the stack and compare it with the hash160 of
   352  	// the payment hash, which is already the sha256 of the payment
   353  	// pre-image. By using this little trick we're able save space on-chain
   354  	// as the witness includes a 20-byte hash rather than a 32-byte hash.
   355  	builder.AddOp(txscript.OP_SHA256)
   356  	builder.AddOp(txscript.OP_RIPEMD160)
   357  	builder.AddData(Ripemd160H(paymentHash))
   358  	builder.AddOp(txscript.OP_EQUALVERIFY)
   359  
   360  	// This checks the receiver's signature so that a third party with
   361  	// knowledge of the payment preimage still cannot steal the output.
   362  	builder.AddOp(txscript.OP_CHECKSIG)
   363  
   364  	// Close out the OP_IF statement above.
   365  	builder.AddOp(txscript.OP_ENDIF)
   366  
   367  	// Add 1 block CSV delay if a confirmation is required for the
   368  	// non-revocation clauses.
   369  	if confirmedSpend {
   370  		builder.AddOp(txscript.OP_1)
   371  		builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
   372  		builder.AddOp(txscript.OP_DROP)
   373  	}
   374  
   375  	// Close out the OP_IF statement at the top of the script.
   376  	builder.AddOp(txscript.OP_ENDIF)
   377  
   378  	return builder.Script()
   379  }
   380  
   381  // SenderHtlcSpendRevokeWithKey constructs a valid witness allowing the receiver of an
   382  // HTLC to claim the output with knowledge of the revocation private key in the
   383  // scenario that the sender of the HTLC broadcasts a previously revoked
   384  // commitment transaction. A valid spend requires knowledge of the private key
   385  // that corresponds to their revocation base point and also the private key fro
   386  // the per commitment point, and a valid signature under the combined public
   387  // key.
   388  func SenderHtlcSpendRevokeWithKey(signer Signer, signDesc *SignDescriptor,
   389  	revokeKey *secp256k1.PublicKey, sweepTx *wire.MsgTx) (TxWitness, error) {
   390  
   391  	sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
   392  	if err != nil {
   393  		return nil, err
   394  	}
   395  
   396  	// The stack required to sweep a revoke HTLC output consists simply of
   397  	// the exact witness stack as one of a regular p2pkh spend. The only
   398  	// difference is that the keys used were derived in an adversarial
   399  	// manner in order to encode the revocation contract into a sig+key
   400  	// pair.
   401  	witnessStack := TxWitness(make([][]byte, 3))
   402  	witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
   403  	witnessStack[1] = revokeKey.SerializeCompressed()
   404  	witnessStack[2] = signDesc.WitnessScript
   405  
   406  	return witnessStack, nil
   407  }
   408  
   409  // SenderHtlcSpendRevoke constructs a valid witness allowing the receiver of an
   410  // HTLC to claim the output with knowledge of the revocation private key in the
   411  // scenario that the sender of the HTLC broadcasts a previously revoked
   412  // commitment transaction.  This method first derives the appropriate revocation
   413  // key, and requires that the provided SignDescriptor has a local revocation
   414  // basepoint and commitment secret in the PubKey and DoubleTweak fields,
   415  // respectively.
   416  func SenderHtlcSpendRevoke(signer Signer, signDesc *SignDescriptor,
   417  	sweepTx *wire.MsgTx) (TxWitness, error) {
   418  
   419  	revokeKey, err := deriveRevokePubKey(signDesc)
   420  	if err != nil {
   421  		return nil, err
   422  	}
   423  
   424  	return SenderHtlcSpendRevokeWithKey(signer, signDesc, revokeKey, sweepTx)
   425  }
   426  
   427  // IsHtlcSpendRevoke is used to determine if the passed spend is spending a
   428  // HTLC output using the revocation key.
   429  func IsHtlcSpendRevoke(txIn *wire.TxIn, signDesc *SignDescriptor) (
   430  	bool, error) {
   431  
   432  	revokeKey, err := deriveRevokePubKey(signDesc)
   433  	if err != nil {
   434  		return false, err
   435  	}
   436  
   437  	witness, err := SigScriptToWitnessStack(txIn.SignatureScript)
   438  	if err != nil {
   439  		return false, err
   440  	}
   441  	if len(witness) == 3 &&
   442  		bytes.Equal(witness[1], revokeKey.SerializeCompressed()) {
   443  		return true, nil
   444  	}
   445  
   446  	return false, nil
   447  }
   448  
   449  // SenderHtlcSpendRedeem constructs a valid witness allowing the receiver of an
   450  // HTLC to redeem the pending output in the scenario that the sender broadcasts
   451  // their version of the commitment transaction. A valid spend requires
   452  // knowledge of the payment preimage, and a valid signature under the receivers
   453  // public key.
   454  func SenderHtlcSpendRedeem(signer Signer, signDesc *SignDescriptor,
   455  	sweepTx *wire.MsgTx, paymentPreimage []byte) (TxWitness, error) {
   456  
   457  	sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
   458  	if err != nil {
   459  		return nil, err
   460  	}
   461  
   462  	// The stack required to spend this output is simply the signature
   463  	// generated above under the receiver's public key, and the payment
   464  	// pre-image.
   465  	witnessStack := TxWitness(make([][]byte, 3))
   466  	witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
   467  	witnessStack[1] = paymentPreimage
   468  	witnessStack[2] = signDesc.WitnessScript
   469  
   470  	return witnessStack, nil
   471  }
   472  
   473  // SenderHtlcSpendTimeout constructs a valid witness allowing the sender of an
   474  // HTLC to activate the time locked covenant clause of a soon to be expired
   475  // HTLC.  This script simply spends the multi-sig output using the
   476  // pre-generated HTLC timeout transaction.
   477  func SenderHtlcSpendTimeout(receiverSig Signature,
   478  	receiverSigHash txscript.SigHashType, signer Signer,
   479  	signDesc *SignDescriptor, htlcTimeoutTx *wire.MsgTx) (
   480  	TxWitness, error) {
   481  
   482  	sweepSig, err := signer.SignOutputRaw(htlcTimeoutTx, signDesc)
   483  	if err != nil {
   484  		return nil, err
   485  	}
   486  
   487  	// We place a zero as the first item of the evaluated witness stack in
   488  	// order to force Script execution to the HTLC timeout clause.
   489  	witnessStack := TxWitness(make([][]byte, 4))
   490  	witnessStack[0] = append(receiverSig.Serialize(), byte(receiverSigHash))
   491  	witnessStack[1] = append(sweepSig.Serialize(), byte(signDesc.HashType))
   492  	witnessStack[2] = nil
   493  	witnessStack[3] = signDesc.WitnessScript
   494  
   495  	return witnessStack, nil
   496  }
   497  
   498  // ReceiverHTLCScript constructs the public key script for an incoming HTLC
   499  // output payment for the receiver's version of the commitment transaction. The
   500  // possible execution paths from this script include: * The receiver of the
   501  // HTLC uses its second level HTLC transaction to advance the state of the HTLC
   502  // into the delay+claim state.  * The sender of the HTLC sweeps all the funds
   503  // of the HTLC as a breached commitment was broadcast.  * The sender of the
   504  // HTLC sweeps the HTLC on-chain after the timeout period of the HTLC has
   505  // passed.
   506  //
   507  // If confirmedSpend=true, a 1 OP_CSV check will be added to the non-revocation
   508  // cases, to allow sweeping only after confirmation.
   509  //
   510  // Possible Input Scripts:
   511  //
   512  //	RECVR: <sender sig> <recvr sig> <preimage> (spend using HTLC success transaction)
   513  //	REVOK: <sig> <key>
   514  //	SENDR: <sig> 0
   515  //
   516  // OP_DUP OP_HASH160 <revocation key hash160> OP_EQUAL
   517  // OP_IF
   518  //
   519  //	OP_CHECKSIG
   520  //
   521  // OP_ELSE
   522  //
   523  //	<sendr htlc key>
   524  //	OP_SWAP OP_SIZE 32 OP_EQUAL
   525  //	OP_IF
   526  //	    OP_HASH160 <ripemd160(payment hash)> OP_EQUALVERIFY
   527  //	    2 OP_SWAP <recvr htlc key> 2 OP_CHECKMULTISIG
   528  //	OP_ELSE
   529  //	    OP_DROP <cltv expiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
   530  //	    OP_CHECKSIG
   531  //	OP_ENDIF
   532  //	[1 OP_CHECKSEQUENCEVERIFY OP_DROP] <- if allowing confirmed spend only.
   533  //
   534  // OP_ENDIF
   535  func ReceiverHTLCScript(cltvExpiry uint32, senderHtlcKey,
   536  	receiverHtlcKey, revocationKey *secp256k1.PublicKey,
   537  	paymentHash []byte, confirmedSpend bool) ([]byte, error) {
   538  
   539  	builder := txscript.NewScriptBuilder()
   540  
   541  	// The opening operations are used to determine if this is the sender
   542  	// of the HTLC attempting to sweep all the funds due to a contract
   543  	// breach. In this case, they'll place the revocation key at the top of
   544  	// the stack.
   545  	builder.AddOp(txscript.OP_DUP)
   546  	builder.AddOp(txscript.OP_HASH160)
   547  	builder.AddData(dcrutil.Hash160(revocationKey.SerializeCompressed()))
   548  	builder.AddOp(txscript.OP_EQUAL)
   549  
   550  	// If the hash matches, then this is the revocation clause. The output
   551  	// can be spent if the check sig operation passes.
   552  	builder.AddOp(txscript.OP_IF)
   553  	builder.AddOp(txscript.OP_CHECKSIG)
   554  
   555  	// Otherwise, this may either be the receiver of the HTLC starting the
   556  	// claiming process via the second level HTLC success transaction and
   557  	// the pre-image, or the sender of the HTLC sweeping the output after
   558  	// it has timed out.
   559  	builder.AddOp(txscript.OP_ELSE)
   560  
   561  	// We'll do a bit of set up by pushing the sender's key on the top of
   562  	// the stack. This will be needed later if we decide that this is the
   563  	// receiver transitioning the output to the claim state using their
   564  	// second-level HTLC success transaction.
   565  	builder.AddData(senderHtlcKey.SerializeCompressed())
   566  
   567  	// Atm, the top item of the stack is the sender's key so we use a swap
   568  	// to expose what is either the payment pre-image or something else.
   569  	builder.AddOp(txscript.OP_SWAP)
   570  
   571  	// With the top item swapped, check if it's 32 bytes. If so, then this
   572  	// *may* be the payment pre-image.
   573  	builder.AddOp(txscript.OP_SIZE)
   574  	builder.AddInt64(32)
   575  	builder.AddOp(txscript.OP_EQUAL)
   576  
   577  	// If the item on the top of the stack is 32-bytes, then it is the
   578  	// proper size, so this indicates that the receiver of the HTLC is
   579  	// attempting to claim the output on-chain by transitioning the state
   580  	// of the HTLC to delay+claim.
   581  	builder.AddOp(txscript.OP_IF)
   582  
   583  	// Next we'll hash the item on the top of the stack, if it matches the
   584  	// payment pre-image, then we'll continue. Otherwise, we'll end the
   585  	// script here as this is the invalid payment pre-image.
   586  	builder.AddOp(txscript.OP_SHA256)
   587  	builder.AddOp(txscript.OP_RIPEMD160)
   588  	builder.AddData(Ripemd160H(paymentHash))
   589  	builder.AddOp(txscript.OP_EQUALVERIFY)
   590  
   591  	// If the payment hash matches, then we'll also need to satisfy the
   592  	// multi-sig covenant by providing both signatures of the sender and
   593  	// receiver. If the convenient is met, then we'll allow the spending of
   594  	// this output, but only by the HTLC success transaction.
   595  	builder.AddOp(txscript.OP_2)
   596  	builder.AddOp(txscript.OP_SWAP)
   597  	builder.AddData(receiverHtlcKey.SerializeCompressed())
   598  	builder.AddOp(txscript.OP_2)
   599  	builder.AddOp(txscript.OP_CHECKMULTISIG)
   600  
   601  	// Otherwise, this might be the sender of the HTLC attempting to sweep
   602  	// it on-chain after the timeout.
   603  	builder.AddOp(txscript.OP_ELSE)
   604  
   605  	// We'll drop the extra item (which is the output from evaluating the
   606  	// OP_EQUAL) above from the stack.
   607  	builder.AddOp(txscript.OP_DROP)
   608  
   609  	// With that item dropped off, we can now enforce the absolute
   610  	// lock-time required to timeout the HTLC. If the time has passed, then
   611  	// we'll proceed with a checksig to ensure that this is actually the
   612  	// sender of he original HTLC.
   613  	builder.AddInt64(int64(cltvExpiry))
   614  	builder.AddOp(txscript.OP_CHECKLOCKTIMEVERIFY)
   615  	builder.AddOp(txscript.OP_DROP)
   616  	builder.AddOp(txscript.OP_CHECKSIG)
   617  
   618  	// Close out the inner if statement.
   619  	builder.AddOp(txscript.OP_ENDIF)
   620  
   621  	// Add 1 block CSV delay for non-revocation clauses if confirmation is
   622  	// required.
   623  	if confirmedSpend {
   624  		builder.AddOp(txscript.OP_1)
   625  		builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
   626  		builder.AddOp(txscript.OP_DROP)
   627  	}
   628  
   629  	// Close out the outer if statement.
   630  	builder.AddOp(txscript.OP_ENDIF)
   631  
   632  	return builder.Script()
   633  }
   634  
   635  // ReceiverHtlcSpendRedeem constructs a valid witness allowing the receiver of
   636  // an HTLC to redeem the conditional payment in the event that their commitment
   637  // transaction is broadcast. This clause transitions the state of the HLTC
   638  // output into the delay+claim state by activating the off-chain covenant bound
   639  // by the 2-of-2 multi-sig output. The HTLC success timeout transaction being
   640  // signed has a relative timelock delay enforced by its sequence number. This
   641  // delay give the sender of the HTLC enough time to revoke the output if this
   642  // is a breach commitment transaction.
   643  func ReceiverHtlcSpendRedeem(senderSig Signature,
   644  	senderSigHash txscript.SigHashType, paymentPreimage []byte,
   645  	signer Signer, signDesc *SignDescriptor, htlcSuccessTx *wire.MsgTx) (
   646  	TxWitness, error) {
   647  
   648  	// First, we'll generate a signature for the HTLC success transaction.
   649  	// The signDesc should be signing with the public key used as the
   650  	// receiver's public key and also the correct single tweak.
   651  	sweepSig, err := signer.SignOutputRaw(htlcSuccessTx, signDesc)
   652  	if err != nil {
   653  		return nil, err
   654  	}
   655  
   656  	// The final witness stack is used the provide the script with the
   657  	// payment pre-image, and also execute the multi-sig clause after the
   658  	// pre-images matches.
   659  	witnessStack := TxWitness(make([][]byte, 4))
   660  	witnessStack[0] = append(senderSig.Serialize(), byte(senderSigHash))
   661  	witnessStack[1] = append(sweepSig.Serialize(), byte(signDesc.HashType))
   662  	witnessStack[2] = paymentPreimage
   663  	witnessStack[3] = signDesc.WitnessScript
   664  
   665  	return witnessStack, nil
   666  }
   667  
   668  // ReceiverHtlcSpendRevokeWithKey constructs a valid witness allowing the sender of an
   669  // HTLC within a previously revoked commitment transaction to re-claim the
   670  // pending funds in the case that the receiver broadcasts this revoked
   671  // commitment transaction.
   672  func ReceiverHtlcSpendRevokeWithKey(signer Signer, signDesc *SignDescriptor,
   673  	revokeKey *secp256k1.PublicKey, sweepTx *wire.MsgTx) (TxWitness, error) {
   674  
   675  	// First, we'll generate a signature for the sweep transaction.  The
   676  	// signDesc should be signing with the public key used as the fully
   677  	// derived revocation public key and also the correct double tweak
   678  	// value.
   679  	sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
   680  	if err != nil {
   681  		return nil, err
   682  	}
   683  
   684  	// We place a zero, then one as the first items in the evaluated
   685  	// witness stack in order to force script execution to the HTLC
   686  	// revocation clause.
   687  	witnessStack := TxWitness(make([][]byte, 3))
   688  	witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
   689  	witnessStack[1] = revokeKey.SerializeCompressed()
   690  	witnessStack[2] = signDesc.WitnessScript
   691  
   692  	return witnessStack, nil
   693  }
   694  
   695  func deriveRevokePubKey(signDesc *SignDescriptor) (*secp256k1.PublicKey, error) {
   696  	if signDesc.KeyDesc.PubKey == nil {
   697  		return nil, fmt.Errorf("cannot generate witness with nil " +
   698  			"KeyDesc pubkey")
   699  	}
   700  
   701  	// Derive the revocation key using the local revocation base point and
   702  	// commitment point.
   703  	revokeKey := DeriveRevocationPubkey(
   704  		signDesc.KeyDesc.PubKey,
   705  		signDesc.DoubleTweak.PubKey(),
   706  	)
   707  
   708  	return revokeKey, nil
   709  }
   710  
   711  // ReceiverHtlcSpendRevoke constructs a valid witness allowing the sender of an
   712  // HTLC within a previously revoked commitment transaction to re-claim the
   713  // pending funds in the case that the receiver broadcasts this revoked
   714  // commitment transaction. This method first derives the appropriate revocation
   715  // key, and requires that the provided SignDescriptor has a local revocation
   716  // basepoint and commitment secret in the PubKey and DoubleTweak fields,
   717  // respectively.
   718  func ReceiverHtlcSpendRevoke(signer Signer, signDesc *SignDescriptor,
   719  	sweepTx *wire.MsgTx) (TxWitness, error) {
   720  
   721  	revokeKey, err := deriveRevokePubKey(signDesc)
   722  	if err != nil {
   723  		return nil, err
   724  	}
   725  
   726  	return ReceiverHtlcSpendRevokeWithKey(signer, signDesc, revokeKey, sweepTx)
   727  }
   728  
   729  // ReceiverHtlcSpendTimeout constructs a valid witness allowing the sender of
   730  // an HTLC to recover the pending funds after an absolute timeout in the
   731  // scenario that the receiver of the HTLC broadcasts their version of the
   732  // commitment transaction. If the caller has already set the lock time on the
   733  // spending transaction, than a value of -1 can be passed for the cltvExpiry
   734  // value.
   735  //
   736  // NOTE: The target input of the passed transaction MUST NOT have a final
   737  // sequence number. Otherwise, the OP_CHECKLOCKTIMEVERIFY check will fail.
   738  func ReceiverHtlcSpendTimeout(signer Signer, signDesc *SignDescriptor,
   739  	sweepTx *wire.MsgTx, cltvExpiry int32) (TxWitness, error) {
   740  
   741  	// If the caller set a proper timeout value, then we'll apply it
   742  	// directly to the transaction.
   743  	if cltvExpiry != -1 {
   744  		// The HTLC output has an absolute time period before we are
   745  		// permitted to recover the pending funds. Therefore we need to
   746  		// set the locktime on this sweeping transaction in order to
   747  		// pass Script verification.
   748  		sweepTx.LockTime = uint32(cltvExpiry)
   749  	}
   750  
   751  	// With the lock time on the transaction set, we'll not generate a
   752  	// signature for the sweep transaction. The passed sign descriptor
   753  	// should be created using the raw public key of the sender (w/o the
   754  	// single tweak applied), and the single tweak set to the proper value
   755  	// taking into account the current state's point.
   756  	sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
   757  	if err != nil {
   758  		return nil, err
   759  	}
   760  
   761  	witnessStack := TxWitness(make([][]byte, 3))
   762  	witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
   763  	witnessStack[1] = nil
   764  	witnessStack[2] = signDesc.WitnessScript
   765  
   766  	return witnessStack, nil
   767  }
   768  
   769  // ReplaceReceiverHtlcSpendRedeemPreimage replaces the pregimage in a sigScript
   770  // generated by receiverHtlcSpendRedeemPreimage with the provided preimage. This
   771  // will generate an undefined result script if the sigScript was *not* generated
   772  // by the provided function (ie: this must be the sigScript of a
   773  // SignedSuccessTx, used to redeem an HTLC).
   774  //
   775  // This function returns the new sigScript to replace the older sigScript.
   776  func ReplaceReceiverHtlcSpendRedeemPreimage(sigScript, preimage []byte) ([]byte, error) {
   777  	sigScriptPushes, err := SigScriptToWitnessStack(sigScript)
   778  	if err != nil {
   779  		return nil, err
   780  	}
   781  	if len(sigScriptPushes) != 4 {
   782  		return nil, fmt.Errorf("the provided sigScript does not have 4 elements")
   783  	}
   784  
   785  	return txscript.NewScriptBuilder().
   786  		AddData(sigScriptPushes[0]). // sender sig
   787  		AddData(sigScriptPushes[1]). // receiver sig
   788  		AddData(preimage).           // preimage
   789  		AddData(sigScriptPushes[3]). // redeem script
   790  		Script()
   791  }
   792  
   793  // SecondLevelHtlcScript is the uniform script that's used as the output for
   794  // the second-level HTLC transactions. The second level transaction act as a
   795  // sort of covenant, ensuring that a 2-of-2 multi-sig output can only be spent
   796  // in a particular way, and to a particular output.
   797  //
   798  // Possible Input Scripts:
   799  //
   800  //   - To revoke an HTLC output that has been transitioned to the claim+delay
   801  //     state:
   802  //
   803  //   - <revoke sig> 1
   804  //
   805  //   - To claim and HTLC output, either with a pre-image or due to a timeout:
   806  //
   807  //   - <delay sig> 0
   808  //
   809  // OP_IF
   810  //
   811  //	<revoke key>
   812  //
   813  // OP_ELSE
   814  //
   815  //	<delay in blocks>
   816  //	OP_CHECKSEQUENCEVERIFY
   817  //	OP_DROP
   818  //	<delay key>
   819  //
   820  // OP_ENDIF
   821  // OP_CHECKSIG
   822  //
   823  // TODO(roasbeef): possible renames for second-level
   824  //   - transition?
   825  //   - covenant output
   826  func SecondLevelHtlcScript(revocationKey, delayKey *secp256k1.PublicKey,
   827  	csvDelay uint32) ([]byte, error) {
   828  
   829  	builder := txscript.NewScriptBuilder()
   830  
   831  	// If this is the revocation clause for this script is to be executed,
   832  	// the spender will push a 1, forcing us to hit the true clause of this
   833  	// if statement.
   834  	builder.AddOp(txscript.OP_IF)
   835  
   836  	// If this this is the revocation case, then we'll push the revocation
   837  	// public key on the stack.
   838  	builder.AddData(revocationKey.SerializeCompressed())
   839  
   840  	// Otherwise, this is either the sender or receiver of the HTLC
   841  	// attempting to claim the HTLC output.
   842  	builder.AddOp(txscript.OP_ELSE)
   843  
   844  	// In order to give the other party time to execute the revocation
   845  	// clause above, we require a relative timeout to pass before the
   846  	// output can be spent.
   847  	builder.AddInt64(int64(csvDelay))
   848  	builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
   849  	builder.AddOp(txscript.OP_DROP)
   850  
   851  	// If the relative timelock passes, then we'll add the delay key to the
   852  	// stack to ensure that we properly authenticate the spending party.
   853  	builder.AddData(delayKey.SerializeCompressed())
   854  
   855  	// Close out the if statement.
   856  	builder.AddOp(txscript.OP_ENDIF)
   857  
   858  	// In either case, we'll ensure that only either the party possessing
   859  	// the revocation private key, or the delay private key is able to
   860  	// spend this output.
   861  	builder.AddOp(txscript.OP_CHECKSIG)
   862  
   863  	return builder.Script()
   864  }
   865  
   866  // LeaseSecondLevelHtlcScript is the uniform script that's used as the output for
   867  // the second-level HTLC transactions. The second level transaction acts as a
   868  // sort of covenant, ensuring that a 2-of-2 multi-sig output can only be
   869  // spent in a particular way, and to a particular output.
   870  //
   871  // Possible Input Scripts:
   872  //
   873  //   - To revoke an HTLC output that has been transitioned to the claim+delay
   874  //     state:
   875  //
   876  //   - <revoke sig> 1
   877  //
   878  //   - To claim an HTLC output, either with a pre-image or due to a timeout:
   879  //
   880  //   - <delay sig> 0
   881  //
   882  // OP_IF
   883  //
   884  //	<revoke key>
   885  //
   886  // OP_ELSE
   887  //
   888  //	<lease maturity in blocks>
   889  //	OP_CHECKLOCKTIMEVERIFY
   890  //	OP_DROP
   891  //	<delay in blocks>
   892  //	OP_CHECKSEQUENCEVERIFY
   893  //	OP_DROP
   894  //	<delay key>
   895  //
   896  // OP_ENDIF
   897  // OP_CHECKSIG
   898  func LeaseSecondLevelHtlcScript(revocationKey, delayKey *secp256k1.PublicKey,
   899  	csvDelay, cltvExpiry uint32) ([]byte, error) {
   900  
   901  	builder := txscript.NewScriptBuilder()
   902  
   903  	// If this is the revocation clause for this script is to be executed,
   904  	// the spender will push a 1, forcing us to hit the true clause of this
   905  	// if statement.
   906  	builder.AddOp(txscript.OP_IF)
   907  
   908  	// If this this is the revocation case, then we'll push the revocation
   909  	// public key on the stack.
   910  	builder.AddData(revocationKey.SerializeCompressed())
   911  
   912  	// Otherwise, this is either the sender or receiver of the HTLC
   913  	// attempting to claim the HTLC output.
   914  	builder.AddOp(txscript.OP_ELSE)
   915  
   916  	// The channel initiator always has the additional channel lease
   917  	// expiration constraint for outputs that pay to them which must be
   918  	// satisfied.
   919  	builder.AddInt64(int64(cltvExpiry))
   920  	builder.AddOp(txscript.OP_CHECKLOCKTIMEVERIFY)
   921  	builder.AddOp(txscript.OP_DROP)
   922  
   923  	// In order to give the other party time to execute the revocation
   924  	// clause above, we require a relative timeout to pass before the
   925  	// output can be spent.
   926  	builder.AddInt64(int64(csvDelay))
   927  	builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
   928  	builder.AddOp(txscript.OP_DROP)
   929  
   930  	// If the relative timelock passes, then we'll add the delay key to the
   931  	// stack to ensure that we properly authenticate the spending party.
   932  	builder.AddData(delayKey.SerializeCompressed())
   933  
   934  	// Close out the if statement.
   935  	builder.AddOp(txscript.OP_ENDIF)
   936  
   937  	// In either case, we'll ensure that only either the party possessing
   938  	// the revocation private key, or the delay private key is able to
   939  	// spend this output.
   940  	builder.AddOp(txscript.OP_CHECKSIG)
   941  
   942  	return builder.Script()
   943  }
   944  
   945  // HtlcSpendSuccess spends a second-level HTLC output. This function is to be
   946  // used by the sender of an HTLC to claim the output after a relative timeout
   947  // or the receiver of the HTLC to claim on-chain with the pre-image.
   948  func HtlcSpendSuccess(signer Signer, signDesc *SignDescriptor,
   949  	sweepTx *wire.MsgTx, csvDelay uint32) (TxWitness, error) {
   950  
   951  	// We're required to wait a relative period of time before we can sweep
   952  	// the output in order to allow the other party to contest our claim of
   953  	// validity to this version of the commitment transaction.
   954  	sweepTx.TxIn[0].Sequence = LockTimeToSequence(false, csvDelay)
   955  
   956  	// Finally, OP_CSV requires that the version of the transaction
   957  	// spending a pkscript with OP_CSV within it *must* be >= 2.
   958  	sweepTx.Version = 2
   959  
   960  	// With the proper sequence and version set, we'll now sign the timeout
   961  	// transaction using the passed signed descriptor. In order to generate
   962  	// a valid signature, then signDesc should be using the base delay
   963  	// public key, and the proper single tweak bytes.
   964  	sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
   965  	if err != nil {
   966  		return nil, err
   967  	}
   968  
   969  	// We set a zero as the first element the witness stack (ignoring the
   970  	// witness script), in order to force execution to the second portion
   971  	// of the if clause.
   972  	witnessStack := TxWitness(make([][]byte, 3))
   973  	witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
   974  	witnessStack[1] = nil
   975  	witnessStack[2] = signDesc.WitnessScript
   976  
   977  	return witnessStack, nil
   978  }
   979  
   980  // HtlcSpendRevoke spends a second-level HTLC output. This function is to be
   981  // used by the sender or receiver of an HTLC to claim the HTLC after a revoked
   982  // commitment transaction was broadcast.
   983  func HtlcSpendRevoke(signer Signer, signDesc *SignDescriptor,
   984  	revokeTx *wire.MsgTx) (TxWitness, error) {
   985  
   986  	// We don't need any spacial modifications to the transaction as this
   987  	// is just sweeping a revoked HTLC output. So we'll generate a regular
   988  	// witness signature.
   989  	sweepSig, err := signer.SignOutputRaw(revokeTx, signDesc)
   990  	if err != nil {
   991  		return nil, err
   992  	}
   993  
   994  	// We set a one as the first element the witness stack (ignoring the
   995  	// witness script), in order to force execution to the revocation
   996  	// clause in the second level HTLC script.
   997  	witnessStack := TxWitness(make([][]byte, 3))
   998  	witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
   999  	witnessStack[1] = []byte{1}
  1000  	witnessStack[2] = signDesc.WitnessScript
  1001  
  1002  	return witnessStack, nil
  1003  }
  1004  
  1005  // HtlcSecondLevelSpend exposes the public witness generation function for
  1006  // spending an HTLC success transaction, either due to an expiring time lock or
  1007  // having had the payment preimage. This method is able to spend any
  1008  // second-level HTLC transaction, assuming the caller sets the locktime or
  1009  // seqno properly.
  1010  //
  1011  // NOTE: The caller MUST set the txn version, sequence number, and sign
  1012  // descriptor's sig hash cache before invocation.
  1013  func HtlcSecondLevelSpend(signer Signer, signDesc *SignDescriptor,
  1014  	sweepTx *wire.MsgTx) (TxWitness, error) {
  1015  
  1016  	// With the proper sequence and version set, we'll now sign the timeout
  1017  	// transaction using the passed signed descriptor. In order to generate
  1018  	// a valid signature, then signDesc should be using the base delay
  1019  	// public key, and the proper single tweak bytes.
  1020  	sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
  1021  	if err != nil {
  1022  		return nil, err
  1023  	}
  1024  
  1025  	// We set a zero as the first element the witness stack (ignoring the
  1026  	// witness script), in order to force execution to the second portion
  1027  	// of the if clause.
  1028  	witnessStack := TxWitness(make([][]byte, 3))
  1029  	witnessStack[0] = append(sweepSig.Serialize(), byte(txscript.SigHashAll))
  1030  	witnessStack[1] = nil
  1031  	witnessStack[2] = signDesc.WitnessScript
  1032  
  1033  	return witnessStack, nil
  1034  }
  1035  
  1036  // LockTimeToSequence converts the passed relative locktime to a sequence
  1037  // number in accordance to BIP-68.  See:
  1038  // https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki *
  1039  // (Compatibility)
  1040  func LockTimeToSequence(isSeconds bool, locktime uint32) uint32 {
  1041  	if !isSeconds {
  1042  		// The locktime is to be expressed in confirmations.
  1043  		return locktime
  1044  	}
  1045  
  1046  	// Set the 22nd bit which indicates the lock time is in seconds, then
  1047  	// shift the locktime over by 9 since the time granularity is in
  1048  	// 512-second intervals (2^9). This results in a max lock-time of
  1049  	// 33,554,431 seconds, or 1.06 years.
  1050  	return SequenceLockTimeSeconds | (locktime >> 9)
  1051  }
  1052  
  1053  // CommitScriptToSelf constructs the public key script for the output on the
  1054  // commitment transaction paying to the "owner" of said commitment transaction.
  1055  // If the other party learns of the preimage to the revocation hash, then they
  1056  // can claim all the settled funds in the channel, plus the unsettled funds.
  1057  //
  1058  // Possible Input Scripts:
  1059  //
  1060  //	REVOKE:     <sig> 1
  1061  //	SENDRSWEEP: <sig> <emptyvector>
  1062  //
  1063  // Output Script:
  1064  //
  1065  //	OP_IF
  1066  //	    <revokeKey>
  1067  //	OP_ELSE
  1068  //	    <numRelativeBlocks> OP_CHECKSEQUENCEVERIFY OP_DROP
  1069  //	    <timeKey>
  1070  //	OP_ENDIF
  1071  //	OP_CHECKSIG
  1072  func CommitScriptToSelf(csvTimeout uint32, selfKey, revokeKey *secp256k1.PublicKey) ([]byte, error) {
  1073  	// This script is spendable under two conditions: either the
  1074  	// 'csvTimeout' has passed and we can redeem our funds, or they can
  1075  	// produce a valid signature with the revocation public key. The
  1076  	// revocation public key will *only* be known to the other party if we
  1077  	// have divulged the revocation hash, allowing them to homomorphically
  1078  	// derive the proper private key which corresponds to the revoke public
  1079  	// key.
  1080  	builder := txscript.NewScriptBuilder()
  1081  
  1082  	builder.AddOp(txscript.OP_IF)
  1083  
  1084  	// If a valid signature using the revocation key is presented, then
  1085  	// allow an immediate spend provided the proper signature.
  1086  	builder.AddData(revokeKey.SerializeCompressed())
  1087  
  1088  	builder.AddOp(txscript.OP_ELSE)
  1089  
  1090  	// Otherwise, we can re-claim our funds after a CSV delay of
  1091  	// 'csvTimeout' timeout blocks, and a valid signature.
  1092  	builder.AddInt64(int64(csvTimeout))
  1093  	builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
  1094  	builder.AddOp(txscript.OP_DROP)
  1095  	builder.AddData(selfKey.SerializeCompressed())
  1096  
  1097  	builder.AddOp(txscript.OP_ENDIF)
  1098  
  1099  	// Finally, we'll validate the signature against the public key that's
  1100  	// left on the top of the stack.
  1101  	builder.AddOp(txscript.OP_CHECKSIG)
  1102  
  1103  	return builder.Script()
  1104  }
  1105  
  1106  // LeaseCommitScriptToSelf constructs the public key script for the output on the
  1107  // commitment transaction paying to the "owner" of said commitment transaction.
  1108  // If the other party learns of the preimage to the revocation hash, then they
  1109  // can claim all the settled funds in the channel, plus the unsettled funds.
  1110  //
  1111  // Possible Input Scripts:
  1112  //
  1113  //	REVOKE:     <sig> 1
  1114  //	SENDRSWEEP: <sig> <emptyvector>
  1115  //
  1116  // Output Script:
  1117  //
  1118  //	OP_IF
  1119  //	    <revokeKey>
  1120  //	OP_ELSE
  1121  //	    <absoluteLeaseExpiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
  1122  //	    <numRelativeBlocks> OP_CHECKSEQUENCEVERIFY OP_DROP
  1123  //	    <timeKey>
  1124  //	OP_ENDIF
  1125  //	OP_CHECKSIG
  1126  func LeaseCommitScriptToSelf(selfKey, revokeKey *secp256k1.PublicKey,
  1127  	csvTimeout, leaseExpiry uint32) ([]byte, error) {
  1128  
  1129  	// This script is spendable under two conditions: either the
  1130  	// 'csvTimeout' has passed and we can redeem our funds, or they can
  1131  	// produce a valid signature with the revocation public key. The
  1132  	// revocation public key will *only* be known to the other party if we
  1133  	// have divulged the revocation hash, allowing them to homomorphically
  1134  	// derive the proper private key which corresponds to the revoke public
  1135  	// key.
  1136  	builder := txscript.NewScriptBuilder()
  1137  
  1138  	builder.AddOp(txscript.OP_IF)
  1139  
  1140  	// If a valid signature using the revocation key is presented, then
  1141  	// allow an immediate spend provided the proper signature.
  1142  	builder.AddData(revokeKey.SerializeCompressed())
  1143  
  1144  	builder.AddOp(txscript.OP_ELSE)
  1145  
  1146  	// Otherwise, we can re-claim our funds after once the CLTV lease
  1147  	// maturity has been met, along with the CSV delay of 'csvTimeout'
  1148  	// timeout blocks, and a valid signature.
  1149  	builder.AddInt64(int64(leaseExpiry))
  1150  	builder.AddOp(txscript.OP_CHECKLOCKTIMEVERIFY)
  1151  	builder.AddOp(txscript.OP_DROP)
  1152  
  1153  	builder.AddInt64(int64(csvTimeout))
  1154  	builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
  1155  	builder.AddOp(txscript.OP_DROP)
  1156  
  1157  	builder.AddData(selfKey.SerializeCompressed())
  1158  
  1159  	builder.AddOp(txscript.OP_ENDIF)
  1160  
  1161  	// Finally, we'll validate the signature against the public key that's
  1162  	// left on the top of the stack.
  1163  	builder.AddOp(txscript.OP_CHECKSIG)
  1164  
  1165  	return builder.Script()
  1166  }
  1167  
  1168  // CommitSpendTimeout constructs a valid witness allowing the owner of a
  1169  // particular commitment transaction to spend the output returning settled
  1170  // funds back to themselves after a relative block timeout.  In order to
  1171  // properly spend the transaction, the target input's sequence number should be
  1172  // set accordingly based off of the target relative block timeout within the
  1173  // redeem script.  Additionally, OP_CSV requires that the version of the
  1174  // transaction spending a pkscript with OP_CSV within it *must* be >= 2.
  1175  func CommitSpendTimeout(signer Signer, signDesc *SignDescriptor,
  1176  	sweepTx *wire.MsgTx) (TxWitness, error) {
  1177  
  1178  	// Ensure the transaction version supports the validation of sequence
  1179  	// locks and CSV semantics.
  1180  	if sweepTx.Version < 2 {
  1181  		return nil, fmt.Errorf("version of passed transaction MUST "+
  1182  			"be >= 2, not %v", sweepTx.Version)
  1183  	}
  1184  
  1185  	// With the sequence number in place, we're now able to properly sign
  1186  	// off on the sweep transaction.
  1187  	sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
  1188  	if err != nil {
  1189  		return nil, err
  1190  	}
  1191  
  1192  	// Place an empty byte as the first item in the evaluated witness stack
  1193  	// to force script execution to the timeout spend clause. We need to
  1194  	// place an empty byte in order to ensure our script is still valid
  1195  	// from the PoV of nodes that are enforcing minimal OP_IF/OP_NOTIF.
  1196  	witnessStack := TxWitness(make([][]byte, 3))
  1197  	witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
  1198  	witnessStack[1] = nil
  1199  	witnessStack[2] = signDesc.WitnessScript
  1200  
  1201  	return witnessStack, nil
  1202  }
  1203  
  1204  // CommitSpendRevoke constructs a valid witness allowing a node to sweep the
  1205  // settled output of a malicious counterparty who broadcasts a revoked
  1206  // commitment transaction.
  1207  //
  1208  // NOTE: The passed SignDescriptor should include the raw (untweaked)
  1209  // revocation base public key of the receiver and also the proper double tweak
  1210  // value based on the commitment secret of the revoked commitment.
  1211  func CommitSpendRevoke(signer Signer, signDesc *SignDescriptor,
  1212  	sweepTx *wire.MsgTx) (TxWitness, error) {
  1213  
  1214  	sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
  1215  	if err != nil {
  1216  		return nil, err
  1217  	}
  1218  
  1219  	// Place a 1 as the first item in the evaluated witness stack to
  1220  	// force script execution to the revocation clause.
  1221  	witnessStack := TxWitness(make([][]byte, 3))
  1222  	witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
  1223  	witnessStack[1] = []byte{1}
  1224  	witnessStack[2] = signDesc.WitnessScript
  1225  
  1226  	return witnessStack, nil
  1227  }
  1228  
  1229  // CommitSpendNoDelay constructs a valid witness allowing a node to spend their
  1230  // settled no-delay output on the counterparty's commitment transaction. If the
  1231  // tweakless field is true, then we'll omit the set where we tweak the pubkey
  1232  // with a random set of bytes, and use it directly in the witness stack.
  1233  //
  1234  // NOTE: The passed SignDescriptor should include the raw (untweaked) public
  1235  // key of the receiver and also the proper single tweak value based on the
  1236  // current commitment point.
  1237  func CommitSpendNoDelay(signer Signer, signDesc *SignDescriptor,
  1238  	sweepTx *wire.MsgTx, tweakless bool) (TxWitness, error) {
  1239  
  1240  	if signDesc.KeyDesc.PubKey == nil {
  1241  		return nil, fmt.Errorf("cannot generate witness with nil " +
  1242  			"KeyDesc pubkey")
  1243  	}
  1244  
  1245  	// This is just a regular p2wkh spend which looks something like:
  1246  	//  * witness: <sig> <pubkey>
  1247  	sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
  1248  	if err != nil {
  1249  		return nil, err
  1250  	}
  1251  
  1252  	// Finally, we'll manually craft the witness. The witness here is the
  1253  	// exact same as a regular p2wkh witness, depending on the value of the
  1254  	// tweakless bool.
  1255  	witness := make([][]byte, 2)
  1256  	witness[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
  1257  
  1258  	switch tweakless {
  1259  	// If we're tweaking the key, then we use the tweaked public key as the
  1260  	// last item in the witness stack which was originally used to created
  1261  	// the pkScript we're spending.
  1262  	case false:
  1263  		witness[1] = TweakPubKeyWithTweak(
  1264  			signDesc.KeyDesc.PubKey, signDesc.SingleTweak,
  1265  		).SerializeCompressed()
  1266  
  1267  	// Otherwise, we can just use the raw pubkey, since there's no random
  1268  	// value to be combined.
  1269  	case true:
  1270  		witness[1] = signDesc.KeyDesc.PubKey.SerializeCompressed()
  1271  	}
  1272  
  1273  	return witness, nil
  1274  }
  1275  
  1276  // CommitScriptUnencumbered constructs the public key script on the commitment
  1277  // transaction paying to the "other" party. The constructed output is a normal
  1278  // p2wkh output spendable immediately, requiring no contestation period.
  1279  func CommitScriptUnencumbered(key *secp256k1.PublicKey) ([]byte, error) {
  1280  	// This script goes to the "other" party, and is spendable immediately.
  1281  	pkh := dcrutil.Hash160(key.SerializeCompressed())
  1282  	builder := txscript.NewScriptBuilder()
  1283  	builder.
  1284  		AddOp(txscript.OP_DUP).
  1285  		AddOp(txscript.OP_HASH160).
  1286  		AddData(pkh).
  1287  		AddOp(txscript.OP_EQUALVERIFY).
  1288  		AddOp(txscript.OP_CHECKSIG)
  1289  
  1290  	return builder.Script()
  1291  }
  1292  
  1293  // CommitScriptToRemoteConfirmed constructs the script for the output on the
  1294  // commitment transaction paying to the remote party of said commitment
  1295  // transaction. The money can only be spend after one confirmation.
  1296  //
  1297  // Possible Input Scripts:
  1298  //
  1299  //	SWEEP: <sig>
  1300  //
  1301  // Output Script:
  1302  //
  1303  //	<key> OP_CHECKSIGVERIFY
  1304  //	1 OP_CHECKSEQUENCEVERIFY
  1305  func CommitScriptToRemoteConfirmed(key *secp256k1.PublicKey) ([]byte, error) {
  1306  	builder := txscript.NewScriptBuilder()
  1307  
  1308  	// Only the given key can spend the output.
  1309  	builder.AddData(key.SerializeCompressed())
  1310  	builder.AddOp(txscript.OP_CHECKSIGVERIFY)
  1311  
  1312  	// Check that the it has one confirmation.
  1313  	builder.AddOp(txscript.OP_1)
  1314  	builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
  1315  
  1316  	return builder.Script()
  1317  }
  1318  
  1319  // LeaseCommitScriptToRemoteConfirmed constructs the script for the output on
  1320  // the commitment transaction paying to the remote party of said commitment
  1321  // transaction. The money can only be spend after one confirmation.
  1322  //
  1323  // Possible Input Scripts:
  1324  //
  1325  //	SWEEP: <sig>
  1326  //
  1327  // Output Script:
  1328  //
  1329  //		<key> OP_CHECKSIGVERIFY
  1330  //	     <lease maturity in blocks> OP_CHECKLOCKTIMEVERIFY OP_DROP
  1331  //		1 OP_CHECKSEQUENCEVERIFY
  1332  func LeaseCommitScriptToRemoteConfirmed(key *secp256k1.PublicKey,
  1333  	leaseExpiry uint32) ([]byte, error) {
  1334  
  1335  	builder := txscript.NewScriptBuilder()
  1336  
  1337  	// Only the given key can spend the output.
  1338  	builder.AddData(key.SerializeCompressed())
  1339  	builder.AddOp(txscript.OP_CHECKSIGVERIFY)
  1340  
  1341  	// The channel initiator always has the additional channel lease
  1342  	// expiration constraint for outputs that pay to them which must be
  1343  	// satisfied.
  1344  	builder.AddInt64(int64(leaseExpiry))
  1345  	builder.AddOp(txscript.OP_CHECKLOCKTIMEVERIFY)
  1346  	builder.AddOp(txscript.OP_DROP)
  1347  
  1348  	// Check that it has one confirmation.
  1349  	builder.AddOp(txscript.OP_1)
  1350  	builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
  1351  
  1352  	return builder.Script()
  1353  }
  1354  
  1355  // CommitSpendToRemoteConfirmed constructs a valid witness allowing a node to
  1356  // spend their settled output on the counterparty's commitment transaction when
  1357  // it has one confirmetion. This is used for the anchor channel type. The
  1358  // spending key will always be non-tweaked for this output type.
  1359  func CommitSpendToRemoteConfirmed(signer Signer, signDesc *SignDescriptor,
  1360  	sweepTx *wire.MsgTx) (TxWitness, error) {
  1361  
  1362  	if signDesc.KeyDesc.PubKey == nil {
  1363  		return nil, fmt.Errorf("cannot generate witness with nil " +
  1364  			"KeyDesc pubkey")
  1365  	}
  1366  
  1367  	// Similar to non delayed output, only a signature is needed.
  1368  	sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
  1369  	if err != nil {
  1370  		return nil, err
  1371  	}
  1372  
  1373  	// Finally, we'll manually craft the witness. The witness here is the
  1374  	// signature and the redeem script.
  1375  	witnessStack := make([][]byte, 2)
  1376  	witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
  1377  	witnessStack[1] = signDesc.WitnessScript
  1378  
  1379  	return witnessStack, nil
  1380  }
  1381  
  1382  // CommitScriptAnchor constructs the script for the anchor output spendable by
  1383  // the given key immediately, or by anyone after 16 confirmations.
  1384  //
  1385  // Possible Input Scripts:
  1386  //
  1387  //	By owner:				<sig>
  1388  //	By anyone (after 16 conf):	<emptyvector>
  1389  //
  1390  // Output Script:
  1391  //
  1392  //	<funding_pubkey> OP_CHECKSIG OP_IFDUP
  1393  //	OP_NOTIF
  1394  //	  OP_16 OP_CSV
  1395  //	OP_ENDIF
  1396  func CommitScriptAnchor(key *secp256k1.PublicKey) ([]byte, error) {
  1397  	builder := txscript.NewScriptBuilder()
  1398  
  1399  	// Spend immediately with key.
  1400  	builder.AddData(key.SerializeCompressed())
  1401  	builder.AddOp(txscript.OP_CHECKSIG)
  1402  
  1403  	// Duplicate the value if true, since it will be consumed by the NOTIF.
  1404  	builder.AddOp(txscript.OP_IFDUP)
  1405  
  1406  	// Otherwise spendable by anyone after 16 confirmations.
  1407  	builder.AddOp(txscript.OP_NOTIF)
  1408  	builder.AddOp(txscript.OP_16)
  1409  	builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
  1410  	builder.AddOp(txscript.OP_ENDIF)
  1411  
  1412  	return builder.Script()
  1413  }
  1414  
  1415  // CommitSpendAnchor constructs a valid witness allowing a node to spend their
  1416  // anchor output on the commitment transaction using their funding key. This is
  1417  // used for the anchor channel type.
  1418  func CommitSpendAnchor(signer Signer, signDesc *SignDescriptor,
  1419  	sweepTx *wire.MsgTx) (TxWitness, error) {
  1420  
  1421  	if signDesc.KeyDesc.PubKey == nil {
  1422  		return nil, fmt.Errorf("cannot generate witness with nil " +
  1423  			"KeyDesc pubkey")
  1424  	}
  1425  
  1426  	// Create a signature.
  1427  	sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
  1428  	if err != nil {
  1429  		return nil, err
  1430  	}
  1431  
  1432  	// The witness here is just a signature and the redeem script.
  1433  	witnessStack := make([][]byte, 2)
  1434  	witnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))
  1435  	witnessStack[1] = signDesc.WitnessScript
  1436  
  1437  	return witnessStack, nil
  1438  }
  1439  
  1440  // CommitSpendAnchorAnyone constructs a witness allowing anyone to spend the
  1441  // anchor output after it has gotten 16 confirmations. Since no signing is
  1442  // required, only knowledge of the redeem script is necessary to spend it.
  1443  func CommitSpendAnchorAnyone(script []byte) (TxWitness, error) {
  1444  	// The witness here is just the redeem script.
  1445  	witnessStack := make([][]byte, 2)
  1446  	witnessStack[0] = nil
  1447  	witnessStack[1] = script
  1448  
  1449  	return witnessStack, nil
  1450  }
  1451  
  1452  // SingleTweakBytes computes set of bytes we call the single tweak. The purpose
  1453  // of the single tweak is to randomize all regular delay and payment base
  1454  // points. To do this, we generate a hash that binds the commitment point to
  1455  // the pay/delay base point. The end result is that the basePoint is tweaked as
  1456  // follows:
  1457  //
  1458  //   - key = basePoint + sha256(commitPoint || basePoint)*G
  1459  func SingleTweakBytes(commitPoint, basePoint *secp256k1.PublicKey) []byte {
  1460  	h := sha256.New()
  1461  	h.Write(commitPoint.SerializeCompressed())
  1462  	h.Write(basePoint.SerializeCompressed())
  1463  	return h.Sum(nil)
  1464  }
  1465  
  1466  // TweakPubKey tweaks a public base point given a per commitment point. The per
  1467  // commitment point is a unique point on our target curve for each commitment
  1468  // transaction. When tweaking a local base point for use in a remote commitment
  1469  // transaction, the remote party's current per commitment point is to be used.
  1470  // The opposite applies for when tweaking remote keys. Precisely, the following
  1471  // operation is used to "tweak" public keys:
  1472  //
  1473  //	tweakPub := basePoint + sha256(commitPoint || basePoint) * G
  1474  //	         := G*k + sha256(commitPoint || basePoint)*G
  1475  //	         := G*(k + sha256(commitPoint || basePoint))
  1476  //
  1477  // Therefore, if a party possess the value k, the private key of the base
  1478  // point, then they are able to derive the proper private key for the
  1479  // revokeKey by computing:
  1480  //
  1481  //	revokePriv := k + sha256(commitPoint || basePoint) mod N
  1482  //
  1483  // Where N is the order of the sub-group.
  1484  //
  1485  // The rationale for tweaking all public keys used within the commitment
  1486  // contracts is to ensure that all keys are properly delinearized to avoid any
  1487  // funny business when jointly collaborating to compute public and private
  1488  // keys. Additionally, the use of the per commitment point ensures that each
  1489  // commitment state houses a unique set of keys which is useful when creating
  1490  // blinded channel outsourcing protocols.
  1491  //
  1492  // TODO(roasbeef): should be using double-scalar mult here
  1493  func TweakPubKey(basePoint, commitPoint *secp256k1.PublicKey) *secp256k1.PublicKey {
  1494  	tweakBytes := SingleTweakBytes(commitPoint, basePoint)
  1495  	return TweakPubKeyWithTweak(basePoint, tweakBytes)
  1496  }
  1497  
  1498  // TweakPubKeyWithTweak is the exact same as the TweakPubKey function, however
  1499  // it accepts the raw tweak bytes directly rather than the commitment point.
  1500  func TweakPubKeyWithTweak(pubKey *secp256k1.PublicKey, tweakBytes []byte) *secp256k1.PublicKey {
  1501  	// TODO(decred): fully switch to secp256k.JacobianPoint repr.
  1502  	curve := secp256k1.S256()
  1503  	tweakX, tweakY := curve.ScalarBaseMult(tweakBytes)
  1504  
  1505  	// TODO(roasbeef): check that both passed on curve?
  1506  	x, y := curve.Add(pubKey.X(), pubKey.Y(), tweakX, tweakY)
  1507  	var fx, fy secp256k1.FieldVal
  1508  	fx.SetByteSlice(x.Bytes())
  1509  	fy.SetByteSlice(y.Bytes())
  1510  	return secp256k1.NewPublicKey(&fx, &fy)
  1511  }
  1512  
  1513  // TweakPrivKey tweaks the private key of a public base point given a per
  1514  // commitment point. The per commitment secret is the revealed revocation
  1515  // secret for the commitment state in question. This private key will only need
  1516  // to be generated in the case that a channel counter party broadcasts a
  1517  // revoked state. Precisely, the following operation is used to derive a
  1518  // tweaked private key:
  1519  //
  1520  //   - tweakPriv := basePriv + sha256(commitment || basePub) mod N
  1521  //
  1522  // Where N is the order of the sub-group.
  1523  func TweakPrivKey(basePriv *secp256k1.PrivateKey, commitTweak []byte) *secp256k1.PrivateKey {
  1524  	// tweakInt := sha256(commitPoint || basePub)
  1525  	tweakInt := new(big.Int).SetBytes(commitTweak)
  1526  
  1527  	// TODO(decred): Fully switch to fieldVal repr.
  1528  	d := new(big.Int).SetBytes(basePriv.Serialize())
  1529  	tweakInt = tweakInt.Add(tweakInt, d)
  1530  	tweakInt = tweakInt.Mod(tweakInt, secp256k1.S256().N)
  1531  
  1532  	tweakPriv := secp256k1.PrivKeyFromBytes(tweakInt.Bytes())
  1533  	return tweakPriv
  1534  }
  1535  
  1536  // DeriveRevocationPubkey derives the revocation public key given the
  1537  // counterparty's commitment key, and revocation preimage derived via a
  1538  // pseudo-random-function. In the event that we (for some reason) broadcast a
  1539  // revoked commitment transaction, then if the other party knows the revocation
  1540  // preimage, then they'll be able to derive the corresponding private key to
  1541  // this private key by exploiting the homomorphism in the elliptic curve group:
  1542  //   - https://en.wikipedia.org/wiki/Group_homomorphism#Homomorphisms_of_abelian_groups
  1543  //
  1544  // The derivation is performed as follows:
  1545  //
  1546  //	revokeKey := revokeBase * sha256(revocationBase || commitPoint) +
  1547  //	             commitPoint * sha256(commitPoint || revocationBase)
  1548  //
  1549  //	          := G*(revokeBasePriv * sha256(revocationBase || commitPoint)) +
  1550  //	             G*(commitSecret * sha256(commitPoint || revocationBase))
  1551  //
  1552  //	          := G*(revokeBasePriv * sha256(revocationBase || commitPoint) +
  1553  //	                commitSecret * sha256(commitPoint || revocationBase))
  1554  //
  1555  // Therefore, once we divulge the revocation secret, the remote peer is able to
  1556  // compute the proper private key for the revokeKey by computing:
  1557  //
  1558  //	revokePriv := (revokeBasePriv * sha256(revocationBase || commitPoint)) +
  1559  //	              (commitSecret * sha256(commitPoint || revocationBase)) mod N
  1560  //
  1561  // Where N is the order of the sub-group.
  1562  func DeriveRevocationPubkey(revokeBase, commitPoint *secp256k1.PublicKey) *secp256k1.PublicKey {
  1563  	// TODO(decred): fully switch to secp256k1.JacobianPoint repr.
  1564  
  1565  	// R = revokeBase * sha256(revocationBase || commitPoint)
  1566  	revokeTweakBytes := SingleTweakBytes(revokeBase, commitPoint)
  1567  	rX, rY := secp256k1.S256().ScalarMult(revokeBase.X(), revokeBase.Y(),
  1568  		revokeTweakBytes)
  1569  
  1570  	// C = commitPoint * sha256(commitPoint || revocationBase)
  1571  	commitTweakBytes := SingleTweakBytes(commitPoint, revokeBase)
  1572  	cX, cY := secp256k1.S256().ScalarMult(commitPoint.X(), commitPoint.Y(),
  1573  		commitTweakBytes)
  1574  
  1575  	// Now that we have the revocation point, we add this to their commitment
  1576  	// public key in order to obtain the revocation public key.
  1577  	//
  1578  	// P = R + C
  1579  	revX, revY := secp256k1.S256().Add(rX, rY, cX, cY)
  1580  	var fx, fy secp256k1.FieldVal
  1581  	fx.SetByteSlice(revX.Bytes())
  1582  	fy.SetByteSlice(revY.Bytes())
  1583  	return secp256k1.NewPublicKey(&fx, &fy)
  1584  }
  1585  
  1586  // DeriveRevocationPrivKey derives the revocation private key given a node's
  1587  // commitment private key, and the preimage to a previously seen revocation
  1588  // hash. Using this derived private key, a node is able to claim the output
  1589  // within the commitment transaction of a node in the case that they broadcast
  1590  // a previously revoked commitment transaction.
  1591  //
  1592  // The private key is derived as follows:
  1593  //
  1594  //	revokePriv := (revokeBasePriv * sha256(revocationBase || commitPoint)) +
  1595  //	              (commitSecret * sha256(commitPoint || revocationBase)) mod N
  1596  //
  1597  // Where N is the order of the sub-group.
  1598  func DeriveRevocationPrivKey(revokeBasePriv *secp256k1.PrivateKey,
  1599  	commitSecret *secp256k1.PrivateKey) *secp256k1.PrivateKey {
  1600  
  1601  	// TODO(decred): Switch to secpp256k1.JacobianPoint repr.
  1602  
  1603  	// r = sha256(revokeBasePub || commitPoint)
  1604  	revokeTweakBytes := SingleTweakBytes(
  1605  		revokeBasePriv.PubKey(),
  1606  		commitSecret.PubKey())
  1607  	revokeTweakInt := new(big.Int).SetBytes(revokeTweakBytes)
  1608  
  1609  	// c = sha256(commitPoint || revokeBasePub)
  1610  	commitTweakBytes := SingleTweakBytes(
  1611  		commitSecret.PubKey(),
  1612  		revokeBasePriv.PubKey())
  1613  	commitTweakInt := new(big.Int).SetBytes(commitTweakBytes)
  1614  
  1615  	// Finally to derive the revocation secret key we'll perform the
  1616  	// following operation:
  1617  	//
  1618  	//  k = (revocationPriv * r) + (commitSecret * c) mod N
  1619  	//
  1620  	// This works since:
  1621  	//  P = (G*a)*b + (G*c)*d
  1622  	//  P = G*(a*b) + G*(c*d)
  1623  	//  P = G*(a*b + c*d)
  1624  	revokeD := new(big.Int).SetBytes(revokeBasePriv.Serialize())
  1625  	commitD := new(big.Int).SetBytes(commitSecret.Serialize())
  1626  	revokeHalfPriv := revokeTweakInt.Mul(revokeTweakInt, revokeD)
  1627  	commitHalfPriv := commitTweakInt.Mul(commitTweakInt, commitD)
  1628  
  1629  	revocationPriv := revokeHalfPriv.Add(revokeHalfPriv, commitHalfPriv)
  1630  	revocationPriv = revocationPriv.Mod(revocationPriv, secp256k1.S256().N)
  1631  
  1632  	priv := secp256k1.PrivKeyFromBytes(revocationPriv.Bytes())
  1633  	return priv
  1634  }
  1635  
  1636  // ComputeCommitmentPoint generates a commitment point given a commitment
  1637  // secret. The commitment point for each state is used to randomize each key in
  1638  // the key-ring and also to used as a tweak to derive new public+private keys
  1639  // for the state.
  1640  func ComputeCommitmentPoint(commitSecret []byte) *secp256k1.PublicKey {
  1641  	priv := secp256k1.PrivKeyFromBytes(commitSecret)
  1642  	return priv.PubKey()
  1643  }