Merge pull request #3821 from halseth/pluggable-anchors-lnwallet

[anchor] pluggable anchor commitments
This commit is contained in:
Olaoluwa Osuntokun authored and GitHub committed 2020-03-09 19:49:05 -07:00
commit 3dda93e30d
37 files changed
+1848 -604

No files matched your search

+7 -6
View File
@@ -156,15 +156,16 @@ type HtlcSucceedInput struct {
// MakeHtlcSucceedInput assembles a new redeem input that can be used to
// construct a sweep transaction.
func MakeHtlcSucceedInput(outpoint *wire.OutPoint,
signDescriptor *SignDescriptor,
preimage []byte, heightHint uint32) HtlcSucceedInput {
signDescriptor *SignDescriptor, preimage []byte, heightHint,
blocksToMaturity uint32) HtlcSucceedInput {
return HtlcSucceedInput{
inputKit: inputKit{
outpoint: *outpoint,
witnessType: HtlcAcceptedRemoteSuccess,
signDesc: *signDescriptor,
heightHint: heightHint,
outpoint: *outpoint,
witnessType: HtlcAcceptedRemoteSuccess,
signDesc: *signDescriptor,
heightHint: heightHint,
blockToMaturity: blocksToMaturity,
},
preimage: preimage,
}
+168 -21
View File
@@ -150,6 +150,9 @@ func Ripemd160H(d []byte) []byte {
// * 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>
@@ -168,9 +171,11 @@ func Ripemd160H(d []byte) []byte {
// OP_HASH160 <ripemd160(payment hash)> OP_EQUALVERIFY
// OP_CHECKSIG
// OP_ENDIF
// [1 OP_CHECKSEQUENCEVERIFY OP_DROP] <- if allowing confirmed spend only.
// OP_ENDIF
func SenderHTLCScript(senderHtlcKey, receiverHtlcKey,
revocationKey *btcec.PublicKey, paymentHash []byte) ([]byte, error) {
revocationKey *btcec.PublicKey, paymentHash []byte,
confirmedSpend bool) ([]byte, error) {
builder := txscript.NewScriptBuilder()
@@ -243,6 +248,14 @@ func SenderHTLCScript(senderHtlcKey, receiverHtlcKey,
// Close out the OP_IF statement above.
builder.AddOp(txscript.OP_ENDIF)
// Add 1 block CSV delay if a confirmation is required for the
// non-revocation clauses.
if confirmedSpend {
builder.AddOp(txscript.OP_1)
builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
builder.AddOp(txscript.OP_DROP)
}
// Close out the OP_IF statement at the top of the script.
builder.AddOp(txscript.OP_ENDIF)
@@ -330,8 +343,10 @@ func SenderHtlcSpendRedeem(signer Signer, signDesc *SignDescriptor,
// 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 SenderHtlcSpendTimeout(receiverSig []byte, signer Signer,
signDesc *SignDescriptor, htlcTimeoutTx *wire.MsgTx) (wire.TxWitness, error) {
func SenderHtlcSpendTimeout(receiverSig []byte,
receiverSigHash txscript.SigHashType, signer Signer,
signDesc *SignDescriptor, htlcTimeoutTx *wire.MsgTx) (
wire.TxWitness, error) {
sweepSig, err := signer.SignOutputRaw(htlcTimeoutTx, signDesc)
if err != nil {
@@ -344,7 +359,7 @@ func SenderHtlcSpendTimeout(receiverSig []byte, signer Signer,
// original OP_CHECKMULTISIG.
witnessStack := wire.TxWitness(make([][]byte, 5))
witnessStack[0] = nil
witnessStack[1] = append(receiverSig, byte(txscript.SigHashAll))
witnessStack[1] = append(receiverSig, byte(receiverSigHash))
witnessStack[2] = append(sweepSig, byte(signDesc.HashType))
witnessStack[3] = nil
witnessStack[4] = signDesc.WitnessScript
@@ -362,6 +377,9 @@ func SenderHtlcSpendTimeout(receiverSig []byte, signer Signer,
// * 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>
@@ -381,10 +399,11 @@ func SenderHtlcSpendTimeout(receiverSig []byte, signer Signer,
// 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 ReceiverHTLCScript(cltvExpiry uint32, senderHtlcKey,
receiverHtlcKey, revocationKey *btcec.PublicKey,
paymentHash []byte) ([]byte, error) {
paymentHash []byte, confirmedSpend bool) ([]byte, error) {
builder := txscript.NewScriptBuilder()
@@ -467,6 +486,14 @@ func ReceiverHTLCScript(cltvExpiry uint32, senderHtlcKey,
// Close out the inner if statement.
builder.AddOp(txscript.OP_ENDIF)
// Add 1 block CSV delay for non-revocation clauses if confirmation is
// required.
if confirmedSpend {
builder.AddOp(txscript.OP_1)
builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
builder.AddOp(txscript.OP_DROP)
}
// Close out the outer if statement.
builder.AddOp(txscript.OP_ENDIF)
@@ -481,9 +508,10 @@ func ReceiverHTLCScript(cltvExpiry uint32, senderHtlcKey,
// 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 ReceiverHtlcSpendRedeem(senderSig, paymentPreimage []byte,
signer Signer, signDesc *SignDescriptor,
htlcSuccessTx *wire.MsgTx) (wire.TxWitness, error) {
func ReceiverHtlcSpendRedeem(senderSig []byte,
senderSigHash txscript.SigHashType, paymentPreimage []byte,
signer Signer, signDesc *SignDescriptor, htlcSuccessTx *wire.MsgTx) (
wire.TxWitness, error) {
// First, we'll generate a signature for the HTLC success transaction.
// The signDesc should be signing with the public key used as the
@@ -499,7 +527,7 @@ func ReceiverHtlcSpendRedeem(senderSig, paymentPreimage []byte,
// order to consume the extra pop within OP_CHECKMULTISIG.
witnessStack := wire.TxWitness(make([][]byte, 5))
witnessStack[0] = nil
witnessStack[1] = append(senderSig, byte(txscript.SigHashAll))
witnessStack[1] = append(senderSig, byte(senderSigHash))
witnessStack[2] = append(sweepSig, byte(signDesc.HashType))
witnessStack[3] = paymentPreimage
witnessStack[4] = signDesc.WitnessScript
@@ -828,18 +856,6 @@ func CommitScriptToSelf(csvTimeout uint32, selfKey, revokeKey *btcec.PublicKey)
return builder.Script()
}
// 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 CommitScriptUnencumbered(key *btcec.PublicKey) ([]byte, error) {
// This script goes to the "other" party, and is spendable immediately.
builder := txscript.NewScriptBuilder()
builder.AddOp(txscript.OP_0)
builder.AddData(btcutil.Hash160(key.SerializeCompressed()))
return builder.Script()
}
// 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
@@ -948,6 +964,137 @@ func CommitSpendNoDelay(signer Signer, signDesc *SignDescriptor,
return witness, nil
}
// 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 CommitScriptUnencumbered(key *btcec.PublicKey) ([]byte, error) {
// This script goes to the "other" party, and is spendable immediately.
builder := txscript.NewScriptBuilder()
builder.AddOp(txscript.OP_0)
builder.AddData(btcutil.Hash160(key.SerializeCompressed()))
return builder.Script()
}
// 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 CommitScriptToRemoteConfirmed(key *btcec.PublicKey) ([]byte, error) {
builder := txscript.NewScriptBuilder()
// Only the given key can spend the output.
builder.AddData(key.SerializeCompressed())
builder.AddOp(txscript.OP_CHECKSIGVERIFY)
// Check that the it has one confirmation.
builder.AddOp(txscript.OP_1)
builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
return builder.Script()
}
// 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 CommitSpendToRemoteConfirmed(signer Signer, signDesc *SignDescriptor,
sweepTx *wire.MsgTx) (wire.TxWitness, error) {
if signDesc.KeyDesc.PubKey == nil {
return nil, fmt.Errorf("cannot generate witness with nil " +
"KeyDesc pubkey")
}
// Similar to non delayed output, only a signature is needed.
sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
if err != nil {
return nil, err
}
// Finally, we'll manually craft the witness. The witness here is the
// signature and the redeem script.
witnessStack := make([][]byte, 2)
witnessStack[0] = append(sweepSig, byte(signDesc.HashType))
witnessStack[1] = signDesc.WitnessScript
return witnessStack, nil
}
// 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 CommitScriptAnchor(key *btcec.PublicKey) ([]byte, error) {
builder := txscript.NewScriptBuilder()
// Spend immediately with key.
builder.AddData(key.SerializeCompressed())
builder.AddOp(txscript.OP_CHECKSIG)
// Duplicate the value if true, since it will be consumed by the NOTIF.
builder.AddOp(txscript.OP_IFDUP)
// Otherwise spendable by anyone after 16 confirmations.
builder.AddOp(txscript.OP_NOTIF)
builder.AddOp(txscript.OP_16)
builder.AddOp(txscript.OP_CHECKSEQUENCEVERIFY)
builder.AddOp(txscript.OP_ENDIF)
return builder.Script()
}
// 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 CommitSpendAnchor(signer Signer, signDesc *SignDescriptor,
sweepTx *wire.MsgTx) (wire.TxWitness, error) {
if signDesc.KeyDesc.PubKey == nil {
return nil, fmt.Errorf("cannot generate witness with nil " +
"KeyDesc pubkey")
}
// Create a signature.
sweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)
if err != nil {
return nil, err
}
// The witness here is just a signature and the redeem script.
witnessStack := make([][]byte, 2)
witnessStack[0] = append(sweepSig, byte(signDesc.HashType))
witnessStack[1] = signDesc.WitnessScript
return witnessStack, nil
}
// 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 CommitSpendAnchorAnyone(script []byte) (wire.TxWitness, error) {
// The witness here is just the redeem script.
witnessStack := make([][]byte, 2)
witnessStack[0] = nil
witnessStack[1] = script
return witnessStack, nil
}
// 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
+740 -203
View File
@@ -15,6 +15,73 @@ import (
"github.com/lightningnetwork/lnd/keychain"
)
// assertEngineExecution executes the VM returned by the newEngine closure,
// asserting the result matches the validity expectation. In the case where it
// doesn't match the expectation, it executes the script step-by-step and
// prints debug information to stdout.
func assertEngineExecution(t *testing.T, testNum int, valid bool,
newEngine func() (*txscript.Engine, error)) {
t.Helper()
// Get a new VM to execute.
vm, err := newEngine()
if err != nil {
t.Fatalf("unable to create engine: %v", err)
}
// Execute the VM, only go on to the step-by-step execution if
// it doesn't validate as expected.
vmErr := vm.Execute()
if valid == (vmErr == nil) {
return
}
// Now that the execution didn't match what we expected, fetch a new VM
// to step through.
vm, err = newEngine()
if err != nil {
t.Fatalf("unable to create engine: %v", err)
}
// This buffer will trace execution of the Script, dumping out
// to stdout.
var debugBuf bytes.Buffer
done := false
for !done {
dis, err := vm.DisasmPC()
if err != nil {
t.Fatalf("stepping (%v)\n", err)
}
debugBuf.WriteString(fmt.Sprintf("stepping %v\n", dis))
done, err = vm.Step()
if err != nil && valid {
fmt.Println(debugBuf.String())
t.Fatalf("spend test case #%v failed, spend "+
"should be valid: %v", testNum, err)
} else if err == nil && !valid && done {
fmt.Println(debugBuf.String())
t.Fatalf("spend test case #%v succeed, spend "+
"should be invalid: %v", testNum, err)
}
debugBuf.WriteString(fmt.Sprintf("Stack: %v", vm.GetStack()))
debugBuf.WriteString(fmt.Sprintf("AltStack: %v", vm.GetAltStack()))
}
// If we get to this point the unexpected case was not reached
// during step execution, which happens for some checks, like
// the clean-stack rule.
validity := "invalid"
if valid {
validity = "valid"
}
fmt.Println(debugBuf.String())
t.Fatalf("%v spend test case #%v execution ended with: %v", validity, testNum, vmErr)
}
// TestRevocationKeyDerivation tests that given a public key, and a revocation
// hash, the homomorphic revocation public and private key derivation work
// properly.
@@ -145,43 +212,6 @@ func TestHTLCSenderSpendValidation(t *testing.T) {
// we'll be using Bob's base point for the revocation key.
revocationKey := DeriveRevocationPubkey(bobKeyPub, commitPoint)
// Generate the raw HTLC redemption scripts, and its p2wsh counterpart.
htlcWitnessScript, err := SenderHTLCScript(aliceLocalKey, bobLocalKey,
revocationKey, paymentHash[:])
if err != nil {
t.Fatalf("unable to create htlc sender script: %v", err)
}
htlcPkScript, err := WitnessScriptHash(htlcWitnessScript)
if err != nil {
t.Fatalf("unable to create p2wsh htlc script: %v", err)
}
// This will be Alice's commitment transaction. In this scenario Alice
// is sending an HTLC to a node she has a path to (could be Bob, could
// be multiple hops down, it doesn't really matter).
htlcOutput := &wire.TxOut{
Value: int64(paymentAmt),
PkScript: htlcPkScript,
}
senderCommitTx := wire.NewMsgTx(2)
senderCommitTx.AddTxIn(fakeFundingTxIn)
senderCommitTx.AddTxOut(htlcOutput)
prevOut := &wire.OutPoint{
Hash: senderCommitTx.TxHash(),
Index: 0,
}
sweepTx := wire.NewMsgTx(2)
sweepTx.AddTxIn(wire.NewTxIn(prevOut, nil, nil))
sweepTx.AddTxOut(
&wire.TxOut{
PkScript: []byte("doesn't matter"),
Value: 1 * 10e8,
},
)
sweepTxSigHashes := txscript.NewTxSigHashes(sweepTx)
bobCommitTweak := SingleTweakBytes(commitPoint, bobKeyPub)
aliceCommitTweak := SingleTweakBytes(commitPoint, aliceKeyPub)
@@ -191,23 +221,92 @@ func TestHTLCSenderSpendValidation(t *testing.T) {
bobSigner := &MockSigner{Privkeys: []*btcec.PrivateKey{bobKeyPriv}}
aliceSigner := &MockSigner{Privkeys: []*btcec.PrivateKey{aliceKeyPriv}}
// We'll also generate a signature on the sweep transaction above
// that will act as Bob's signature to Alice for the second level HTLC
// transaction.
bobSignDesc := SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: bobKeyPub,
},
SingleTweak: bobCommitTweak,
WitnessScript: htlcWitnessScript,
Output: htlcOutput,
HashType: txscript.SigHashAll,
SigHashes: sweepTxSigHashes,
InputIndex: 0,
var (
htlcWitnessScript, htlcPkScript []byte
htlcOutput *wire.TxOut
sweepTxSigHashes *txscript.TxSigHashes
senderCommitTx, sweepTx *wire.MsgTx
bobRecvrSig []byte
bobSigHash txscript.SigHashType
)
// genCommitTx generates a commitment tx where the htlc output requires
// confirmation to be spent according to 'confirmed'.
genCommitTx := func(confirmed bool) {
// Generate the raw HTLC redemption scripts, and its p2wsh
// counterpart.
htlcWitnessScript, err = SenderHTLCScript(
aliceLocalKey, bobLocalKey, revocationKey,
paymentHash[:], confirmed,
)
if err != nil {
t.Fatalf("unable to create htlc sender script: %v", err)
}
htlcPkScript, err = WitnessScriptHash(htlcWitnessScript)
if err != nil {
t.Fatalf("unable to create p2wsh htlc script: %v", err)
}
// This will be Alice's commitment transaction. In this
// scenario Alice is sending an HTLC to a node she has a path
// to (could be Bob, could be multiple hops down, it doesn't
// really matter).
htlcOutput = &wire.TxOut{
Value: int64(paymentAmt),
PkScript: htlcPkScript,
}
senderCommitTx = wire.NewMsgTx(2)
senderCommitTx.AddTxIn(fakeFundingTxIn)
senderCommitTx.AddTxOut(htlcOutput)
}
bobRecvrSig, err := bobSigner.SignOutputRaw(sweepTx, &bobSignDesc)
if err != nil {
t.Fatalf("unable to generate alice signature: %v", err)
// genSweepTx generates a sweep of the senderCommitTx, and sets the
// sequence and sighash single|anyonecanspend if confirmed is true.
genSweepTx := func(confirmed bool) {
prevOut := &wire.OutPoint{
Hash: senderCommitTx.TxHash(),
Index: 0,
}
sweepTx = wire.NewMsgTx(2)
sweepTx.AddTxIn(wire.NewTxIn(prevOut, nil, nil))
if confirmed {
sweepTx.TxIn[0].Sequence = LockTimeToSequence(false, 1)
}
sweepTx.AddTxOut(
&wire.TxOut{
PkScript: []byte("doesn't matter"),
Value: 1 * 10e8,
},
)
sweepTxSigHashes = txscript.NewTxSigHashes(sweepTx)
bobSigHash = txscript.SigHashAll
if confirmed {
bobSigHash = txscript.SigHashSingle | txscript.SigHashAnyOneCanPay
}
// We'll also generate a signature on the sweep transaction above
// that will act as Bob's signature to Alice for the second level HTLC
// transaction.
bobSignDesc := SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: bobKeyPub,
},
SingleTweak: bobCommitTweak,
WitnessScript: htlcWitnessScript,
Output: htlcOutput,
HashType: bobSigHash,
SigHashes: sweepTxSigHashes,
InputIndex: 0,
}
bobRecvrSig, err = bobSigner.SignOutputRaw(sweepTx, &bobSignDesc)
if err != nil {
t.Fatalf("unable to generate alice signature: %v", err)
}
}
testCases := []struct {
@@ -218,6 +317,9 @@ func TestHTLCSenderSpendValidation(t *testing.T) {
// revoke w/ sig
// TODO(roasbeef): test invalid revoke
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
genCommitTx(false)
genSweepTx(false)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: bobKeyPub,
@@ -238,6 +340,9 @@ func TestHTLCSenderSpendValidation(t *testing.T) {
{
// HTLC with invalid preimage size
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
genCommitTx(false)
genSweepTx(false)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: bobKeyPub,
@@ -261,6 +366,9 @@ func TestHTLCSenderSpendValidation(t *testing.T) {
// HTLC with valid preimage size + sig
// TODO(roasbeef): invalid preimage
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
genCommitTx(false)
genSweepTx(false)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: bobKeyPub,
@@ -278,11 +386,72 @@ func TestHTLCSenderSpendValidation(t *testing.T) {
}),
true,
},
{
// HTLC with valid preimage size + sig, and with
// enforced locktime in HTLC script.
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
// Make a commit tx that needs confirmation for
// HTLC output to be spent.
genCommitTx(true)
// Generate a sweep with the locktime set.
genSweepTx(true)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: bobKeyPub,
},
SingleTweak: bobCommitTweak,
WitnessScript: htlcWitnessScript,
Output: htlcOutput,
HashType: txscript.SigHashAll,
SigHashes: sweepTxSigHashes,
InputIndex: 0,
}
return SenderHtlcSpendRedeem(bobSigner, signDesc,
sweepTx, paymentPreimage)
}),
true,
},
{
// HTLC with valid preimage size + sig, but trying to
// spend CSV output without sequence set.
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
// Generate commitment tx with 1 CSV locked
// HTLC.
genCommitTx(true)
// Generate sweep tx that doesn't have locktime
// enabled.
genSweepTx(false)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: bobKeyPub,
},
SingleTweak: bobCommitTweak,
WitnessScript: htlcWitnessScript,
Output: htlcOutput,
HashType: txscript.SigHashAll,
SigHashes: sweepTxSigHashes,
InputIndex: 0,
}
return SenderHtlcSpendRedeem(bobSigner, signDesc,
sweepTx, paymentPreimage)
}),
false,
},
{
// valid spend to the transition the state of the HTLC
// output with the second level HTLC timeout
// transaction.
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
genCommitTx(false)
genSweepTx(false)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: aliceKeyPub,
@@ -295,11 +464,76 @@ func TestHTLCSenderSpendValidation(t *testing.T) {
InputIndex: 0,
}
return SenderHtlcSpendTimeout(bobRecvrSig, aliceSigner,
signDesc, sweepTx)
return SenderHtlcSpendTimeout(
bobRecvrSig, bobSigHash, aliceSigner,
signDesc, sweepTx,
)
}),
true,
},
{
// valid spend to the transition the state of the HTLC
// output with the second level HTLC timeout
// transaction.
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
// Make a commit tx that needs confirmation for
// HTLC output to be spent.
genCommitTx(true)
// Generate a sweep with the locktime set.
genSweepTx(true)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: aliceKeyPub,
},
SingleTweak: aliceCommitTweak,
WitnessScript: htlcWitnessScript,
Output: htlcOutput,
HashType: txscript.SigHashAll,
SigHashes: sweepTxSigHashes,
InputIndex: 0,
}
return SenderHtlcSpendTimeout(
bobRecvrSig, bobSigHash, aliceSigner,
signDesc, sweepTx,
)
}),
true,
},
{
// valid spend to the transition the state of the HTLC
// output with the second level HTLC timeout
// transaction.
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
// Generate commitment tx with 1 CSV locked
// HTLC.
genCommitTx(true)
// Generate sweep tx that doesn't have locktime
// enabled.
genSweepTx(false)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: aliceKeyPub,
},
SingleTweak: aliceCommitTweak,
WitnessScript: htlcWitnessScript,
Output: htlcOutput,
HashType: txscript.SigHashAll,
SigHashes: sweepTxSigHashes,
InputIndex: 0,
}
return SenderHtlcSpendTimeout(
bobRecvrSig, bobSigHash, aliceSigner,
signDesc, sweepTx,
)
}),
false,
},
}
// TODO(roasbeef): set of cases to ensure able to sign w/ keypath and
@@ -308,39 +542,13 @@ func TestHTLCSenderSpendValidation(t *testing.T) {
for i, testCase := range testCases {
sweepTx.TxIn[0].Witness = testCase.witness()
vm, err := txscript.NewEngine(htlcPkScript,
sweepTx, 0, txscript.StandardVerifyFlags, nil,
nil, int64(paymentAmt))
if err != nil {
t.Fatalf("unable to create engine: %v", err)
newEngine := func() (*txscript.Engine, error) {
return txscript.NewEngine(htlcPkScript,
sweepTx, 0, txscript.StandardVerifyFlags, nil,
nil, int64(paymentAmt))
}
// This buffer will trace execution of the Script, only dumping
// out to stdout in the case that a test fails.
var debugBuf bytes.Buffer
done := false
for !done {
dis, err := vm.DisasmPC()
if err != nil {
t.Fatalf("stepping (%v)\n", err)
}
debugBuf.WriteString(fmt.Sprintf("stepping %v\n", dis))
done, err = vm.Step()
if err != nil && testCase.valid {
fmt.Println(debugBuf.String())
t.Fatalf("spend test case #%v failed, spend "+
"should be valid: %v", i, err)
} else if err == nil && !testCase.valid && done {
fmt.Println(debugBuf.String())
t.Fatalf("spend test case #%v succeed, spend "+
"should be invalid: %v", i, err)
}
debugBuf.WriteString(fmt.Sprintf("Stack: %v", vm.GetStack()))
debugBuf.WriteString(fmt.Sprintf("AltStack: %v", vm.GetAltStack()))
}
assertEngineExecution(t, i, testCase.valid, newEngine)
}
}
@@ -400,46 +608,6 @@ func TestHTLCReceiverSpendValidation(t *testing.T) {
// be using Alice's base point for the revocation key.
revocationKey := DeriveRevocationPubkey(aliceKeyPub, commitPoint)
// Generate the raw HTLC redemption scripts, and its p2wsh counterpart.
htlcWitnessScript, err := ReceiverHTLCScript(cltvTimeout, aliceLocalKey,
bobLocalKey, revocationKey, paymentHash[:])
if err != nil {
t.Fatalf("unable to create htlc sender script: %v", err)
}
htlcPkScript, err := WitnessScriptHash(htlcWitnessScript)
if err != nil {
t.Fatalf("unable to create p2wsh htlc script: %v", err)
}
// This will be Bob's commitment transaction. In this scenario Alice is
// sending an HTLC to a node she has a path to (could be Bob, could be
// multiple hops down, it doesn't really matter).
htlcOutput := &wire.TxOut{
Value: int64(paymentAmt),
PkScript: htlcWitnessScript,
}
receiverCommitTx := wire.NewMsgTx(2)
receiverCommitTx.AddTxIn(fakeFundingTxIn)
receiverCommitTx.AddTxOut(htlcOutput)
prevOut := &wire.OutPoint{
Hash: receiverCommitTx.TxHash(),
Index: 0,
}
sweepTx := wire.NewMsgTx(2)
sweepTx.AddTxIn(&wire.TxIn{
PreviousOutPoint: *prevOut,
})
sweepTx.AddTxOut(
&wire.TxOut{
PkScript: []byte("doesn't matter"),
Value: 1 * 10e8,
},
)
sweepTxSigHashes := txscript.NewTxSigHashes(sweepTx)
bobCommitTweak := SingleTweakBytes(commitPoint, bobKeyPub)
aliceCommitTweak := SingleTweakBytes(commitPoint, aliceKeyPub)
@@ -449,23 +617,88 @@ func TestHTLCReceiverSpendValidation(t *testing.T) {
bobSigner := &MockSigner{Privkeys: []*btcec.PrivateKey{bobKeyPriv}}
aliceSigner := &MockSigner{Privkeys: []*btcec.PrivateKey{aliceKeyPriv}}
// We'll also generate a signature on the sweep transaction above
// that will act as Alice's signature to Bob for the second level HTLC
// transaction.
aliceSignDesc := SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: aliceKeyPub,
},
SingleTweak: aliceCommitTweak,
WitnessScript: htlcWitnessScript,
Output: htlcOutput,
HashType: txscript.SigHashAll,
SigHashes: sweepTxSigHashes,
InputIndex: 0,
var (
htlcWitnessScript, htlcPkScript []byte
htlcOutput *wire.TxOut
receiverCommitTx, sweepTx *wire.MsgTx
sweepTxSigHashes *txscript.TxSigHashes
aliceSenderSig []byte
aliceSigHash txscript.SigHashType
)
genCommitTx := func(confirmed bool) {
// Generate the raw HTLC redemption scripts, and its p2wsh
// counterpart.
htlcWitnessScript, err = ReceiverHTLCScript(
cltvTimeout, aliceLocalKey, bobLocalKey, revocationKey,
paymentHash[:], confirmed,
)
if err != nil {
t.Fatalf("unable to create htlc sender script: %v", err)
}
htlcPkScript, err = WitnessScriptHash(htlcWitnessScript)
if err != nil {
t.Fatalf("unable to create p2wsh htlc script: %v", err)
}
// This will be Bob's commitment transaction. In this scenario Alice is
// sending an HTLC to a node she has a path to (could be Bob, could be
// multiple hops down, it doesn't really matter).
htlcOutput = &wire.TxOut{
Value: int64(paymentAmt),
PkScript: htlcWitnessScript,
}
receiverCommitTx = wire.NewMsgTx(2)
receiverCommitTx.AddTxIn(fakeFundingTxIn)
receiverCommitTx.AddTxOut(htlcOutput)
}
aliceSenderSig, err := aliceSigner.SignOutputRaw(sweepTx, &aliceSignDesc)
if err != nil {
t.Fatalf("unable to generate alice signature: %v", err)
genSweepTx := func(confirmed bool) {
prevOut := &wire.OutPoint{
Hash: receiverCommitTx.TxHash(),
Index: 0,
}
sweepTx = wire.NewMsgTx(2)
sweepTx.AddTxIn(&wire.TxIn{
PreviousOutPoint: *prevOut,
})
if confirmed {
sweepTx.TxIn[0].Sequence = LockTimeToSequence(false, 1)
}
sweepTx.AddTxOut(
&wire.TxOut{
PkScript: []byte("doesn't matter"),
Value: 1 * 10e8,
},
)
sweepTxSigHashes = txscript.NewTxSigHashes(sweepTx)
aliceSigHash = txscript.SigHashAll
if confirmed {
aliceSigHash = txscript.SigHashSingle | txscript.SigHashAnyOneCanPay
}
// We'll also generate a signature on the sweep transaction above
// that will act as Alice's signature to Bob for the second level HTLC
// transaction.
aliceSignDesc := SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: aliceKeyPub,
},
SingleTweak: aliceCommitTweak,
WitnessScript: htlcWitnessScript,
Output: htlcOutput,
HashType: aliceSigHash,
SigHashes: sweepTxSigHashes,
InputIndex: 0,
}
aliceSenderSig, err = aliceSigner.SignOutputRaw(sweepTx, &aliceSignDesc)
if err != nil {
t.Fatalf("unable to generate alice signature: %v", err)
}
}
// TODO(roasbeef): modify valid to check precise script errors?
@@ -476,6 +709,9 @@ func TestHTLCReceiverSpendValidation(t *testing.T) {
{
// HTLC redemption w/ invalid preimage size
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
genCommitTx(false)
genSweepTx(false)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: bobKeyPub,
@@ -488,9 +724,11 @@ func TestHTLCReceiverSpendValidation(t *testing.T) {
InputIndex: 0,
}
return ReceiverHtlcSpendRedeem(aliceSenderSig,
return ReceiverHtlcSpendRedeem(
aliceSenderSig, aliceSigHash,
bytes.Repeat([]byte{1}, 45), bobSigner,
signDesc, sweepTx)
signDesc, sweepTx,
)
}),
false,
@@ -498,6 +736,9 @@ func TestHTLCReceiverSpendValidation(t *testing.T) {
{
// HTLC redemption w/ valid preimage size
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
genCommitTx(false)
genSweepTx(false)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: bobKeyPub,
@@ -510,15 +751,20 @@ func TestHTLCReceiverSpendValidation(t *testing.T) {
InputIndex: 0,
}
return ReceiverHtlcSpendRedeem(aliceSenderSig,
paymentPreimage[:], bobSigner,
signDesc, sweepTx)
return ReceiverHtlcSpendRedeem(
aliceSenderSig, aliceSigHash,
paymentPreimage, bobSigner,
signDesc, sweepTx,
)
}),
true,
},
{
// revoke w/ sig
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
genCommitTx(false)
genSweepTx(false)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: aliceKeyPub,
@@ -536,9 +782,76 @@ func TestHTLCReceiverSpendValidation(t *testing.T) {
}),
true,
},
{
// HTLC redemption w/ valid preimage size, and with
// enforced locktime in HTLC scripts.
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
// Make a commit tx that needs confirmation for
// HTLC output to be spent.
genCommitTx(true)
// Generate a sweep with the locktime set.
genSweepTx(true)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: bobKeyPub,
},
SingleTweak: bobCommitTweak,
WitnessScript: htlcWitnessScript,
Output: htlcOutput,
HashType: txscript.SigHashAll,
SigHashes: sweepTxSigHashes,
InputIndex: 0,
}
return ReceiverHtlcSpendRedeem(
aliceSenderSig, aliceSigHash,
paymentPreimage, bobSigner,
signDesc, sweepTx,
)
}),
true,
},
{
// HTLC redemption w/ valid preimage size, but trying
// to spend CSV output without sequence set.
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
// Generate commitment tx with 1 CSV locked
// HTLC.
genCommitTx(true)
// Generate sweep tx that doesn't have locktime
// enabled.
genSweepTx(false)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: bobKeyPub,
},
SingleTweak: bobCommitTweak,
WitnessScript: htlcWitnessScript,
Output: htlcOutput,
HashType: txscript.SigHashAll,
SigHashes: sweepTxSigHashes,
InputIndex: 0,
}
return ReceiverHtlcSpendRedeem(
aliceSenderSig, aliceSigHash,
paymentPreimage, bobSigner, signDesc,
sweepTx,
)
}),
false,
},
{
// refund w/ invalid lock time
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
genCommitTx(false)
genSweepTx(false)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: aliceKeyPub,
@@ -559,6 +872,9 @@ func TestHTLCReceiverSpendValidation(t *testing.T) {
{
// refund w/ valid lock time
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
genCommitTx(false)
genSweepTx(false)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: aliceKeyPub,
@@ -576,42 +892,75 @@ func TestHTLCReceiverSpendValidation(t *testing.T) {
}),
true,
},
{
// refund w/ valid lock time, and enforced locktime in
// HTLC scripts.
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
// Make a commit tx that needs confirmation for
// HTLC output to be spent.
genCommitTx(true)
// Generate a sweep with the locktime set.
genSweepTx(true)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: aliceKeyPub,
},
SingleTweak: aliceCommitTweak,
WitnessScript: htlcWitnessScript,
Output: htlcOutput,
HashType: txscript.SigHashAll,
SigHashes: sweepTxSigHashes,
InputIndex: 0,
}
return ReceiverHtlcSpendTimeout(aliceSigner, signDesc,
sweepTx, int32(cltvTimeout))
}),
true,
},
{
// refund w/ valid lock time, but no sequence set in
// sweep tx trying to spend CSV locked HTLC output.
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
// Generate commitment tx with 1 CSV locked
// HTLC.
genCommitTx(true)
// Generate sweep tx that doesn't have locktime
// enabled.
genSweepTx(false)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: aliceKeyPub,
},
SingleTweak: aliceCommitTweak,
WitnessScript: htlcWitnessScript,
Output: htlcOutput,
HashType: txscript.SigHashAll,
SigHashes: sweepTxSigHashes,
InputIndex: 0,
}
return ReceiverHtlcSpendTimeout(aliceSigner, signDesc,
sweepTx, int32(cltvTimeout))
}),
false,
},
}
for i, testCase := range testCases {
sweepTx.TxIn[0].Witness = testCase.witness()
vm, err := txscript.NewEngine(htlcPkScript,
sweepTx, 0, txscript.StandardVerifyFlags, nil,
nil, int64(paymentAmt))
if err != nil {
t.Fatalf("unable to create engine: %v", err)
newEngine := func() (*txscript.Engine, error) {
return txscript.NewEngine(htlcPkScript,
sweepTx, 0, txscript.StandardVerifyFlags, nil,
nil, int64(paymentAmt))
}
// This buffer will trace execution of the Script, only dumping
// out to stdout in the case that a test fails.
var debugBuf bytes.Buffer
done := false
for !done {
dis, err := vm.DisasmPC()
if err != nil {
t.Fatalf("stepping (%v)\n", err)
}
debugBuf.WriteString(fmt.Sprintf("stepping %v\n", dis))
done, err = vm.Step()
if err != nil && testCase.valid {
fmt.Println(debugBuf.String())
t.Fatalf("spend test case #%v failed, spend should be valid: %v", i, err)
} else if err == nil && !testCase.valid && done {
fmt.Println(debugBuf.String())
t.Fatalf("spend test case #%v succeed, spend should be invalid: %v", i, err)
}
debugBuf.WriteString(fmt.Sprintf("Stack: %v", vm.GetStack()))
debugBuf.WriteString(fmt.Sprintf("AltStack: %v", vm.GetAltStack()))
}
assertEngineExecution(t, i, testCase.valid, newEngine)
}
}
@@ -811,39 +1160,227 @@ func TestSecondLevelHtlcSpends(t *testing.T) {
for i, testCase := range testCases {
sweepTx.TxIn[0].Witness = testCase.witness()
vm, err := txscript.NewEngine(htlcPkScript,
sweepTx, 0, txscript.StandardVerifyFlags, nil,
nil, int64(htlcAmt))
if err != nil {
t.Fatalf("unable to create engine: %v", err)
newEngine := func() (*txscript.Engine, error) {
return txscript.NewEngine(htlcPkScript,
sweepTx, 0, txscript.StandardVerifyFlags, nil,
nil, int64(htlcAmt))
}
// This buffer will trace execution of the Script, only dumping
// out to stdout in the case that a test fails.
var debugBuf bytes.Buffer
assertEngineExecution(t, i, testCase.valid, newEngine)
}
}
done := false
for !done {
dis, err := vm.DisasmPC()
if err != nil {
t.Fatalf("stepping (%v)\n", err)
}
debugBuf.WriteString(fmt.Sprintf("stepping %v\n", dis))
// TestCommitSpendToRemoteConfirmed checks that the delayed version of the
// to_remote version can only be spent by the owner, and after one
// confirmation.
func TestCommitSpendToRemoteConfirmed(t *testing.T) {
t.Parallel()
done, err = vm.Step()
if err != nil && testCase.valid {
fmt.Println(debugBuf.String())
t.Fatalf("spend test case #%v failed, spend "+
"should be valid: %v", i, err)
} else if err == nil && !testCase.valid && done {
fmt.Println(debugBuf.String())
t.Fatalf("spend test case #%v succeed, spend "+
"should be invalid: %v", i, err)
}
const outputVal = btcutil.Amount(2 * 10e8)
debugBuf.WriteString(fmt.Sprintf("Stack: %v", vm.GetStack()))
debugBuf.WriteString(fmt.Sprintf("AltStack: %v", vm.GetAltStack()))
aliceKeyPriv, aliceKeyPub := btcec.PrivKeyFromBytes(btcec.S256(),
testWalletPrivKey)
txid, err := chainhash.NewHash(testHdSeed.CloneBytes())
if err != nil {
t.Fatalf("unable to create txid: %v", err)
}
commitOut := &wire.OutPoint{
Hash: *txid,
Index: 0,
}
commitScript, err := CommitScriptToRemoteConfirmed(aliceKeyPub)
if err != nil {
t.Fatalf("unable to create htlc script: %v", err)
}
commitPkScript, err := WitnessScriptHash(commitScript)
if err != nil {
t.Fatalf("unable to create htlc output: %v", err)
}
commitOutput := &wire.TxOut{
PkScript: commitPkScript,
Value: int64(outputVal),
}
sweepTx := wire.NewMsgTx(2)
sweepTx.AddTxIn(wire.NewTxIn(commitOut, nil, nil))
sweepTx.AddTxOut(
&wire.TxOut{
PkScript: []byte("doesn't matter"),
Value: 1 * 10e8,
},
)
aliceSigner := &MockSigner{Privkeys: []*btcec.PrivateKey{aliceKeyPriv}}
testCases := []struct {
witness func() wire.TxWitness
valid bool
}{
{
// Alice can spend after the a CSV delay has passed.
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
sweepTx.TxIn[0].Sequence = LockTimeToSequence(false, 1)
sweepTxSigHashes := txscript.NewTxSigHashes(sweepTx)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: aliceKeyPub,
},
WitnessScript: commitScript,
Output: commitOutput,
HashType: txscript.SigHashAll,
SigHashes: sweepTxSigHashes,
InputIndex: 0,
}
return CommitSpendToRemoteConfirmed(aliceSigner, signDesc,
sweepTx)
}),
true,
},
{
// Alice cannot spend output without sequence set.
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
sweepTx.TxIn[0].Sequence = wire.MaxTxInSequenceNum
sweepTxSigHashes := txscript.NewTxSigHashes(sweepTx)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: aliceKeyPub,
},
WitnessScript: commitScript,
Output: commitOutput,
HashType: txscript.SigHashAll,
SigHashes: sweepTxSigHashes,
InputIndex: 0,
}
return CommitSpendToRemoteConfirmed(aliceSigner, signDesc,
sweepTx)
}),
false,
},
}
for i, testCase := range testCases {
sweepTx.TxIn[0].Witness = testCase.witness()
newEngine := func() (*txscript.Engine, error) {
return txscript.NewEngine(commitPkScript,
sweepTx, 0, txscript.StandardVerifyFlags, nil,
nil, int64(outputVal))
}
assertEngineExecution(t, i, testCase.valid, newEngine)
}
}
// TestSpendAnchor checks that we can spend the anchors using the various spend
// paths.
func TestSpendAnchor(t *testing.T) {
t.Parallel()
const anchorSize = 294
// First we'll set up some initial key state for Alice.
aliceKeyPriv, aliceKeyPub := btcec.PrivKeyFromBytes(btcec.S256(),
testWalletPrivKey)
// Create a fake anchor outpoint that we'll use to generate the
// sweeping transaction.
txid, err := chainhash.NewHash(testHdSeed.CloneBytes())
if err != nil {
t.Fatalf("unable to create txid: %v", err)
}
anchorOutPoint := &wire.OutPoint{
Hash: *txid,
Index: 0,
}
sweepTx := wire.NewMsgTx(2)
sweepTx.AddTxIn(wire.NewTxIn(anchorOutPoint, nil, nil))
sweepTx.AddTxOut(
&wire.TxOut{
PkScript: []byte("doesn't matter"),
Value: 1 * 10e8,
},
)
// Generate the anchor script that can be spent by Alice immediately,
// or by anyone after 16 blocks.
anchorScript, err := CommitScriptAnchor(aliceKeyPub)
if err != nil {
t.Fatalf("unable to create htlc script: %v", err)
}
anchorPkScript, err := WitnessScriptHash(anchorScript)
if err != nil {
t.Fatalf("unable to create htlc output: %v", err)
}
anchorOutput := &wire.TxOut{
PkScript: anchorPkScript,
Value: int64(anchorSize),
}
// Create mock signer for Alice.
aliceSigner := &MockSigner{Privkeys: []*btcec.PrivateKey{aliceKeyPriv}}
testCases := []struct {
witness func() wire.TxWitness
valid bool
}{
{
// Alice can spend immediately.
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
sweepTx.TxIn[0].Sequence = wire.MaxTxInSequenceNum
sweepTxSigHashes := txscript.NewTxSigHashes(sweepTx)
signDesc := &SignDescriptor{
KeyDesc: keychain.KeyDescriptor{
PubKey: aliceKeyPub,
},
WitnessScript: anchorScript,
Output: anchorOutput,
HashType: txscript.SigHashAll,
SigHashes: sweepTxSigHashes,
InputIndex: 0,
}
return CommitSpendAnchor(aliceSigner, signDesc,
sweepTx)
}),
true,
},
{
// Anyone can spend after 16 blocks.
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
sweepTx.TxIn[0].Sequence = LockTimeToSequence(false, 16)
return CommitSpendAnchorAnyone(anchorScript)
}),
true,
},
{
// Anyone cannot spend before 16 blocks.
makeWitnessTestCase(t, func() (wire.TxWitness, error) {
sweepTx.TxIn[0].Sequence = LockTimeToSequence(false, 15)
return CommitSpendAnchorAnyone(anchorScript)
}),
false,
},
}
for i, testCase := range testCases {
sweepTx.TxIn[0].Witness = testCase.witness()
newEngine := func() (*txscript.Engine, error) {
return txscript.NewEngine(anchorPkScript,
sweepTx, 0, txscript.StandardVerifyFlags, nil,
nil, int64(anchorSize))
}
assertEngineExecution(t, i, testCase.valid, newEngine)
}
}
+76 -33
View File
@@ -132,6 +132,12 @@ const (
// - 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)
@@ -169,9 +175,32 @@ const (
// WitnessCommitmentTxWeight 224 weight
WitnessCommitmentTxWeight = WitnessHeaderSize + WitnessSize
// 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
@@ -183,6 +212,23 @@ const (
// 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
@@ -223,7 +269,23 @@ const (
// - witness_script (to_local_script)
ToLocalPenaltyWitnessSize = 1 + 1 + 73 + 1 + 1 + ToLocalScriptSize
// AcceptedHtlcScriptSize 139 bytes
// 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 142 bytes
// - OP_DUP: 1 byte
// - OP_HASH160: 1 byte
// - OP_DATA: 1 byte (RIPEMD160(SHA256(revocationkey)) length)
@@ -257,11 +319,14 @@ const (
// - 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 + 7*1 + 20 + 4*1 +
33 + 5*1 + 4 + 5*1
33 + 5*1 + 4 + 8*1
// AcceptedHtlcTimeoutWitnessSize 216
// AcceptedHtlcTimeoutWitnessSize 219
// - number_of_witness_elements: 1 byte
// - sender_sig_length: 1 byte
// - sender_sig: 73 bytes
@@ -270,20 +335,7 @@ const (
// - witness_script: (accepted_htlc_script)
AcceptedHtlcTimeoutWitnessSize = 1 + 1 + 73 + 1 + 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 + 73 + 1 + 73 + 1 + 32 + 1 + AcceptedHtlcScriptSize
// AcceptedHtlcPenaltyWitnessSize 249 bytes
// AcceptedHtlcPenaltyWitnessSize 252 bytes
// - number_of_witness_elements: 1 byte
// - revocation_sig_length: 1 byte
// - revocation_sig: 73 bytes
@@ -293,7 +345,7 @@ const (
// - witness_script (accepted_htlc_script)
AcceptedHtlcPenaltyWitnessSize = 1 + 1 + 73 + 1 + 33 + 1 + AcceptedHtlcScriptSize
// OfferedHtlcScriptSize 133 bytes
// OfferedHtlcScriptSize 136 bytes
// - OP_DUP: 1 byte
// - OP_HASH160: 1 byte
// - OP_DATA: 1 byte (RIPEMD160(SHA256(revocationkey)) length)
@@ -324,22 +376,13 @@ const (
// - 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 + 4*1
OfferedHtlcScriptSize = 3*1 + 20 + 5*1 + 33 + 10*1 + 33 + 5*1 + 20 + 7*1
// 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
// OfferedHtlcSuccessWitnessSize 317 bytes
// OfferedHtlcSuccessWitnessSize 320 bytes
// - number_of_witness_elements: 1 byte
// - nil_length: 1 byte
// - receiver_sig_length: 1 byte
@@ -352,7 +395,7 @@ const (
// - witness_script (offered_htlc_script)
OfferedHtlcSuccessWitnessSize = 1 + 1 + 1 + 73 + 1 + 73 + 1 + 32 + 1 + OfferedHtlcScriptSize
// OfferedHtlcPenaltyWitnessSize 243 bytes
// OfferedHtlcPenaltyWitnessSize 246 bytes
// - number_of_witness_elements: 1 byte
// - revocation_sig_length: 1 byte
// - revocation_sig: 73 bytes
+1 -1
View File
@@ -67,7 +67,7 @@ func (m *MockSigner) SignOutputRaw(tx *wire.MsgTx, signDesc *SignDescriptor) ([]
sig, err := txscript.RawTxInWitnessSignature(tx, signDesc.SigHashes,
signDesc.InputIndex, signDesc.Output.Value, signDesc.WitnessScript,
txscript.SigHashAll, privKey)
signDesc.HashType, privKey)
if err != nil {
return nil, err
}
+27 -2
View File
@@ -48,8 +48,9 @@ type StandardWitnessType uint16
var _ WitnessType = (StandardWitnessType)(0)
const (
// CommitmentTimeLock is a witness that allows us to spend the output of
// a commitment transaction after a relative lock-time lockout.
// 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
@@ -119,6 +120,11 @@ const (
// 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
)
// String returns a human readable version of the target WitnessType.
@@ -129,6 +135,9 @@ func (wt StandardWitnessType) String() string {
case CommitmentTimeLock:
return "CommitmentTimeLock"
case CommitmentToRemoteConfirmed:
return "CommitmentToRemoteConfirmed"
case CommitmentNoDelay:
return "CommitmentNoDelay"
@@ -197,6 +206,18 @@ func (wt StandardWitnessType) WitnessGenerator(signer Signer,
Witness: witness,
}, nil
case CommitmentToRemoteConfirmed:
witness, err := CommitSpendToRemoteConfirmed(
signer, desc, tx,
)
if err != nil {
return nil, err
}
return &Script{
Witness: witness,
}, nil
case CommitmentNoDelay:
witness, err := CommitSpendNoDelay(signer, desc, tx, false)
if err != nil {
@@ -323,6 +344,10 @@ func (wt StandardWitnessType) SizeUpperBound() (int, bool, error) {
case CommitmentTimeLock:
return ToLocalTimeoutWitnessSize, false, nil
// 1 CSV time locked output to us on remote commitment.
case CommitmentToRemoteConfirmed:
return ToRemoteConfirmedWitnessSize, false, nil
// Outgoing second layer HTLC's that have confirmed within the
// chain, and the output they produced is now mature enough to
// sweep.