diff --git a/channeldb/channel_test.go b/channeldb/channel_test.go index 248f5348dc0..b4df8e7af43 100644 --- a/channeldb/channel_test.go +++ b/channeldb/channel_test.go @@ -660,6 +660,47 @@ func assertRevocationLogEntryEqual(t *testing.T, c *ChannelCommitment, } } +// TestUpdateCommitmentRevocationAuxSigsRollback asserts that the revocation +// aux sigs held in memory always match what was persisted. They are set on +// the channel before the store writes them, so a write that fails must leave +// the previous value in place. Otherwise a retransmission would send a blob +// that is gone after a restart. +func TestUpdateCommitmentRevocationAuxSigsRollback(t *testing.T) { + t.Parallel() + + fullDB, err := MakeTestDB(t) + require.NoError(t, err, "unable to make test database") + + cdb := fullDB.ChannelStateDB() + channel := createTestChannel(t, cdb) + + commitment := channel.LocalCommitment + commitment.CommitHeight++ + + // A successful update persists the sigs. + firstSigs := fn.Some(tlv.Blob{1, 2, 3}) + _, err = channel.UpdateCommitment(&commitment, nil, firstSigs) + require.NoError(t, err) + require.Equal(t, firstSigs, channel.RevocationAuxSigs) + + // Once the channel is borked, further updates are refused by the + // store. The sigs of the refused update must not stick in memory. + require.NoError(t, channel.MarkBorked()) + + commitment.CommitHeight++ + _, err = channel.UpdateCommitment( + &commitment, nil, fn.Some(tlv.Blob{4, 5, 6}), + ) + require.ErrorIs(t, err, ErrChanBorked) + require.Equal(t, firstSigs, channel.RevocationAuxSigs) + + // What is on disk is the first blob as well. + openChannels, err := cdb.FetchOpenChannels(channel.IdentityPub) + require.NoError(t, err) + require.Len(t, openChannels, 1) + require.Equal(t, firstSigs, openChannels[0].RevocationAuxSigs) +} + func TestChannelStateTransition(t *testing.T) { t.Parallel() @@ -736,7 +777,9 @@ func TestChannelStateTransition(t *testing.T) { }, } - _, err = channel.UpdateCommitment(&commitment, unsignedAckedUpdates) + _, err = channel.UpdateCommitment( + &commitment, unsignedAckedUpdates, fn.None[tlv.Blob](), + ) require.NoError(t, err, "unable to update commitment") // Assert that update is correctly written to the database. diff --git a/channeldb/db_test.go b/channeldb/db_test.go index 1f87e3b668a..b43f48a8c61 100644 --- a/channeldb/db_test.go +++ b/channeldb/db_test.go @@ -14,6 +14,7 @@ import ( "github.com/btcsuite/btcd/btcutil/v2" "github.com/btcsuite/btcd/chainhash/v2" "github.com/btcsuite/btcd/wire/v2" + "github.com/lightningnetwork/lnd/fn/v2" "github.com/lightningnetwork/lnd/graph/db/models" "github.com/lightningnetwork/lnd/keychain" "github.com/lightningnetwork/lnd/kvdb" @@ -21,6 +22,7 @@ import ( "github.com/lightningnetwork/lnd/lnwire" "github.com/lightningnetwork/lnd/routing/route" "github.com/lightningnetwork/lnd/shachain" + "github.com/lightningnetwork/lnd/tlv" "github.com/stretchr/testify/require" ) @@ -382,7 +384,7 @@ func TestRestoreChannelShells(t *testing.T) { // Ensure that it isn't possible to modify the commitment state machine // of this restored channel. channel := nodeChans[0] - _, err = channel.UpdateCommitment(nil, nil) + _, err = channel.UpdateCommitment(nil, nil, fn.None[tlv.Blob]()) if err != ErrNoRestoredChannelMutation { t.Fatalf("able to mutate restored channel") } diff --git a/chanstate/kv_open_channel.go b/chanstate/kv_open_channel.go index 98d5ab7cd34..96c1ea5a938 100644 --- a/chanstate/kv_open_channel.go +++ b/chanstate/kv_open_channel.go @@ -620,6 +620,13 @@ type openChannelTlvData struct { // Note: if not set, it means either the channel has not been // closed yet, or it was closed before this field was introduced. closeConfirmationHeight tlv.OptionalRecordT[tlv.TlvType9, uint32] + + // revocationAuxSigs is an optional blob carrying the revocation aux + // signatures attached to the most recently sent RevokeAndAck. It is + // only ever set for aux/custom (taproot asset) channels, so the same + // signatures can be re-attached if that RevokeAndAck has to be + // retransmitted on channel reestablish. + revocationAuxSigs tlv.OptionalRecordT[tlv.TlvType10, tlv.Blob] } // encode serializes the openChannelTlvData to the given io.Writer. @@ -648,6 +655,12 @@ func (c *openChannelTlvData) encode(w io.Writer) error { }, ) + c.revocationAuxSigs.WhenSome( + func(sigs tlv.RecordT[tlv.TlvType10, tlv.Blob]) { + tlvRecords = append(tlvRecords, sigs.Record()) + }, + ) + tlv.SortRecords(tlvRecords) // Create the tlv stream. @@ -665,6 +678,7 @@ func (c *openChannelTlvData) decode(r io.Reader) error { tapscriptRoot := c.tapscriptRoot.Zero() blob := c.customBlob.Zero() closeConfHeight := c.closeConfirmationHeight.Zero() + revocationAuxSigs := c.revocationAuxSigs.Zero() // Create the tlv stream. tlvStream, err := tlv.NewStream( @@ -677,6 +691,7 @@ func (c *openChannelTlvData) decode(r io.Reader) error { blob.Record(), c.confirmationHeight.Record(), closeConfHeight.Record(), + revocationAuxSigs.Record(), ) if err != nil { return err @@ -699,6 +714,9 @@ func (c *openChannelTlvData) decode(r io.Reader) error { if _, ok := tlvs[closeConfHeight.TlvType()]; ok { c.closeConfirmationHeight = tlv.SomeRecordT(closeConfHeight) } + if _, ok := tlvs[revocationAuxSigs.TlvType()]; ok { + c.revocationAuxSigs = tlv.SomeRecordT(revocationAuxSigs) + } return nil } @@ -748,6 +766,9 @@ func amendOpenChannelTlvData(channel *OpenChannel, auxData openChannelTlvData) { auxData.closeConfirmationHeight.WhenSomeV(func(h uint32) { channel.CloseConfirmationHeight = fn.Some(h) }) + auxData.revocationAuxSigs.WhenSomeV(func(sigs tlv.Blob) { + channel.RevocationAuxSigs = fn.Some(sigs) + }) } // extractOpenChannelTlvData creates a new openChannelTlvData from the given @@ -791,6 +812,11 @@ func extractOpenChannelTlvData(channel *OpenChannel) openChannelTlvData { tlv.NewPrimitiveRecord[tlv.TlvType9](h), ) }) + channel.RevocationAuxSigs.WhenSome(func(sigs tlv.Blob) { + auxData.revocationAuxSigs = tlv.SomeRecordT( + tlv.NewPrimitiveRecord[tlv.TlvType10](sigs), + ) + }) return auxData } diff --git a/chanstate/open_channel.go b/chanstate/open_channel.go index e0558f392e9..033e64f69dd 100644 --- a/chanstate/open_channel.go +++ b/chanstate/open_channel.go @@ -223,6 +223,15 @@ type OpenChannel struct { // immutable. CustomBlob fn.Option[tlv.Blob] + // RevocationAuxSigs is an optional blob carrying the revocation aux + // signatures attached to the most recently sent RevokeAndAck. It is + // only ever set for aux/custom (taproot asset) channels, and is + // persisted so the exact same signatures can be re-attached if that + // RevokeAndAck has to be retransmitted on channel reestablish. Only + // the latest revocation can ever be owed to the peer, so a single + // slot suffices; it is overwritten on every revocation. + RevocationAuxSigs fn.Option[tlv.Blob] + // Db persists channel state through the Store contract. This field // intentionally keeps the existing name while callers still construct // channels through the channeldb compatibility alias. The store @@ -814,7 +823,8 @@ func (c *OpenChannel) SyncPending(addr net.Addr, pendingHeight uint32) error { // commitment. Keys correspond to htlc indices and values indicate whether the // htlc was settled or failed. func (c *OpenChannel) UpdateCommitment(newCommitment *ChannelCommitment, - unsignedAckedUpdates []LogUpdate) (map[uint64]bool, error) { + unsignedAckedUpdates []LogUpdate, + revocationAuxSigs fn.Option[tlv.Blob]) (map[uint64]bool, error) { c.Lock() defer c.Unlock() @@ -826,10 +836,24 @@ func (c *OpenChannel) UpdateCommitment(newCommitment *ChannelCommitment, return nil, ErrNoRestoredChannelMutation } + // Record the aux sigs attached to the RevokeAndAck this commitment + // update corresponds to (custom channels only, None otherwise), so + // they persist alongside it and survive for retransmission. This + // overwrites the previous revocation's sigs, which can no longer be + // owed to the peer. The store serializes them from the channel + // itself, so they have to be set before the write, and are rolled + // back if the write fails: the in-memory copy must never hold sigs + // that were not persisted, or a retransmission would send a blob + // that does not survive a restart. + prevRevocationAuxSigs := c.RevocationAuxSigs + c.RevocationAuxSigs = revocationAuxSigs + finalHtlcs, err := c.Db.UpdateChannelCommitment( c, newCommitment, unsignedAckedUpdates, ) if err != nil { + c.RevocationAuxSigs = prevRevocationAuxSigs + return nil, err } diff --git a/contractcourt/breach_arbitrator.go b/contractcourt/breach_arbitrator.go index 65bc53697ef..ba7c3025374 100644 --- a/contractcourt/breach_arbitrator.go +++ b/contractcourt/breach_arbitrator.go @@ -61,6 +61,12 @@ var ( // errBrarShuttingDown is an error returned if the BreachArbitrator has // been signalled to exit. errBrarShuttingDown = errors.New("BreachArbitrator shutting down") + + // errSecondLevelOutputNotFound is returned when the second-level + // output of a breached aux channel HTLC cannot be located in the + // transaction that took the HTLC to the second level. + errSecondLevelOutputNotFound = errors.New("no unclaimed output " + + "matching the expected second-level taproot pkScript") ) // ContractBreachEvent is an event the BreachArbitrator will receive in case a @@ -128,6 +134,14 @@ type RetributionStorer interface { // chosen, read-only callback to each. This method should ensure that it // immediately propagate any errors generated by the callback. ForAll(cb func(*retributionInfo) error, reset func()) error + + // RecordJusticeTxs persists the metadata of justice transactions + // created for the breach of the given channel, keyed by txid, so the + // aux sweeper can still be told about the one that confirms after a + // restart. It is only called for channels that carry aux resolution + // data. + RecordJusticeTxs(chanPoint *wire.OutPoint, + justiceTxs map[chainhash.Hash]*justiceTxCtx) error } // BreachConfig bundles the required subsystems used by the breach arbiter. An @@ -179,6 +193,11 @@ type BreachConfig struct { // AuxSweeper is an optional interface that can be used to modify the // way sweep transaction are generated. AuxSweeper fn.Option[sweep.AuxSweeper] + + // AuxResolver is an optional interface for resolving auxiliary + // contract data. Used to generate resolution blobs for second-level + // HTLC revocations at morph time. + AuxResolver fn.Option[lnwallet.AuxContractResolver] } // BreachArbitrator is a special subsystem which is responsible for watching and @@ -539,60 +558,252 @@ func (b *BreachArbitrator) waitForSpendEvent(breachInfo *retributionInfo, } } +// findSecondLevelOutputIndex searches the spending (second-level) transaction's +// outputs for the one that matches the expected second-level HTLC output +// script. This is necessary because SpenderInputIndex (which identifies the +// input that spent our output) does NOT necessarily correspond to the output +// index: the second-level tx may contain additional inputs (e.g. wallet UTXOs +// for fees) that shift the input indices. +// +// Several HTLCs of one commitment can share a second-level script, as it only +// depends on keys, the CSV delay and the aux leaf. The script alone then does +// not tell their outputs apart, so outputs that already belong to another +// breached output (as reported by claimed) are skipped, and among the rest +// the output at the index of the spending input is preferred, which is where +// a second-level tx that pairs inputs with outputs puts it. +func findSecondLevelOutputIndex(bo *breachedOutput, spendingTx *wire.MsgTx, + spenderInputIndex uint32, + claimed func(wire.OutPoint) bool) (uint32, error) { + + isTaproot := txscript.IsPayToTaproot(bo.signDesc.Output.PkScript) + if !isTaproot || bo.signDesc.DoubleTweak == nil { + return 0, fmt.Errorf("cannot derive expected pkScript: " + + "non-taproot or missing DoubleTweak") + } + + // For taproot outputs we derive the expected pkScript from the + // revocation key and the second-level tap tweak. + // + // Derive the revocation public key from the revocation base point + // and the commitment secret (DoubleTweak). + commitPoint := bo.signDesc.DoubleTweak.PubKey() + revokeKey := input.DeriveRevocationPubkey( + bo.signDesc.KeyDesc.PubKey, commitPoint, + ) + + // Compute the expected taproot output key using the revocation key + // as internal key and the second-level tap tweak. + expectedOutputKey := txscript.ComputeTaprootOutputKey( + revokeKey, bo.secondLevelTapTweak[:], + ) + expectedPkScript, err := input.PayToTaprootScript(expectedOutputKey) + if err != nil { + return 0, fmt.Errorf("unable to compute expected pkScript: %w", + err) + } + + // An output is a candidate if it carries the expected script and no + // other breached output has been assigned to it yet. + txHash := spendingTx.TxHash() + isCandidate := func(idx uint32) bool { + if int(idx) >= len(spendingTx.TxOut) { + return false + } + + txOut := spendingTx.TxOut[idx] + if !bytes.Equal(txOut.PkScript, expectedPkScript) { + return false + } + + return !claimed(wire.OutPoint{Hash: txHash, Index: idx}) + } + + if isCandidate(spenderInputIndex) { + return spenderInputIndex, nil + } + for i := range spendingTx.TxOut { + if isCandidate(uint32(i)) { + return uint32(i), nil + } + } + + // Log details to help diagnose why no match was found. + brarLog.Warnf("Expected second-level pkScript %x (revokeKey=%x, "+ + "tapTweak=%x) not found among the unclaimed outputs of the "+ + "%d outputs of tx %s", expectedPkScript, + revokeKey.SerializeCompressed(), bo.secondLevelTapTweak[:], + len(spendingTx.TxOut), txHash) + for i, txOut := range spendingTx.TxOut { + brarLog.Warnf(" output %d: pkScript=%x value=%d", + i, txOut.PkScript, txOut.Value) + } + + return 0, fmt.Errorf("%w in tx %s", errSecondLevelOutputNotFound, + txHash) +} + // convertToSecondLevelRevoke takes a breached output, and a transaction that // spends it to the second level, and mutates the breach output into one that // is able to properly sweep that second level output. We'll use this function // when we go to sweep a breached commitment transaction, but the cheating // party has already attempted to take it to the second level. +// +// Everything is worked out first and only then committed to the breached +// output, so an error leaves the output exactly as it was. The only error is +// errSecondLevelOutputNotFound, returned when the second-level output of an +// aux channel HTLC cannot be located in the spending transaction. func convertToSecondLevelRevoke(bo *breachedOutput, breachInfo *retributionInfo, - spendDetails *chainntnfs.SpendDetail) { + spendDetails *chainntnfs.SpendDetail, + auxResolver fn.Option[lnwallet.AuxContractResolver]) error { // In this case, we'll modify the witness type of this output to // actually prepare for a second level revoke. - isTaproot := txscript.IsPayToTaproot(bo.signDesc.Output.PkScript) - if isTaproot { - bo.witnessType = input.TaprootHtlcSecondLevelRevoke - } else { - bo.witnessType = input.HtlcSecondLevelRevoke + witnessType := input.HtlcSecondLevelRevoke + if txscript.IsPayToTaproot(bo.signDesc.Output.PkScript) { + witnessType = input.TaprootHtlcSecondLevelRevoke + } + + // Find the correct output index in the spending (second-level) tx. + // + // On aux (taproot-asset) channels the second-level tx may bundle + // multiple HTLCs and/or wallet UTXOs for fees, so input index no + // longer matches output index. We script-match our expected + // second-level pkScript to locate the right output. + // + // On non-aux channels (regular legacy/anchor/taproot, including + // non-custom simple taproot) we keep the legacy behavior of using + // SpenderInputIndex directly, so we don't regress sweep behavior on + // normal channels. + // + // resolveReq is a reliable aux-channel discriminator here: it is + // populated in createHtlcRetribution only for channels with a + // tapscript root (aux/custom channels), and restored from the + // retribution store after a restart, so a nil resolveReq + // unambiguously means "not a custom channel" and takes the legacy + // path below. + spendingTx := spendDetails.SpendingTx + isAuxChannel := bo.resolveReq != nil + + outputIndex := spendDetails.SpenderInputIndex + if isAuxChannel { + idx, err := findSecondLevelOutputIndex( + bo, spendingTx, spendDetails.SpenderInputIndex, + breachInfo.claimsOutpoint, + ) + if err != nil { + return err + } + outputIndex = idx + } + + // Re-resolve the aux contract blob for the second-level witness + // type. The blob we hold was resolved for the output on the + // commitment, which is spent now, so it must not be carried over to + // the second-level output. If the resolver fails, the output is + // still converted and swept for its BTC value, just without a blob: + // one HTLC the resolver cannot handle must not hold up the justice + // transactions of all the other outputs. + resolutionBlob := bo.resolutionBlob + if isAuxChannel { + blob, err := reresolveAuxBlobForSecondLevel( + bo, spendingTx, spendDetails, auxResolver, + ) + if err != nil { + brarLog.Errorf("Unable to re-resolve second-level "+ + "HTLC blob for %v of ChannelPoint(%v), "+ + "sweeping it without aux resolution: %v", + bo.outpoint, breachInfo.chanPoint, err) + } + resolutionBlob = blob } - // We'll also redirect the outpoint to this second level output, so the - // spending transaction updates it inputs accordingly. - spendingTx := spendDetails.SpendingTx - spendInputIndex := spendDetails.SpenderInputIndex + // With everything worked out, commit the conversion. oldOp := bo.outpoint + bo.witnessType = witnessType bo.outpoint = wire.OutPoint{ Hash: spendingTx.TxHash(), - Index: spendInputIndex, + Index: outputIndex, } // Next, we need to update the amount so we can do fee estimation // properly, and also so we can generate a valid signature as we need // to know the new input value (the second level transactions shaves // off some funds to fees). - newAmt := spendingTx.TxOut[spendInputIndex].Value + newAmt := spendingTx.TxOut[outputIndex].Value bo.amt = btcutil.Amount(newAmt) bo.signDesc.Output.Value = newAmt - bo.signDesc.Output.PkScript = spendingTx.TxOut[spendInputIndex].PkScript + bo.signDesc.Output.PkScript = spendingTx.TxOut[outputIndex].PkScript // For taproot outputs, the taptweak also needs to be swapped out. We // do this unconditionally as this field isn't used at all for segwit - // v0 outputs. - bo.signDesc.TapTweak = bo.secondLevelTapTweak[:] + // v0 outputs. The tweak is copied out of the breached output, as a + // slice over the array embedded in the struct keeps pointing at this + // slot of the breached outputs slice. Once updateBreachInfo compacts + // that slice, another output shifts into the slot and we would sign + // with its tweak. + bo.signDesc.TapTweak = bytes.Clone(bo.secondLevelTapTweak[:]) // Finally, we'll need to adjust the witness program in the // SignDescriptor. bo.signDesc.WitnessScript = bo.secondLevelWitnessScript + bo.resolutionBlob = resolutionBlob + brarLog.Warnf("HTLC(%v) for ChannelPoint(%v) has been spent to the "+ "second-level, adjusting -> %v", oldOp, breachInfo.chanPoint, bo.outpoint) + + return nil +} + +// reresolveAuxBlobForSecondLevel re-runs the aux contract resolution against +// the now-known second-level transaction and returns the resolution blob that +// targets the second-level witness path. The breached output is not modified. +// On error no blob is returned: the one resolved for the commitment output +// does not apply to the second-level output. +func reresolveAuxBlobForSecondLevel(bo *breachedOutput, + spendingTx *wire.MsgTx, spendDetails *chainntnfs.SpendDetail, + auxResolver fn.Option[lnwallet.AuxContractResolver]) ( + fn.Option[tlv.Blob], error) { + + none := fn.None[tlv.Blob]() + + if bo.resolveReq == nil || bo.resolveReq.KeyRing == nil { + return none, errors.New("no resolve request template") + } + + secondLevelReq := *bo.resolveReq + if bo.resolveReq.CommitTx != nil { + secondLevelReq.CommitTx = bo.resolveReq.CommitTx.Copy() + } + secondLevelReq.Type = input.TaprootHtlcSecondLevelRevoke + secondLevelReq.SecondLevel = fn.Some(lnwallet.SecondLevelInfo{ + Tx: spendingTx, + BlockHeight: uint32(spendDetails.SpendingHeight), + }) + + brarLog.Infof("Re-resolving HTLC blob for second-level revoke, "+ + "htlcID=%v, incoming=%v, htlcAmt=%v", secondLevelReq.HtlcID, + secondLevelReq.HtlcIncoming, secondLevelReq.HtlcAmt) + + resolveBlob := fn.MapOptionZ( + auxResolver, + func(a lnwallet.AuxContractResolver) fn.Result[tlv.Blob] { + return a.ResolveContract(secondLevelReq) + }, + ) + if err := resolveBlob.Err(); err != nil { + return none, err + } + + return resolveBlob.OkToSome(), nil } // updateBreachInfo mutates the passed breachInfo by removing or converting any // outputs among the spends. It also counts the total and revoked funds swept // by our justice spends. -func updateBreachInfo(breachInfo *retributionInfo, spends []spend) ( +func updateBreachInfo(breachInfo *retributionInfo, spends []spend, + auxResolver fn.Option[lnwallet.AuxContractResolver]) ( btcutil.Amount, btcutil.Amount) { inputs := breachInfo.breachedOutputs @@ -639,9 +850,26 @@ func updateBreachInfo(breachInfo *retributionInfo, spends []spend) ( // spend to instead point to the second level // output, and update the sign descriptor in the // process. - convertToSecondLevelRevoke( + err = convertToSecondLevelRevoke( breachedOutput, breachInfo, s.detail, + auxResolver, ) + if err == nil { + continue + } + + // The second-level output could not be located, so + // there is nothing we could sweep for this HTLC + // anymore. The output is dropped so the remaining + // ones can proceed, but its value is not reported as + // claimed: it was not. + brarLog.Errorf("BUG: abandoning %s(%v) of "+ + "ChannelPoint(%v), spent to the second level "+ + "by %v: %v", breachedOutput.witnessType, + breachedOutput.outpoint, breachInfo.chanPoint, + s.detail.SpenderTxHash, err) + + doneOutputs[s.index] = struct{}{} continue } @@ -689,6 +917,253 @@ func updateBreachInfo(breachInfo *retributionInfo, spends []spend) ( return totalFunds, revokedFunds } +// confirmedJusticeTx is a justice transaction of ours that confirmed and +// that the aux sweeper has not been told about yet. +type confirmedJusticeTx struct { + // tx is the confirmed transaction. + tx *wire.MsgTx + + // height is the height the transaction confirmed at. + height uint32 + + // ctx is the metadata recorded when the transaction was created. + ctx *justiceTxCtx + + // inputs holds a copy of every breached output the transaction + // spends, taken as the spends are detected, keyed by outpoint. The + // aux sweeper is only notified once all inputs of the transaction + // are collected. + inputs map[wire.OutPoint]*breachedOutput +} + +// complete returns true once every input of the transaction is collected. +func (c *confirmedJusticeTx) complete() bool { + return len(c.inputs) == len(c.tx.TxIn) +} + +// justiceTxTracker keeps track of the justice transactions created for a +// breach and of which confirmed ones the aux sweeper still has to be told +// about. The aux sweeper builds its proofs from a justice transaction only +// once it confirmed, so each confirmed justice transaction must be reported +// to it exactly once, with all of its inputs, and reporting must survive both +// a failure of the aux sweeper and a restart. +type justiceTxTracker struct { + // history holds the metadata of every justice tx created for the + // breach, keyed by txid. The variants are rebuilt every time an + // output is spent or morphed, and the transaction that ends up + // confirming may stem from any earlier rebuild, or from before a + // restart. + history map[chainhash.Hash]*justiceTxCtx + + // notified is the set of confirmed justice txs the aux sweeper was + // successfully told about. + notified map[chainhash.Hash]struct{} + + // pending holds the confirmed justice txs the aux sweeper has not + // been told about yet, either because not all of their inputs have + // been collected or because telling it failed and is to be retried. + pending map[chainhash.Hash]*confirmedJusticeTx +} + +// newJusticeTxTracker creates a tracker seeded with the justice txs that +// were recorded for the breach before a restart, if any. +func newJusticeTxTracker( + recorded map[chainhash.Hash]*justiceTxCtx) *justiceTxTracker { + + history := make(map[chainhash.Hash]*justiceTxCtx, len(recorded)) + for txid, jtx := range recorded { + history[txid] = jtx + } + + return &justiceTxTracker{ + history: history, + notified: make(map[chainhash.Hash]struct{}), + pending: make(map[chainhash.Hash]*confirmedJusticeTx), + } +} + +// record adds all non-nil justice tx variants to the history, keyed by their +// txid, and returns the ones that were not known before. +func (j *justiceTxTracker) record( + variants *justiceTxVariants) map[chainhash.Hash]*justiceTxCtx { + + added := make(map[chainhash.Hash]*justiceTxCtx) + record := func(jtx *justiceTxCtx) { + if jtx == nil || jtx.justiceTx == nil { + return + } + + hash := jtx.justiceTx.TxHash() + if _, ok := j.history[hash]; ok { + return + } + + // The history is only used to recognize a confirmed spend as + // one of our justice txs and to tell the aux sweeper about + // it. Store an immutable snapshot of the metadata that takes, + // so later rebuilds can't change what is associated with an + // older txid. The inputs are collected afresh from the spends + // that report the transaction, and the transaction itself is + // taken from there too. + snapshot := *jtx + snapshot.inputs = nil + snapshot.justiceTx = nil + + j.history[hash] = &snapshot + added[hash] = &snapshot + } + + record(variants.spendAll) + record(variants.spendCommitOuts) + record(variants.spendHTLCs) + for _, tx := range variants.spendSecondLevelHTLCs { + record(tx) + } + + return added +} + +// collect inspects a batch of spends for confirmed justice txs and collects +// the breached outputs they spend. It must be called before the spends are +// applied to the breached outputs, as that removes the outputs a justice tx +// spent. +// +// A justice tx usually spends several breached outputs, and the spend of +// each is reported on its own, possibly in different batches. After a +// restart the spends are replayed from the breach on, so a justice tx can be +// reported through one of its inputs before another input of it, an HTLC +// that was taken to the second level, has been morphed back into the output +// the justice tx spent. The inputs are therefore accumulated across batches. +func (j *justiceTxTracker) collect(spends []spend, + breachedOutputs []breachedOutput) { + + for _, s := range spends { + txid := *s.detail.SpenderTxHash + if _, ok := j.notified[txid]; ok { + continue + } + + jtx, ok := j.history[txid] + if !ok { + brarLog.Debugf("Spend txid=%v is not one of our "+ + "justice txs", txid) + + continue + } + + confirmed, ok := j.pending[txid] + if !ok { + confirmed = &confirmedJusticeTx{ + tx: s.detail.SpendingTx, + height: uint32(s.detail.SpendingHeight), + ctx: jtx, + inputs: make( + map[wire.OutPoint]*breachedOutput, + ), + } + j.pending[txid] = confirmed + } + + // Collect every breached output the transaction spends that + // we currently know at the outpoint it was spent from. The + // output is copied: it is about to be removed from the set, + // or mutated by later morphing. + for _, txIn := range confirmed.tx.TxIn { + op := txIn.PreviousOutPoint + if _, ok := confirmed.inputs[op]; ok { + continue + } + + for i := range breachedOutputs { + if breachedOutputs[i].outpoint != op { + continue + } + + bo := breachedOutputs[i] + confirmed.inputs[op] = &bo + + break + } + } + } +} + +// hasPending returns true if the aux sweeper still has to be told about a +// confirmed justice tx. +func (j *justiceTxTracker) hasPending() bool { + return len(j.pending) > 0 +} + +// notifyConfirmedJusticeTxs tells the aux sweeper about every confirmed +// justice tx whose inputs are all collected, so it can generate the aux-level +// proofs. A transaction the aux sweeper fails to take stays pending and is +// retried on the next call. +func (b *BreachArbitrator) notifyConfirmedJusticeTxs(j *justiceTxTracker) { + for txid, confirmed := range j.pending { + if !confirmed.complete() { + brarLog.Debugf("Justice tx %v confirmed, collected "+ + "%d of its %d inputs so far", txid, + len(confirmed.inputs), len(confirmed.tx.TxIn)) + + continue + } + + // The inputs are handed over in the order the transaction + // spends them. + hasSecondLevel := confirmed.ctx.hasSecondLevel + inputs := make([]input.Input, 0, len(confirmed.tx.TxIn)) + for _, txIn := range confirmed.tx.TxIn { + bo := confirmed.inputs[txIn.PreviousOutPoint] + inputs = append(inputs, bo) + + switch bo.WitnessType() { + case input.HtlcSecondLevelRevoke, + input.TaprootHtlcSecondLevelRevoke: + + hasSecondLevel = true + } + } + + brarLog.Debugf("Notifying aux sweeper of confirmed justice "+ + "tx %v (numInputs=%d, hasSecondLevel=%v)", txid, + len(inputs), hasSecondLevel) + + bumpReq := sweep.BumpRequest{ + Inputs: inputs, + DeliveryAddress: confirmed.ctx.sweepAddr, + ExtraTxOut: confirmed.ctx.extraTxOut, + } + + err := fn.MapOptionZ( + b.cfg.AuxSweeper, + func(aux sweep.AuxSweeper) error { + // The tx is already confirmed, so skip + // broadcast. + return aux.NotifyBroadcast( + &bumpReq, confirmed.tx, + confirmed.ctx.fee, nil, + sweep.AuxNotifyOpts{ + SkipBroadcast: true, + ConfirmHeight: confirmed.height, + //nolint:ll + LookupInputProofs: hasSecondLevel, + }, + ) + }, + ) + if err != nil { + brarLog.Errorf("Failed to notify aux sweeper of "+ + "confirmed justice tx %v, will retry: %v", + txid, err) + + continue + } + + j.notified[txid] = struct{}{} + delete(j.pending, txid) + } +} + // exactRetribution is a goroutine which is executed once a contract breach has // been detected by a breachObserver. This function is responsible for // punishing a counterparty for violating the channel contract by sweeping ALL @@ -725,10 +1200,30 @@ func (b *BreachArbitrator) exactRetribution( // SpendEvents between each attempt to not re-register unnecessarily. spendNtfns := make(map[wire.OutPoint]*chainntnfs.SpendEvent) + // Track all justice txs created for this breach by their txid, along + // with the confirmed ones the aux sweeper still has to be told about. + // This is needed because justiceTxs is rebuilt after each spend + // detection, and the tx that actually confirmed may have been from + // an earlier rebuild cycle, or from before a restart. Without this + // history, we can't match the confirmed tx to call NotifyBroadcast on + // the aux sweeper. + // + // Only aux (custom) channels have anything to report to the aux + // sweeper. For every other channel the tracker stays empty and + // nothing is persisted. + tracker := newJusticeTxTracker(breachInfo.justiceTxs) + trackJusticeTxs := b.cfg.AuxSweeper.IsSome() && breachInfo.hasAuxData() + // Compute both the total value of funds being swept and the // amount of funds that were revoked from the counter party. var totalFunds, revokedFunds btcutil.Amount + // allSwept is set once no breached output is left to sweep. The + // breach is only cleaned up after the aux sweeper has also been told + // about every confirmed justice tx: the retribution store is what + // lets us pick that up again after a restart. + var allSwept bool + justiceTxBroadcast: // With the breach transaction confirmed, we now create the // justice tx which will claim ALL the funds within the @@ -738,35 +1233,28 @@ justiceTxBroadcast: brarLog.Errorf("Unable to create justice tx: %v", err) return } - finalTx := justiceTxs.spendAll - - brarLog.Debugf("Broadcasting justice tx: %v", lnutils.SpewLogClosure( - finalTx)) - - // As we're about to broadcast our breach transaction, we'll notify the - // aux sweeper of our broadcast attempt first. - err = fn.MapOptionZ(b.cfg.AuxSweeper, func(aux sweep.AuxSweeper) error { - bumpReq := sweep.BumpRequest{ - Inputs: finalTx.inputs, - DeliveryAddress: finalTx.sweepAddr, - ExtraTxOut: finalTx.extraTxOut, - } - return aux.NotifyBroadcast( - &bumpReq, finalTx.justiceTx, finalTx.fee, nil, + // Record the new variants before any of them is published, so the + // one that confirms is recognized even if we restart in between. + if trackJusticeTxs { + err = b.cfg.Store.RecordJusticeTxs( + &breachInfo.chanPoint, tracker.record(justiceTxs), ) - }) - if err != nil { - brarLog.Errorf("unable to notify broadcast: %w", err) - return + if err != nil { + brarLog.Errorf("Unable to persist justice txs of "+ + "ChannelPoint(%v): %v", breachInfo.chanPoint, + err) + } } + finalTx := justiceTxs.spendAll // We'll now attempt to broadcast the transaction which finalized the // channel's retribution against the cheating counter party. label := labels.MakeLabel(labels.LabelTypeJusticeTransaction, nil) err = b.cfg.PublishTransaction(finalTx.justiceTx, label) if err != nil { - brarLog.Errorf("Unable to broadcast justice tx: %v", err) + brarLog.Errorf("Unable to broadcast initial spendAll "+ + "justice tx: %v", err) } // Regardless of publication succeeded or not, we now wait for any of @@ -805,8 +1293,25 @@ Loop: for { select { case spends := <-spendChan: + // Check if any of the spends represent a confirmed + // justice transaction, and if so, collect the outputs + // it spends while they are still part of the breach + // info. + if trackJusticeTxs { + tracker.collect( + spends, breachInfo.breachedOutputs, + ) + } + // Update the breach info with the new spends. - t, r := updateBreachInfo(breachInfo, spends) + t, r := updateBreachInfo( + breachInfo, spends, b.cfg.AuxResolver, + ) + + // Notify the aux sweeper of the confirmed justice + // transactions whose inputs are all accounted for. + b.notifyConfirmedJusticeTxs(tracker) + totalFunds += t revokedFunds += r @@ -824,6 +1329,21 @@ Loop: "resolved", breachInfo.chanPoint, revokedFunds, totalFunds) + // If the aux sweeper still has to be told + // about a confirmed justice tx, keep the + // breach around and retry on the next block. + allSwept = true + if tracker.hasPending() { + brarLog.Warnf("ChannelPoint(%v) fully "+ + "swept, waiting to notify the "+ + "aux sweeper of %d confirmed "+ + "justice tx(s)", + breachInfo.chanPoint, + len(tracker.pending)) + + continue Loop + } + err = b.cleanupBreach(&breachInfo.chanPoint) if err != nil { brarLog.Errorf("Failed to cleanup "+ @@ -852,6 +1372,27 @@ Loop: return } + // Retry telling the aux sweeper about confirmed + // justice txs it failed to take earlier. + b.notifyConfirmedJusticeTxs(tracker) + + // Once everything is swept, the only thing left to + // wait for is the aux sweeper. + if allSwept { + if tracker.hasPending() { + continue Loop + } + + err = b.cleanupBreach(&breachInfo.chanPoint) + if err != nil { + brarLog.Errorf("Failed to cleanup "+ + "breached ChannelPoint(%v): %v", + breachInfo.chanPoint, err) + } + + break Loop + } + // If less than four blocks have passed since the // breach confirmed, we'll continue waiting. It was // published with a 2-block fee estimate, so it's not @@ -1097,6 +1638,12 @@ type breachedOutput struct { secondLevelWitnessScript []byte secondLevelTapTweak [32]byte + // resolveReq is a template ResolutionReq populated at breach + // detection time. It is used when an HTLC is taken to the second + // level and we need to re-resolve the contract with the updated + // witness type and the actual second-level spending tx. + resolveReq *lnwallet.ResolutionReq + witnessFunc input.WitnessGenerator resolutionBlob fn.Option[tlv.Blob] @@ -1239,6 +1786,36 @@ type retributionInfo struct { breachHeight uint32 breachedOutputs []breachedOutput + + // justiceTxs holds the metadata of the justice transactions created + // for this breach before a restart, keyed by txid. It is only set + // when the retribution of an aux channel is loaded from the store. + justiceTxs map[chainhash.Hash]*justiceTxCtx +} + +// hasAuxData returns true if any breached output carries aux resolution +// data, which is only ever the case for aux (custom) channels. +func (ret *retributionInfo) hasAuxData() bool { + for i := range ret.breachedOutputs { + bo := &ret.breachedOutputs[i] + if bo.resolveReq != nil || bo.resolutionBlob.IsSome() { + return true + } + } + + return false +} + +// claimsOutpoint returns true if one of the breached outputs currently sits +// at the given outpoint. +func (ret *retributionInfo) claimsOutpoint(op wire.OutPoint) bool { + for i := range ret.breachedOutputs { + if ret.breachedOutputs[i].outpoint == op { + return true + } + } + + return false } // newRetributionInfo constructs a retributionInfo containing all the @@ -1392,9 +1969,10 @@ func newRetributionInfo(chanPoint *wire.OutPoint, ) // For taproot outputs, we also need to hold onto the second - // level tap tweak as well. + // level tap tweak and resolution request template. //nolint:ll htlcOutput.secondLevelTapTweak = breachedHtlc.SecondLevelTapTweak + htlcOutput.resolveReq = breachedHtlc.ResolveReq breachedOutputs = append(breachedOutputs, htlcOutput) } @@ -1472,6 +2050,10 @@ func (b *BreachArbitrator) createJusticeTx( } } + brarLog.Infof("createJusticeTx: %d total inputs (%d commit, "+ + "%d htlc, %d second-level)", len(allInputs), + len(commitInputs), len(htlcInputs), len(secondLevelInputs)) + var ( txs = &justiceTxVariants{} err error @@ -1482,35 +2064,52 @@ func (b *BreachArbitrator) createJusticeTx( if err != nil { return nil, err } + brarLog.Infof("createJusticeTx: spendAll created successfully "+ + "(%d inputs, txid=%v)", len(allInputs), + txs.spendAll.justiceTx.TxHash()) txs.spendCommitOuts, err = b.createSweepTx(commitInputs...) if err != nil { brarLog.Errorf("could not create sweep tx for commitment "+ "outputs: %v", err) + } else if txs.spendCommitOuts != nil { + brarLog.Infof("createJusticeTx: spendCommitOuts created "+ + "successfully (%d inputs)", len(commitInputs)) } txs.spendHTLCs, err = b.createSweepTx(htlcInputs...) if err != nil { brarLog.Errorf("could not create sweep tx for HTLC outputs: %v", err) + } else if txs.spendHTLCs != nil { + brarLog.Infof("createJusticeTx: spendHTLCs created "+ + "successfully (%d inputs)", len(htlcInputs)) } // TODO(roasbeef): only register one of them? secondLevelSweeps := make([]*justiceTxCtx, 0, len(secondLevelInputs)) - for _, input := range secondLevelInputs { + for i, input := range secondLevelInputs { sweepTx, err := b.createSweepTx(input) if err != nil { brarLog.Errorf("could not create sweep tx for "+ - "second-level HTLC output: %v", err) + "second-level HTLC output %d: %v", i, err) continue } + brarLog.Infof("createJusticeTx: individual second-level "+ + "sweep %d created successfully", i) secondLevelSweeps = append(secondLevelSweeps, sweepTx) } txs.spendSecondLevelHTLCs = secondLevelSweeps + brarLog.Infof("createJusticeTx: variants summary: spendAll=%v, "+ + "spendCommitOuts=%v, spendHTLCs=%v, "+ + "spendSecondLevelHTLCs=%d", + txs.spendAll != nil, txs.spendCommitOuts != nil, + txs.spendHTLCs != nil, len(txs.spendSecondLevelHTLCs)) + return txs, nil } @@ -1525,6 +2124,12 @@ type justiceTxCtx struct { fee btcutil.Amount + // hasSecondLevel records whether this concrete justice tx spends any + // second-level revoke inputs. We keep it on the tx context because the + // live breachedOutputs slice may later be rebuilt into a view that no + // longer faithfully reflects the confirmed tx we need to notify about. + hasSecondLevel bool + inputs []input.Input } @@ -1644,19 +2249,56 @@ func (b *BreachArbitrator) sweepSpendableOutputsTxn(txWeight lntypes.WeightUnit, // First, we'll add the extra sweep output if it exists, subtracting the // amount from the sweep amt. + var ( + hasAuxOut bool + auxOutAmt btcutil.Amount + ) if b.cfg.AuxSweeper.IsSome() { extraChangeOut.WhenOk(func(o sweep.SweepOutput) { sweepAmt -= o.Value + auxOutAmt = btcutil.Amount(o.Value) txn.AddTxOut(&o.TxOut) + hasAuxOut = true }) } - // Next, we'll add the output to which our funds will be deposited. - txn.AddTxOut(&wire.TxOut{ - PkScript: pkScript.DeliveryAddress, - Value: sweepAmt, - }) + dustLimit := int64(lnwallet.DustLimitForSize(input.UnknownWitnessSize)) + switch { + // Without an aux output this is the justice transaction of a regular + // channel: we add the output to which our funds will be deposited, + // exactly as we always did. + case !hasAuxOut: + txn.AddTxOut(&wire.TxOut{ + PkScript: pkScript.DeliveryAddress, + Value: sweepAmt, + }) + + // With an aux output, the BTC sweep output is only added if it is + // above the dust limit. + case sweepAmt > dustLimit: + txn.AddTxOut(&wire.TxOut{ + PkScript: pkScript.DeliveryAddress, + Value: sweepAmt, + }) + + // Otherwise we skip the BTC sweep output entirely: for custom (asset) + // channels the real value is carried by the aux output, and whatever + // BTC the inputs hold beyond it goes towards fees. Using the dust + // limit instead of zero prevents the mempool from rejecting the + // transaction. The inputs still have to cover the aux output, or the + // transaction would spend more than it has. + case totalAmt < auxOutAmt: + return nil, fmt.Errorf("inputs of %v cannot fund the aux "+ + "sweep output of %v", totalAmt, auxOutAmt) + + default: + txFee = totalAmt - auxOutAmt + + brarLog.Infof("Dropping BTC sweep output (amount=%d), all "+ + "input BTC (%v) goes to the aux output (%v) and fees "+ + "(%v)", sweepAmt, totalAmt, auxOutAmt, txFee) + } // TODO(roasbeef): add other output change modify sweep amt @@ -1720,7 +2362,12 @@ func (b *BreachArbitrator) sweepSpendableOutputsTxn(txWeight lntypes.WeightUnit, sweepAddr: pkScript, extraTxOut: extraChangeOut.OkToSome(), fee: txFee, - inputs: inputs, + hasSecondLevel: fn.Any(inputs, func(inp input.Input) bool { + wt := inp.WitnessType() + return wt == input.HtlcSecondLevelRevoke || + wt == input.TaprootHtlcSecondLevelRevoke + }), + inputs: inputs, }, nil } @@ -1795,6 +2442,21 @@ func taprootBriefcaseFromRetInfo(retInfo *retributionInfo) *taprootBriefcase { //nolint:ll tapCase.TapTweaks.Val.BreachedSecondLevelHltcTweaks[resID] = secondLevelTweak + + // The aux resolution blob of the HTLC is only known + // at breach detection time, so it has to be stored + // to still be able to sweep the HTLC's aux value + // after a restart. + bo.resolutionBlob.WhenSome(func(blob tlv.Blob) { + blobsOpt := tapCase.HtlcBlobs.ValOpt() + htlcBlobs := blobsOpt.UnwrapOr( + newAuxHtlcBlobs(), + ) + htlcBlobs[resID] = blob + tapCase.HtlcBlobs = tlv.SomeRecordT( + tlv.NewRecordT[tlv.TlvType4](htlcBlobs), + ) + }) } } @@ -1860,6 +2522,12 @@ func applyTaprootRetInfo(tapCase *taprootBriefcase, "tweak for: %v", bo.OutPoint()) } bo.secondLevelTapTweak = tap2 + + tapCase.HtlcBlobs.WhenSomeV(func(blobs htlcAuxBlobs) { + if blob, ok := blobs[resID]; ok { + bo.resolutionBlob = fn.Some(blob) + } + }) } retInfo.breachedOutputs[i] = bo @@ -1901,6 +2569,14 @@ func (rs *RetributionStore) Add(ret *retributionInfo) error { return err } + // For aux channels, store what we need to resolve the HTLCs + // again after a restart. This is a no-op for every other + // channel. + err = putAuxBreachContext(tx, outBuf.Bytes(), ret) + if err != nil { + return err + } + // If this isn't a taproot channel, then we can exit early here // as there's no extra data to write. switch { @@ -1991,6 +2667,10 @@ func (rs *RetributionStore) Remove(chanPoint *wire.OutPoint) error { return err } + if err := deleteAuxBreachState(tx, chanBytes); err != nil { + return err + } + return tapRetBucket.Delete(chanBytes) }, func() {}) } @@ -2037,6 +2717,13 @@ func (rs *RetributionStore) ForAll(cb func(*retributionInfo) error, } } + // Restore the aux state, if any was stored. This + // needs the fully restored sign descriptors, so it + // comes last. + if err := fetchAuxBreachState(tx, k, ret); err != nil { + return err + } + return cb(ret) }) }, reset) diff --git a/contractcourt/breach_arbitrator_aux_test.go b/contractcourt/breach_arbitrator_aux_test.go new file mode 100644 index 00000000000..b4d81cc0eb8 --- /dev/null +++ b/contractcourt/breach_arbitrator_aux_test.go @@ -0,0 +1,1207 @@ +package contractcourt + +import ( + crand "crypto/rand" + "errors" + "testing" + + "github.com/btcsuite/btcd/address/v2" + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chaincfg/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightningnetwork/lnd/chainntnfs" + "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/keychain" + "github.com/lightningnetwork/lnd/lnwallet" + "github.com/lightningnetwork/lnd/lnwallet/chainfee" + "github.com/lightningnetwork/lnd/sweep" + "github.com/lightningnetwork/lnd/tlv" + "github.com/stretchr/testify/require" +) + +// auxBreachTestKeys holds the keys the breached aux HTLC outputs of a test +// are derived from. +type auxBreachTestKeys struct { + revokeBasePub *btcec.PublicKey + commitSecret *btcec.PrivateKey + revokeKey *btcec.PublicKey +} + +// newAuxBreachTestKeys generates a random set of breach test keys. +func newAuxBreachTestKeys(t *testing.T) *auxBreachTestKeys { + t.Helper() + + revokeBasePriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + commitSecret, err := btcec.NewPrivateKey() + require.NoError(t, err) + + return &auxBreachTestKeys{ + revokeBasePub: revokeBasePriv.PubKey(), + commitSecret: commitSecret, + revokeKey: input.DeriveRevocationPubkey( + revokeBasePriv.PubKey(), commitSecret.PubKey(), + ), + } +} + +// secondLevelPkScript returns the pkScript of the second-level output that +// is expected for the given second-level tap tweak. +func (k *auxBreachTestKeys) secondLevelPkScript(t *testing.T, + tapTweak [32]byte) []byte { + + t.Helper() + + outputKey := txscript.ComputeTaprootOutputKey( + k.revokeKey, tapTweak[:], + ) + pkScript, err := input.PayToTaprootScript(outputKey) + require.NoError(t, err) + + return pkScript +} + +// randomTapTweak returns a random second-level tap tweak. +func randomTapTweak(t *testing.T) [32]byte { + t.Helper() + + var tweak [32]byte + _, err := crand.Read(tweak[:]) + require.NoError(t, err) + + return tweak +} + +// randomPkScript returns the pkScript of a random taproot key. +func randomPkScript(t *testing.T) []byte { + t.Helper() + + key, err := btcec.NewPrivateKey() + require.NoError(t, err) + pkScript, err := input.PayToTaprootScript(key.PubKey()) + require.NoError(t, err) + + return pkScript +} + +// htlcOutput returns a breached first-level HTLC output of the given type +// at the given commitment output index. With aux set the output carries a +// resolution request template and a first-level blob, like the HTLC of an +// aux channel does. +func (k *auxBreachTestKeys) htlcOutput(t *testing.T, index uint32, + witnessType input.StandardWitnessType, tapTweak [32]byte, + aux bool) breachedOutput { + + t.Helper() + + bo := breachedOutput{ + amt: 1000, + outpoint: wire.OutPoint{Index: index}, + witnessType: witnessType, + signDesc: input.SignDescriptor{ + KeyDesc: keychain.KeyDescriptor{ + PubKey: k.revokeBasePub, + }, + DoubleTweak: k.commitSecret, + Output: &wire.TxOut{ + Value: 1000, + PkScript: randomPkScript(t), + }, + }, + secondLevelTapTweak: tapTweak, + } + + if aux { + incoming := witnessType == input.TaprootHtlcAcceptedRevoke + bo.resolveReq = &lnwallet.ResolutionReq{ + Type: witnessType, + HtlcID: fn.Some(uint64(index)), + HtlcIncoming: fn.Some(incoming), + KeyRing: &lnwallet.CommitmentKeyRing{}, + } + bo.resolutionBlob = fn.Some(tlv.Blob{0xf1, byte(index)}) + } + + return bo +} + +// secondLevelSpend returns the spend of the breached output at the given +// index by a transaction with the given outputs, whose input at +// spenderInputIndex is the one that took the HTLC to the second level. A +// script path spend carries more than one witness element, so the spend is +// not taken for our own revocation spend. +func secondLevelSpend(index int, spenderInputIndex uint32, + spendingTx *wire.MsgTx) spend { + + for len(spendingTx.TxIn) <= int(spenderInputIndex) { + spendingTx.AddTxIn(&wire.TxIn{ + PreviousOutPoint: wire.OutPoint{ + Index: uint32(len(spendingTx.TxIn)), + }, + }) + } + spendingTx.TxIn[spenderInputIndex].Witness = wire.TxWitness{ + {1}, {2}, {3}, + } + + txHash := spendingTx.TxHash() + + return spend{ + index: index, + detail: &chainntnfs.SpendDetail{ + SpendingTx: spendingTx, + SpenderTxHash: &txHash, + SpenderInputIndex: spenderInputIndex, + SpendingHeight: 500, + }, + } +} + +// auxTestResolver is an AuxContractResolver that records the requests it +// receives and answers them with a canned blob or error. +type auxTestResolver struct { + reqs []lnwallet.ResolutionReq + blob tlv.Blob + err error +} + +// ResolveContract records the request and returns the canned answer. +func (r *auxTestResolver) ResolveContract( + req lnwallet.ResolutionReq) fn.Result[tlv.Blob] { + + r.reqs = append(r.reqs, req) + if r.err != nil { + return fn.Err[tlv.Blob](r.err) + } + + return fn.Ok(r.blob) +} + +// TestFindSecondLevelOutputIndex verifies that findSecondLevelOutputIndex +// correctly identifies the HTLC output in second-level transactions, including +// batched txs with multiple inputs and a wallet change output where input +// indices diverge from output indices, and transactions in which several +// outputs carry the same second-level script. +func TestFindSecondLevelOutputIndex(t *testing.T) { + t.Parallel() + + keys := newAuxBreachTestKeys(t) + tapTweak := randomTapTweak(t) + expectedPkScript := keys.secondLevelPkScript(t, tapTweak) + unrelatedPkScript := randomPkScript(t) + + bo := keys.htlcOutput( + t, 0, input.TaprootHtlcAcceptedRevoke, tapTweak, true, + ) + + txOut := func(pkScript []byte, value int64) *wire.TxOut { + return &wire.TxOut{PkScript: pkScript, Value: value} + } + + tests := []struct { + name string + outputs []*wire.TxOut + spenderInputIndex uint32 + claimed []uint32 + expectedIndex uint32 + expectErr bool + }{{ + // Simple 1-input-1-output second-level tx. + name: "single output matches", + outputs: []*wire.TxOut{txOut(expectedPkScript, 50_000)}, + }, { + // Batched tx: wallet UTXO input adds a change output before + // the HTLC output. + name: "batched tx - HTLC at index 1", + outputs: []*wire.TxOut{ + txOut(unrelatedPkScript, 100_000), + txOut(expectedPkScript, 50_000), + }, + expectedIndex: 1, + }, { + // Batched tx: HTLC output first, change output second, with + // the HTLC spent by the second input. + name: "batched tx - HTLC at index 0", + outputs: []*wire.TxOut{ + txOut(expectedPkScript, 50_000), + txOut(unrelatedPkScript, 100_000), + }, + spenderInputIndex: 1, + }, { + // Batched tx with 3 outputs: HTLC in the middle. + name: "batched tx - HTLC at index 1 of 3", + outputs: []*wire.TxOut{ + txOut(unrelatedPkScript, 100_000), + txOut(expectedPkScript, 50_000), + txOut(unrelatedPkScript, 200_000), + }, + spenderInputIndex: 2, + expectedIndex: 1, + }, { + // Two HTLCs with the same second-level script in one tx that + // pairs inputs with outputs: the output at the index of the + // spending input is the one that belongs to the HTLC. + name: "same script twice - spender index wins", + outputs: []*wire.TxOut{ + txOut(expectedPkScript, 50_000), + txOut(expectedPkScript, 60_000), + }, + spenderInputIndex: 1, + expectedIndex: 1, + }, { + // The output at the spender index was already assigned to + // another breached output, so the next match is taken. + name: "same script twice - claimed output skipped", + outputs: []*wire.TxOut{ + txOut(expectedPkScript, 50_000), + txOut(expectedPkScript, 60_000), + }, + claimed: []uint32{0}, + expectedIndex: 1, + }, { + // Every matching output is taken: nothing is left for this + // HTLC, and it must not be mapped onto one of them a second + // time. + name: "same script twice - all claimed", + outputs: []*wire.TxOut{ + txOut(expectedPkScript, 50_000), + txOut(expectedPkScript, 60_000), + }, + claimed: []uint32{0, 1}, + expectErr: true, + }, { + // No matching output: should error. + name: "no match", + outputs: []*wire.TxOut{txOut(unrelatedPkScript, 50_000)}, + expectErr: true, + }} + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + tx := &wire.MsgTx{TxOut: tc.outputs} + txHash := tx.TxHash() + claimed := func(op wire.OutPoint) bool { + require.Equal(t, txHash, op.Hash) + + for _, idx := range tc.claimed { + if op.Index == idx { + return true + } + } + + return false + } + + idx, err := findSecondLevelOutputIndex( + &bo, tx, tc.spenderInputIndex, claimed, + ) + if tc.expectErr { + require.ErrorIs( + t, err, errSecondLevelOutputNotFound, + ) + + return + } + + require.NoError(t, err) + require.Equal(t, tc.expectedIndex, idx) + }) + } +} + +// TestConvertToSecondLevelRevokeAuxGate asserts which output of the +// second-level transaction a breached HTLC is morphed onto. For an aux +// channel HTLC the output is located by its script, as the transaction may +// carry inputs and outputs that shift the indexes. For any other channel the +// output at the index of the spending input is used, exactly as before, even +// if a script match would point elsewhere. +func TestConvertToSecondLevelRevokeAuxGate(t *testing.T) { + t.Parallel() + + keys := newAuxBreachTestKeys(t) + tapTweak := randomTapTweak(t) + secondLevelScript := keys.secondLevelPkScript(t, tapTweak) + otherScript := randomPkScript(t) + + // The HTLC is spent by input 0, but its second-level output sits at + // index 1. + newSpend := func() spend { + return secondLevelSpend(0, 0, &wire.MsgTx{ + TxOut: []*wire.TxOut{ + {PkScript: otherScript, Value: 700}, + {PkScript: secondLevelScript, Value: 900}, + }, + }) + } + + for _, aux := range []bool{true, false} { + bo := keys.htlcOutput( + t, 0, input.TaprootHtlcAcceptedRevoke, tapTweak, aux, + ) + breachInfo := &retributionInfo{ + breachedOutputs: []breachedOutput{bo}, + } + resolver := &auxTestResolver{blob: tlv.Blob{0x02}} + + s := newSpend() + err := convertToSecondLevelRevoke( + &breachInfo.breachedOutputs[0], breachInfo, s.detail, + fn.Some[lnwallet.AuxContractResolver](resolver), + ) + require.NoError(t, err) + + converted := breachInfo.breachedOutputs[0] + require.Equal( + t, input.TaprootHtlcSecondLevelRevoke, + converted.witnessType, + ) + + wantIndex, wantAmt, wantScript := uint32(0), int64(700), + otherScript + if aux { + wantIndex, wantAmt, wantScript = 1, 900, + secondLevelScript + } + require.Equal(t, wire.OutPoint{ + Hash: s.detail.SpendingTx.TxHash(), + Index: wantIndex, + }, converted.outpoint) + require.EqualValues(t, wantAmt, converted.amt) + require.Equal(t, wantAmt, converted.signDesc.Output.Value) + require.Equal( + t, wantScript, converted.signDesc.Output.PkScript, + ) + + // Only an aux channel HTLC is resolved again. + if !aux { + require.Empty(t, resolver.reqs) + require.True(t, converted.resolutionBlob.IsNone()) + + continue + } + + // The request targets the second-level revocation of the + // same HTLC, direction included, and carries the confirmed + // second-level transaction. + require.Len(t, resolver.reqs, 1) + req := resolver.reqs[0] + require.Equal( + t, input.WitnessType( + input.TaprootHtlcSecondLevelRevoke, + ), req.Type, + ) + require.Equal(t, fn.Some(true), req.HtlcIncoming) + require.Equal(t, fn.Some(uint64(0)), req.HtlcID) + + secondLevel, err := req.SecondLevel.UnwrapOrErr( + errors.New("no second-level info"), + ) + require.NoError(t, err) + require.Equal(t, s.detail.SpendingTx, secondLevel.Tx) + require.EqualValues(t, 500, secondLevel.BlockHeight) + + // The blob resolved for the commitment output is replaced by + // the one resolved for the second-level output. + require.Equal( + t, fn.Some(tlv.Blob{0x02}), converted.resolutionBlob, + ) + + // The template itself is left untouched for later use. + require.Equal( + t, input.WitnessType(input.TaprootHtlcAcceptedRevoke), + bo.resolveReq.Type, + ) + require.True(t, bo.resolveReq.SecondLevel.IsNone()) + } +} + +// TestConvertToSecondLevelRevokeResolveFailure asserts that a failing aux +// resolver does not hold up the conversion of an HTLC that was taken to the +// second level. The output is still morphed, so its BTC value is swept, but +// the blob that was resolved for the commitment output is dropped: carried +// along, it would make every justice transaction that includes the output +// invalid for the aux sweeper and stall the whole breach. +func TestConvertToSecondLevelRevokeResolveFailure(t *testing.T) { + t.Parallel() + + keys := newAuxBreachTestKeys(t) + tapTweak := randomTapTweak(t) + bo := keys.htlcOutput( + t, 0, input.TaprootHtlcOfferedRevoke, tapTweak, true, + ) + breachInfo := &retributionInfo{ + breachedOutputs: []breachedOutput{bo}, + } + require.True(t, bo.resolutionBlob.IsSome()) + + s := secondLevelSpend(0, 0, &wire.MsgTx{ + TxOut: []*wire.TxOut{{ + PkScript: keys.secondLevelPkScript(t, tapTweak), + Value: 900, + }}, + }) + resolver := &auxTestResolver{err: errors.New("cannot resolve")} + + err := convertToSecondLevelRevoke( + &breachInfo.breachedOutputs[0], breachInfo, s.detail, + fn.Some[lnwallet.AuxContractResolver](resolver), + ) + require.NoError(t, err) + require.Len(t, resolver.reqs, 1) + + converted := breachInfo.breachedOutputs[0] + require.Equal( + t, input.TaprootHtlcSecondLevelRevoke, converted.witnessType, + ) + require.EqualValues(t, 900, converted.amt) + require.True(t, converted.resolutionBlob.IsNone()) +} + +// TestUpdateBreachInfoSecondLevelOutputNotFound asserts what happens when +// the second-level output of an aux channel HTLC cannot be located in the +// transaction that spent it. The breached output must be left exactly as it +// was, not half converted, and it is then dropped from the breach without +// its value being reported as claimed: its outpoint is spent, so keeping it +// would have the next spend notification replay the very same spend, and +// counting it would report funds as recovered that were not. +func TestUpdateBreachInfoSecondLevelOutputNotFound(t *testing.T) { + t.Parallel() + + keys := newAuxBreachTestKeys(t) + lost := keys.htlcOutput( + t, 1, input.TaprootHtlcAcceptedRevoke, randomTapTweak(t), true, + ) + keptTweak := randomTapTweak(t) + kept := keys.htlcOutput( + t, 2, input.TaprootHtlcOfferedRevoke, keptTweak, true, + ) + + // The transaction that spends the first HTLC has no output with the + // expected second-level script. + lostSpend := secondLevelSpend(0, 0, &wire.MsgTx{ + TxOut: []*wire.TxOut{{ + PkScript: randomPkScript(t), Value: 900, + }}, + }) + + // Converting it directly fails without touching the output. + breachInfo := &retributionInfo{ + breachedOutputs: []breachedOutput{lost, kept}, + } + resolver := &auxTestResolver{blob: tlv.Blob{0x02}} + auxResolver := fn.Some[lnwallet.AuxContractResolver](resolver) + + err := convertToSecondLevelRevoke( + &breachInfo.breachedOutputs[0], breachInfo, lostSpend.detail, + auxResolver, + ) + require.ErrorIs(t, err, errSecondLevelOutputNotFound) + require.Equal(t, lost, breachInfo.breachedOutputs[0]) + require.Empty(t, resolver.reqs) + + // Applied as a spend, the output is dropped and nothing is counted. + // The other HTLC, spent to the second level properly in the same + // batch, is converted as usual. + keptSpend := secondLevelSpend(1, 0, &wire.MsgTx{ + TxOut: []*wire.TxOut{{ + PkScript: keys.secondLevelPkScript(t, keptTweak), + Value: 800, + }}, + }) + total, revoked := updateBreachInfo( + breachInfo, []spend{lostSpend, keptSpend}, auxResolver, + ) + require.Zero(t, total) + require.Zero(t, revoked) + + require.Len(t, breachInfo.breachedOutputs, 1) + remaining := breachInfo.breachedOutputs[0] + require.Equal( + t, input.TaprootHtlcSecondLevelRevoke, remaining.witnessType, + ) + require.EqualValues(t, 800, remaining.amt) + require.Equal( + t, keptSpend.detail.SpendingTx.TxHash(), + remaining.outpoint.Hash, + ) +} + +// TestUpdateBreachInfoSharedSecondLevelScript asserts that two aux channel +// HTLCs whose second-level outputs share a script, bundled into one +// second-level transaction, are morphed onto two different outputs. Mapping +// both onto the first match would put the same outpoint into the justice +// transaction twice, which makes it invalid and stalls the whole breach. +func TestUpdateBreachInfoSharedSecondLevelScript(t *testing.T) { + t.Parallel() + + keys := newAuxBreachTestKeys(t) + + // The second-level script depends on keys, the CSV delay and the aux + // leaf only, so two HTLCs with the same aux leaf share it. + tapTweak := randomTapTweak(t) + sharedScript := keys.secondLevelPkScript(t, tapTweak) + + breachInfo := &retributionInfo{ + breachedOutputs: []breachedOutput{ + keys.htlcOutput( + t, 1, input.TaprootHtlcAcceptedRevoke, + tapTweak, true, + ), + keys.htlcOutput( + t, 2, input.TaprootHtlcAcceptedRevoke, + tapTweak, true, + ), + }, + } + + // One transaction takes both HTLCs to the second level, the first + // HTLC through its second input and vice versa. + bundle := &wire.MsgTx{ + TxOut: []*wire.TxOut{ + {PkScript: sharedScript, Value: 900}, + {PkScript: sharedScript, Value: 800}, + }, + } + spends := []spend{ + secondLevelSpend(0, 1, bundle), + secondLevelSpend(1, 0, bundle), + } + require.Equal( + t, spends[0].detail.SpendingTx, spends[1].detail.SpendingTx, + ) + + resolver := &auxTestResolver{blob: tlv.Blob{0x02}} + updateBreachInfo( + breachInfo, spends, + fn.Some[lnwallet.AuxContractResolver](resolver), + ) + + require.Len(t, breachInfo.breachedOutputs, 2) + first, second := breachInfo.breachedOutputs[0], + breachInfo.breachedOutputs[1] + + // Each HTLC follows the input that spent it. + bundleHash := bundle.TxHash() + require.Equal( + t, wire.OutPoint{Hash: bundleHash, Index: 1}, first.outpoint, + ) + require.EqualValues(t, 800, first.amt) + require.Equal( + t, wire.OutPoint{Hash: bundleHash, Index: 0}, second.outpoint, + ) + require.EqualValues(t, 900, second.amt) +} + +// mockAuxSweeperWithOutput is a mock AuxSweeper that returns a configurable +// sweep output from DeriveSweepAddr. +type mockAuxSweeperWithOutput struct { + outputValue int64 + pkScript []byte +} + +func (m *mockAuxSweeperWithOutput) DeriveSweepAddr( + _ []input.Input, + _ lnwallet.AddrWithKey) fn.Result[sweep.SweepOutput] { + + return fn.Ok(sweep.SweepOutput{ + TxOut: wire.TxOut{ + PkScript: m.pkScript, + Value: m.outputValue, + }, + }) +} + +func (m *mockAuxSweeperWithOutput) ExtraBudgetForInputs( + _ []input.Input) fn.Result[btcutil.Amount] { + + return fn.Ok(btcutil.Amount(0)) +} + +func (m *mockAuxSweeperWithOutput) NotifyBroadcast( + _ *sweep.BumpRequest, _ *wire.MsgTx, + _ btcutil.Amount, _ map[wire.OutPoint]int, + _ sweep.AuxNotifyOpts) error { + + return nil +} + +// TestSweepSpendableOutputsAuxOutput tests the output construction logic in +// sweepSpendableOutputsTxn. Without an aux output the transaction is built +// exactly as for any regular channel. With one, the BTC sweep output is only +// added above the dust limit, and what the inputs hold beyond the aux output +// is otherwise paid as fees. +func TestSweepSpendableOutputsAuxOutput(t *testing.T) { + t.Parallel() + + privKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + + pkScript, err := input.PayToTaprootScript(privKey.PubKey()) + require.NoError(t, err) + + // Build a P2WKH pkScript for the input (WitnessKeyHash needs + // a valid P2WKH output to sign). + p2wkhAddr := address.Hash160( + privKey.PubKey().SerializeCompressed(), + ) + builder := txscript.NewScriptBuilder() + builder.AddOp(txscript.OP_0) + builder.AddData(p2wkhAddr) + p2wkhScript, err := builder.Script() + require.NoError(t, err) + + makeOutput := func(value int64) breachedOutput { + return breachedOutput{ + amt: btcutil.Amount(value), + outpoint: wire.OutPoint{ + Hash: chainhash.Hash{0x01}, + Index: 0, + }, + witnessType: input.WitnessKeyHash, + signDesc: input.SignDescriptor{ + KeyDesc: keychain.KeyDescriptor{ + PubKey: privKey.PubKey(), + }, + Output: &wire.TxOut{ + PkScript: p2wkhScript, + Value: value, + }, + }, + } + } + + sweepAddr := lnwallet.AddrWithKey{ + DeliveryAddress: pkScript, + } + + signer := input.NewMockSigner( + []*btcec.PrivateKey{privKey}, + &chaincfg.RegressionNetParams, + ) + + // The fee rate is fixed, so the fee follows from the weight alone. + feeRate := chainfee.FeePerKwFloor + makeBrar := func(auxOutValue int64) *BreachArbitrator { + genScript := func() fn.Result[lnwallet.AddrWithKey] { + return fn.Ok(sweepAddr) + } + + auxSweeper := fn.None[sweep.AuxSweeper]() + if auxOutValue > 0 { + auxSweeper = fn.Some[sweep.AuxSweeper]( + &mockAuxSweeperWithOutput{ + outputValue: auxOutValue, + pkScript: pkScript, + }, + ) + } + + return &BreachArbitrator{ + cfg: &BreachConfig{ + Signer: signer, + GenSweepScript: genScript, + Estimator: chainfee.NewStaticEstimator( + feeRate, 0, + ), + AuxSweeper: auxSweeper, + }, + } + } + + const txWeight = 400 + estimatedFee := int64(feeRate.FeeForWeight(txWeight)) + dustLimit := int64( + lnwallet.DustLimitForSize(input.UnknownWitnessSize), + ) + + testCases := []struct { + name string + inputValue int64 + auxOutValue int64 + wantOutputs []int64 + wantFee int64 + wantErr string + }{{ + name: "no aux output", + inputValue: 1_000_000, + wantOutputs: []int64{1_000_000 - estimatedFee}, + wantFee: estimatedFee, + }, { + // A regular channel gets its sweep output no matter how + // small it is, exactly as before. + name: "no aux output, sweep output below dust", + inputValue: estimatedFee + dustLimit - 1, + wantOutputs: []int64{dustLimit - 1}, + wantFee: estimatedFee, + }, { + // And an input that cannot pay the fee still fails on the + // negative output. + name: "no aux output, negative sweep output", + inputValue: estimatedFee - 1, + wantErr: "negative", + }, { + name: "aux output and sweep output", + inputValue: 1_000_000, + auxOutValue: 10_000, + wantOutputs: []int64{ + 10_000, 1_000_000 - 10_000 - estimatedFee, + }, + wantFee: estimatedFee, + }, { + // The sweep output would sit exactly at the dust limit: it + // is dropped and its value goes to fees. + name: "aux output, sweep output at dust limit", + inputValue: 400 + estimatedFee + dustLimit, + auxOutValue: 400, + wantOutputs: []int64{400}, + wantFee: estimatedFee + dustLimit, + }, { + // The inputs cannot even pay the estimated fee on top of the + // aux output: what is left beyond the aux output is the fee. + name: "aux output, fee below the estimate", + inputValue: 630, + auxOutValue: 400, + wantOutputs: []int64{400}, + wantFee: 230, + }, { + // The inputs cannot fund the aux output at all: the + // transaction would spend more than it has. + name: "aux output larger than the inputs", + inputValue: 354, + auxOutValue: 1_000, + wantErr: "cannot fund the aux sweep output", + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + brar := makeBrar(tc.auxOutValue) + bo := makeOutput(tc.inputValue) + + result, err := brar.sweepSpendableOutputsTxn( + txWeight, &bo, + ) + if tc.wantErr != "" { + require.ErrorContains(t, err, tc.wantErr) + + return + } + require.NoError(t, err) + + var ( + outputs []int64 + totalOut int64 + ) + for _, txOut := range result.justiceTx.TxOut { + outputs = append(outputs, txOut.Value) + totalOut += txOut.Value + } + require.Equal(t, tc.wantOutputs, outputs) + + // The reported fee is what the transaction really + // pays. + require.EqualValues(t, tc.wantFee, result.fee) + require.Equal(t, tc.inputValue-totalOut, tc.wantFee) + }) + } +} + +// mockAuxSweeperNotify is a mock implementation of sweep.AuxSweeper that tracks +// calls to NotifyBroadcast for testing purposes. +type mockAuxSweeperNotify struct { + notifyCalls []notifyCall + notifyErr error +} + +// notifyCall records the parameters of a NotifyBroadcast call. +type notifyCall struct { + req *sweep.BumpRequest + tx *wire.MsgTx + fee btcutil.Amount + opts sweep.AuxNotifyOpts +} + +// DeriveSweepAddr implements sweep.AuxSweeper. +func (m *mockAuxSweeperNotify) DeriveSweepAddr(_ []input.Input, + _ lnwallet.AddrWithKey) fn.Result[sweep.SweepOutput] { + + return fn.Ok(sweep.SweepOutput{}) +} + +// ExtraBudgetForInputs implements sweep.AuxSweeper. +func (m *mockAuxSweeperNotify) ExtraBudgetForInputs( + _ []input.Input) fn.Result[btcutil.Amount] { + + return fn.Ok(btcutil.Amount(0)) +} + +// NotifyBroadcast implements sweep.AuxSweeper and records the call. +func (m *mockAuxSweeperNotify) NotifyBroadcast(req *sweep.BumpRequest, + tx *wire.MsgTx, fee btcutil.Amount, + _ map[wire.OutPoint]int, opts sweep.AuxNotifyOpts) error { + + m.notifyCalls = append(m.notifyCalls, notifyCall{ + req: req, + tx: tx, + fee: fee, + opts: opts, + }) + + return m.notifyErr +} + +// justiceTrackerHarness bundles a justice tx tracker with a breach arbiter +// whose aux sweeper records the notifications it receives. +type justiceTrackerHarness struct { + t *testing.T + + brar *BreachArbitrator + sweeper *mockAuxSweeperNotify + tracker *justiceTxTracker +} + +// newJusticeTrackerHarness creates a harness whose tracker is seeded with +// the given justice txs, as if they had been recorded before a restart. +func newJusticeTrackerHarness(t *testing.T, + recorded map[chainhash.Hash]*justiceTxCtx) *justiceTrackerHarness { + + t.Helper() + + sweeper := &mockAuxSweeperNotify{} + + return &justiceTrackerHarness{ + t: t, + brar: &BreachArbitrator{ + cfg: &BreachConfig{ + AuxSweeper: fn.Some[sweep.AuxSweeper](sweeper), + }, + }, + sweeper: sweeper, + tracker: newJusticeTxTracker(recorded), + } +} + +// spendsOf processes the spend of the breached outputs at the given indexes +// by the given transaction the way the retribution loop does: the confirmed +// justice txs are collected first, then the outputs the transaction spent +// are removed, then the aux sweeper is notified. +func (h *justiceTrackerHarness) spendsOf(breachInfo *retributionInfo, + tx *wire.MsgTx, indexes ...int) { + + h.t.Helper() + + txHash := tx.TxHash() + spends := make([]spend, 0, len(indexes)) + for _, index := range indexes { + spends = append(spends, spend{ + index: index, + detail: &chainntnfs.SpendDetail{ + SpendingTx: tx, + SpenderTxHash: &txHash, + SpendingHeight: 700, + }, + }) + } + + h.tracker.collect(spends, breachInfo.breachedOutputs) + + // Drop the spent outputs, like updateBreachInfo does for outputs + // that reached their terminal state. + spent := make(map[int]struct{}, len(indexes)) + for _, index := range indexes { + spent[index] = struct{}{} + } + var remaining []breachedOutput + for i := range breachInfo.breachedOutputs { + if _, ok := spent[i]; !ok { + remaining = append( + remaining, breachInfo.breachedOutputs[i], + ) + } + } + breachInfo.breachedOutputs = remaining + + h.brar.notifyConfirmedJusticeTxs(h.tracker) +} + +// newJusticeTx returns a justice tx spending the given breached outputs, +// along with its context. +func newJusticeTx(fee btcutil.Amount, + outputs ...breachedOutput) *justiceTxCtx { + + tx := wire.NewMsgTx(2) + for i := range outputs { + tx.AddTxIn(&wire.TxIn{ + PreviousOutPoint: outputs[i].outpoint, + }) + } + tx.AddTxOut(&wire.TxOut{Value: int64(fee)}) + + return &justiceTxCtx{ + justiceTx: tx, + fee: fee, + sweepAddr: lnwallet.AddrWithKey{ + DeliveryAddress: []byte{0x51, byte(fee)}, + }, + } +} + +// commitOutput returns a breached commitment output at the given index. +func commitOutput(index uint32) breachedOutput { + return breachedOutput{ + amt: 5000, + outpoint: wire.OutPoint{Index: index}, + witnessType: input.TaprootCommitmentRevoke, + resolutionBlob: fn.Some(tlv.Blob{0xc0, byte(index)}), + } +} + +// TestJusticeTxTrackerNotifiesOnce asserts that the aux sweeper is told +// about a confirmed justice tx exactly once and with all of its inputs, even +// though the spends of its inputs are reported one at a time: each breached +// output has its own spend subscription, and the retribution loop moves on +// as soon as the first one fires. +func TestJusticeTxTrackerNotifiesOnce(t *testing.T) { + t.Parallel() + + breachInfo := &retributionInfo{ + breachedOutputs: []breachedOutput{ + commitOutput(0), commitOutput(1), commitOutput(2), + }, + } + justice := newJusticeTx(1000, breachInfo.breachedOutputs...) + variants := &justiceTxVariants{spendAll: justice} + + h := newJusticeTrackerHarness(t, nil) + added := h.tracker.record(variants) + require.Len(t, added, 1) + + // Recording the same variants again adds nothing. + require.Empty(t, h.tracker.record(variants)) + + // The spend of the first input is reported alone. All three outputs + // are still part of the breach, so the notification is complete. + h.spendsOf(breachInfo, justice.justiceTx, 0) + require.Len(t, h.sweeper.notifyCalls, 1) + require.False(t, h.tracker.hasPending()) + + call := h.sweeper.notifyCalls[0] + require.Equal(t, justice.justiceTx, call.tx) + require.EqualValues(t, 1000, call.fee) + require.Equal(t, justice.sweepAddr, call.req.DeliveryAddress) + require.Len(t, call.req.Inputs, 3) + for i, inp := range call.req.Inputs { + wantOp := wire.OutPoint{Index: uint32(i)} + require.Equal(t, wantOp, inp.OutPoint()) + require.Equal( + t, fn.Some(tlv.Blob{0xc0, byte(i)}), + inp.ResolutionBlob(), + ) + } + + // The transaction is confirmed: the aux sweeper must not broadcast + // it, and it is told where to look for it. + require.True(t, call.opts.SkipBroadcast) + require.EqualValues(t, 700, call.opts.ConfirmHeight) + require.False(t, call.opts.LookupInputProofs) + + // The spends of the other two inputs follow in later batches. They + // must not trigger a second, partial notification. + h.spendsOf(breachInfo, justice.justiceTx, 0) + h.spendsOf(breachInfo, justice.justiceTx, 0) + require.Empty(t, breachInfo.breachedOutputs) + require.Len(t, h.sweeper.notifyCalls, 1) +} + +// TestJusticeTxTrackerIgnoresForeignSpends asserts that a spend by a +// transaction that is not one of our justice txs, such as the remote party +// taking an HTLC to the second level, is never reported to the aux sweeper. +func TestJusticeTxTrackerIgnoresForeignSpends(t *testing.T) { + t.Parallel() + + breachInfo := &retributionInfo{ + breachedOutputs: []breachedOutput{ + commitOutput(0), commitOutput(1), + }, + } + justice := newJusticeTx(1000, breachInfo.breachedOutputs...) + + h := newJusticeTrackerHarness(t, nil) + h.tracker.record(&justiceTxVariants{spendAll: justice}) + + foreign := newJusticeTx(77, breachInfo.breachedOutputs[1]) + h.spendsOf(breachInfo, foreign.justiceTx, 1) + + require.Empty(t, h.sweeper.notifyCalls) + require.False(t, h.tracker.hasPending()) +} + +// TestJusticeTxTrackerRetriesFailedNotify asserts that a notification the +// aux sweeper fails to take is not lost. The confirmed justice tx stays +// pending, which keeps the breach from being cleaned up, and the +// notification is retried with the same inputs until it goes through. +func TestJusticeTxTrackerRetriesFailedNotify(t *testing.T) { + t.Parallel() + + breachInfo := &retributionInfo{ + breachedOutputs: []breachedOutput{ + commitOutput(0), commitOutput(1), + }, + } + justice := newJusticeTx(1000, breachInfo.breachedOutputs...) + + h := newJusticeTrackerHarness(t, nil) + h.tracker.record(&justiceTxVariants{spendAll: justice}) + + // The aux sweeper is unable to take the notification. + h.sweeper.notifyErr = errors.New("aux sweeper unavailable") + h.spendsOf(breachInfo, justice.justiceTx, 0, 1) + require.Empty(t, breachInfo.breachedOutputs) + require.Len(t, h.sweeper.notifyCalls, 1) + require.True(t, h.tracker.hasPending()) + + // It is retried, as the retribution loop does on every block, and + // still fails. + h.brar.notifyConfirmedJusticeTxs(h.tracker) + require.Len(t, h.sweeper.notifyCalls, 2) + require.True(t, h.tracker.hasPending()) + + // Once the aux sweeper recovers, the notification goes through with + // the outputs the transaction spent, although they have long been + // removed from the breach. + h.sweeper.notifyErr = nil + h.brar.notifyConfirmedJusticeTxs(h.tracker) + require.Len(t, h.sweeper.notifyCalls, 3) + require.Len(t, h.sweeper.notifyCalls[2].req.Inputs, 2) + require.False(t, h.tracker.hasPending()) + + // And it is not repeated after that. + h.brar.notifyConfirmedJusticeTxs(h.tracker) + require.Len(t, h.sweeper.notifyCalls, 3) +} + +// TestJusticeTxTrackerAfterRestart asserts that a justice tx that was +// created before a restart is still recognized when it confirms afterwards. +// After a restart the spends are replayed from the breach on, and the justice +// txs that are built then differ from the ones that were broadcast before +// (new sweep address, new fee), so only the recorded history can match the +// confirmed transaction. +// +// The replay also reports the confirmed justice tx through its commitment +// input before the HTLC it spent on the second level has been morphed back +// into that second-level output. The aux sweeper must only be notified once +// both inputs are known, with both of them. +func TestJusticeTxTrackerAfterRestart(t *testing.T) { + t.Parallel() + + keys := newAuxBreachTestKeys(t) + tapTweak := randomTapTweak(t) + + // Before the restart: the HTLC was taken to the second level, and a + // justice tx spending the commitment output and the second-level + // output was broadcast. + htlcSpend := secondLevelSpend(0, 0, &wire.MsgTx{ + TxOut: []*wire.TxOut{{ + PkScript: keys.secondLevelPkScript(t, tapTweak), + Value: 900, + }}, + }) + secondLevelOp := wire.OutPoint{ + Hash: htlcSpend.detail.SpendingTx.TxHash(), + } + + commit := commitOutput(0) + justice := newJusticeTx(1000, commit, breachedOutput{ + outpoint: secondLevelOp, + }) + justice.hasSecondLevel = true + + // Only the metadata survives the restart, keyed by txid. + recorded := newJusticeTxTracker(nil).record( + &justiceTxVariants{spendAll: justice}, + ) + require.Len(t, recorded, 1) + for _, jtx := range recorded { + require.Nil(t, jtx.justiceTx) + require.Nil(t, jtx.inputs) + } + + // After the restart the breach starts over with the outputs as they + // were on the commitment. + breachInfo := &retributionInfo{ + breachedOutputs: []breachedOutput{ + commit, + keys.htlcOutput( + t, 1, input.TaprootHtlcAcceptedRevoke, + tapTweak, true, + ), + }, + } + h := newJusticeTrackerHarness(t, recorded) + + // The spend of the commitment output by the justice tx is replayed + // first. The HTLC still sits on the commitment, so one input of the + // justice tx is unknown and nothing is reported yet. + h.spendsOf(breachInfo, justice.justiceTx, 0) + require.Empty(t, h.sweeper.notifyCalls) + require.True(t, h.tracker.hasPending()) + + // Then the HTLC's spend to the second level is replayed, which + // morphs it onto the second-level output. + resolver := &auxTestResolver{blob: tlv.Blob{0x02}} + updateBreachInfo( + breachInfo, []spend{htlcSpend}, + fn.Some[lnwallet.AuxContractResolver](resolver), + ) + require.Len(t, breachInfo.breachedOutputs, 1) + require.Equal( + t, secondLevelOp, breachInfo.breachedOutputs[0].outpoint, + ) + + // Finally the spend of the second-level output by the justice tx is + // replayed. Now the notification is complete. + h.spendsOf(breachInfo, justice.justiceTx, 0) + require.Len(t, h.sweeper.notifyCalls, 1) + require.False(t, h.tracker.hasPending()) + + call := h.sweeper.notifyCalls[0] + require.Equal(t, justice.sweepAddr, call.req.DeliveryAddress) + require.EqualValues(t, 1000, call.fee) + require.Len(t, call.req.Inputs, 2) + require.Equal(t, commit.outpoint, call.req.Inputs[0].OutPoint()) + require.Equal(t, secondLevelOp, call.req.Inputs[1].OutPoint()) + + // The second-level input carries the blob that was resolved for it + // after the restart, and its proof has to be looked up. + require.Equal( + t, fn.Some(tlv.Blob{0x02}), + call.req.Inputs[1].ResolutionBlob(), + ) + require.True(t, call.opts.LookupInputProofs) +} + +// TestJusticeTxTrackerNoAuxSweeper asserts that confirmed justice txs are +// simply dropped from the pending set when no aux sweeper is configured, so +// they can never hold up the cleanup of a breach. +func TestJusticeTxTrackerNoAuxSweeper(t *testing.T) { + t.Parallel() + + breachInfo := &retributionInfo{ + breachedOutputs: []breachedOutput{commitOutput(0)}, + } + justice := newJusticeTx(1000, breachInfo.breachedOutputs...) + + h := newJusticeTrackerHarness(t, nil) + h.brar.cfg.AuxSweeper = fn.None[sweep.AuxSweeper]() + h.tracker.record(&justiceTxVariants{spendAll: justice}) + + h.spendsOf(breachInfo, justice.justiceTx, 0) + require.False(t, h.tracker.hasPending()) +} diff --git a/contractcourt/breach_arbitrator_test.go b/contractcourt/breach_arbitrator_test.go index ad917a531f0..a4d5f0306f6 100644 --- a/contractcourt/breach_arbitrator_test.go +++ b/contractcourt/breach_arbitrator_test.go @@ -424,6 +424,15 @@ func (frs *failingRetributionStore) ForAll(cb func(*retributionInfo) error, return frs.rs.ForAll(cb, reset) } +func (frs *failingRetributionStore) RecordJusticeTxs(chanPoint *wire.OutPoint, + justiceTxs map[chainhash.Hash]*justiceTxCtx) error { + + frs.mu.Lock() + defer frs.mu.Unlock() + + return frs.rs.RecordJusticeTxs(chanPoint, justiceTxs) +} + // Parse the pubkeys in the breached outputs. func initBreachedOutputs() error { for i := range breachedOutputs { @@ -594,6 +603,27 @@ func (rs *mockRetributionStore) ForAll(cb func(*retributionInfo) error, return nil } +func (rs *mockRetributionStore) RecordJusticeTxs(chanPoint *wire.OutPoint, + justiceTxs map[chainhash.Hash]*justiceTxCtx) error { + + rs.mu.Lock() + defer rs.mu.Unlock() + + retInfo, ok := rs.state[*chanPoint] + if !ok { + return errors.New("unknown retribution") + } + + if retInfo.justiceTxs == nil { + retInfo.justiceTxs = make(map[chainhash.Hash]*justiceTxCtx) + } + for txid, jtx := range justiceTxs { + retInfo.justiceTxs[txid] = jtx + } + + return nil +} + var retributionStoreTestSuite = []struct { name string test func(FailingRetributionStore, *testing.T) @@ -2634,6 +2664,118 @@ func TestTaprootBriefcaseRoundTripFinalWitnessTypes(t *testing.T) { ) } +// TestUpdateBreachInfoKeepsSecondLevelTweakOnCompaction verifies that an +// HTLC output morphed to the second level keeps signing with its own tap +// tweak after updateBreachInfo compacts the breached outputs slice. The sign +// descriptor must not alias the array embedded in the breached output, as the +// struct values shift once an earlier output is removed. +func TestUpdateBreachInfoKeepsSecondLevelTweakOnCompaction(t *testing.T) { + t.Parallel() + + revokeBasePriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + commitSecret, err := btcec.NewPrivateKey() + require.NoError(t, err) + + taprootPkScript, err := input.PayToTaprootScript( + revokeBasePriv.PubKey(), + ) + require.NoError(t, err) + + newHtlcOutput := func(index uint32) breachedOutput { + var tweak [32]byte + _, err := crand.Read(tweak[:]) + require.NoError(t, err) + + return breachedOutput{ + amt: 1000, + outpoint: wire.OutPoint{Index: index}, + witnessType: input.TaprootHtlcAcceptedRevoke, + signDesc: input.SignDescriptor{ + KeyDesc: keychain.KeyDescriptor{ + PubKey: revokeBasePriv.PubKey(), + }, + DoubleTweak: commitSecret, + Output: &wire.TxOut{ + Value: 1000, + PkScript: taprootPkScript, + }, + }, + secondLevelTapTweak: tweak, + } + } + + breachInfo := &retributionInfo{ + breachedOutputs: []breachedOutput{ + { + amt: 5000, + outpoint: wire.OutPoint{Index: 0}, + witnessType: input.TaprootCommitmentRevoke, + signDesc: input.SignDescriptor{ + Output: &wire.TxOut{ + PkScript: taprootPkScript, + }, + }, + }, + newHtlcOutput(1), + newHtlcOutput(2), + }, + } + + // The remote party takes both HTLC outputs to the second level. A + // script path spend carries more than one witness element, so it is + // not our own revocation spend and the outputs are morphed. + secondLevelSpend := func(index int) spend { + return spend{ + index: index, + detail: &chainntnfs.SpendDetail{ + SpendingTx: &wire.MsgTx{ + TxIn: []*wire.TxIn{{ + Witness: wire.TxWitness{ + {1}, {2}, {3}, + }, + }}, + TxOut: []*wire.TxOut{{ + Value: 900, + PkScript: taprootPkScript, + }}, + }, + SpenderInputIndex: 0, + }, + } + } + updateBreachInfo( + breachInfo, []spend{secondLevelSpend(1), secondLevelSpend(2)}, + fn.None[lnwallet.AuxContractResolver](), + ) + require.Len(t, breachInfo.breachedOutputs, 3) + + // Our justice tx then sweeps the commitment output, which is removed + // from the breached outputs and shifts the morphed outputs down by one + // slot. + updateBreachInfo(breachInfo, []spend{{ + index: 0, + detail: &chainntnfs.SpendDetail{ + SpendingTx: &wire.MsgTx{ + TxIn: []*wire.TxIn{{ + Witness: wire.TxWitness{{1}}, + }}, + }, + SpenderInputIndex: 0, + }, + }}, fn.None[lnwallet.AuxContractResolver]()) + require.Len(t, breachInfo.breachedOutputs, 2) + + for _, bo := range breachInfo.breachedOutputs { + require.Equal( + t, input.TaprootHtlcSecondLevelRevoke, bo.witnessType, + ) + require.Equal( + t, bo.secondLevelTapTweak[:], bo.signDesc.TapTweak, + ) + } +} + // TestUpdateBreachInfoCountsFinalTaprootRevokedFunds verifies that final // taproot revoked commitment outputs are included in the revoked-funds tally. func TestUpdateBreachInfoCountsFinalTaprootRevokedFunds(t *testing.T) { @@ -2659,7 +2801,7 @@ func TestUpdateBreachInfoCountsFinalTaprootRevokedFunds(t *testing.T) { SpendingTx: &wire.MsgTx{TxIn: []*wire.TxIn{{}}}, SpenderInputIndex: 0, }, - }}) + }}, fn.None[lnwallet.AuxContractResolver]()) // Assert: The amount contributes to both the total and revoked-funds // tallies and is removed from the remaining breach set. diff --git a/contractcourt/breach_aux_state.go b/contractcourt/breach_aux_state.go new file mode 100644 index 00000000000..872744e317c --- /dev/null +++ b/contractcourt/breach_aux_state.go @@ -0,0 +1,766 @@ +package contractcourt + +import ( + "bytes" + "errors" + "fmt" + "io" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightningnetwork/lnd/channeldb" + "github.com/lightningnetwork/lnd/fn/v2" + graphdb "github.com/lightningnetwork/lnd/graph/db" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/keychain" + "github.com/lightningnetwork/lnd/kvdb" + "github.com/lightningnetwork/lnd/lnwallet" + "github.com/lightningnetwork/lnd/lnwire" + "github.com/lightningnetwork/lnd/sweep" + "github.com/lightningnetwork/lnd/tlv" +) + +var ( + // auxRetributionBucket stores the aux (custom channel) state of a + // retribution, keyed by channel point. It holds what the breach + // arbiter cannot recover from anywhere else after a restart: the + // request template it needs to resolve an HTLC that was taken to the + // second level, and the justice transactions it has created so far, + // whose confirmation the aux sweeper has to be told about. The bucket + // is only ever written for channels that carry aux resolution data, + // so retributions of regular channels are stored exactly as before. + auxRetributionBucket = []byte("aux-retribution") + + // auxBreachContextKey is the key, inside a channel's aux retribution + // bucket, of the encoded auxBreachContext. + auxBreachContextKey = []byte("context") + + // auxBreachJusticeBucket is the sub-bucket, inside a channel's aux + // retribution bucket, that maps the txid of every justice transaction + // created for the channel to its encoded metadata. + auxBreachJusticeBucket = []byte("justice-txs") +) + +// auxBreachStateVersion is the encoding version of the aux retribution +// records. +const auxBreachStateVersion uint8 = 0 + +// auxBreachContext is the part of the aux resolution request of a breached +// channel that all of its HTLCs share, together with the per-HTLC remainder. +// Storing the shared part once keeps the record small: it includes the breach +// transaction and the commitment blob, which grow with the number of HTLCs. +type auxBreachContext struct { + chanType channeldb.ChannelType + shortChanID lnwire.ShortChannelID + initiator bool + fundingBlob fn.Option[tlv.Blob] + commitBlob fn.Option[tlv.Blob] + commitTx *wire.MsgTx + commitFee btcutil.Amount + csvDelay uint32 + keyRing lnwallet.CommitmentKeyRing + + // htlcs holds the HTLC specific part of the request, keyed by the + // HTLC's outpoint on the breached commitment. + htlcs map[wire.OutPoint]auxBreachHtlc +} + +// auxBreachHtlc is the HTLC specific part of an aux resolution request. +type auxBreachHtlc struct { + htlcID fn.Option[input.HtlcIndex] + incoming fn.Option[bool] + payHash fn.Option[[32]byte] + cltvDelay fn.Option[uint32] + + // auxSig is the remote party's revocation aux sig for the HTLC, empty + // if the state was revoked without one. + auxSig []byte + + // auxSigKeyDesc and auxSigTweak identify our key the aux sig is + // paired with. + auxSigKeyDesc keychain.KeyDescriptor + auxSigTweak []byte +} + +// auxBreachContextFromRetInfo extracts the aux resolution context from the +// request templates of a retribution. It returns nil if no breached output +// carries a template, which is the case for every regular channel. +func auxBreachContextFromRetInfo(ret *retributionInfo) *auxBreachContext { + var ctx *auxBreachContext + for i := range ret.breachedOutputs { + bo := &ret.breachedOutputs[i] + req := bo.resolveReq + if req == nil || req.KeyRing == nil { + continue + } + + if ctx == nil { + ctx = &auxBreachContext{ + chanType: req.ChanType, + shortChanID: req.ShortChanID, + initiator: req.Initiator, + fundingBlob: req.FundingBlob, + commitBlob: req.CommitBlob, + commitTx: req.CommitTx, + commitFee: req.CommitFee, + csvDelay: req.CsvDelay, + keyRing: *req.KeyRing, + htlcs: make( + map[wire.OutPoint]auxBreachHtlc, + ), + } + } + + htlc := auxBreachHtlc{ + htlcID: req.HtlcID, + incoming: req.HtlcIncoming, + payHash: req.PayHash, + cltvDelay: req.CltvDelay, + } + req.AuxSigDesc.WhenSome(func(desc lnwallet.AuxSigDesc) { + signDesc := desc.SignDetails.SignDesc + + htlc.auxSig = desc.AuxSig + htlc.auxSigKeyDesc = signDesc.KeyDesc + htlc.auxSigTweak = signDesc.SingleTweak + }) + + ctx.htlcs[bo.outpoint] = htlc + } + + return ctx +} + +// apply restores the aux resolution request templates of the breached HTLC +// outputs of a retribution that was just loaded from disk. It must run +// before any output is morphed, while each output still sits at its outpoint +// on the breached commitment. +func (c *auxBreachContext) apply(ret *retributionInfo) { + for i := range ret.breachedOutputs { + bo := &ret.breachedOutputs[i] + + htlc, ok := c.htlcs[bo.outpoint] + if !ok { + continue + } + + // The sign descriptor of the request is the one of the + // breached output. The store doesn't persist the sign method, + // which for the key spend of a taproot HTLC revocation is + // always the same. + signDesc := bo.signDesc + signDesc.SignMethod = input.TaprootKeySpendSignMethod + + keyRing := c.keyRing + req := &lnwallet.ResolutionReq{ + ChanPoint: ret.chanPoint, + ChanType: c.chanType, + ShortChanID: c.shortChanID, + Initiator: c.initiator, + CommitBlob: c.commitBlob, + FundingBlob: c.fundingBlob, + HtlcID: htlc.htlcID, + HtlcIncoming: htlc.incoming, + HtlcAmt: bo.amt, + Type: bo.witnessType, + CloseType: lnwallet.Breach, + CommitTx: c.commitTx, + CommitTxBlockHeight: ret.breachHeight, + CommitFee: c.commitFee, + SignDesc: signDesc, + KeyRing: &keyRing, + CsvDelay: c.csvDelay, + CltvDelay: htlc.cltvDelay, + PayHash: htlc.payHash, + } + + if len(htlc.auxSig) > 0 { + //nolint:ll + req.AuxSigDesc = fn.Some(lnwallet.AuxSigDesc{ + AuxSig: htlc.auxSig, + SignDetails: input.SignDetails{ + SignDesc: input.SignDescriptor{ + KeyDesc: htlc.auxSigKeyDesc, + SingleTweak: htlc.auxSigTweak, + SignMethod: input.TaprootScriptSpendSignMethod, + }, + }, + }) + } + + bo.resolveReq = req + } +} + +// writeOptBlob writes an optional blob as a presence flag followed by the +// blob. +func writeOptBlob(w io.Writer, blob fn.Option[tlv.Blob]) error { + err := channeldb.WriteElement(w, blob.IsSome()) + if err != nil { + return err + } + + return fn.MapOptionZ(blob, func(b tlv.Blob) error { + return wire.WriteVarBytes(w, 0, b) + }) +} + +// readOptBlob reads an optional blob written by writeOptBlob. +func readOptBlob(r io.Reader) (fn.Option[tlv.Blob], error) { + none := fn.None[tlv.Blob]() + + var isSome bool + if err := channeldb.ReadElement(r, &isSome); err != nil { + return none, err + } + if !isSome { + return none, nil + } + + blob, err := wire.ReadVarBytes(r, 0, wire.MaxMessagePayload, "blob") + if err != nil { + return none, err + } + + return fn.Some[tlv.Blob](blob), nil +} + +// writeOptKeyDesc writes an optional key descriptor as a presence flag +// followed by the descriptor. +func writeOptKeyDesc(w io.Writer, + keyDesc fn.Option[keychain.KeyDescriptor]) error { + + err := channeldb.WriteElement(w, keyDesc.IsSome()) + if err != nil { + return err + } + + return fn.MapOptionZ(keyDesc, func(k keychain.KeyDescriptor) error { + return writeKeyDesc(w, k) + }) +} + +// readOptKeyDesc reads an optional key descriptor written by +// writeOptKeyDesc. +func readOptKeyDesc(r io.Reader) (fn.Option[keychain.KeyDescriptor], error) { + none := fn.None[keychain.KeyDescriptor]() + + var isSome bool + if err := channeldb.ReadElement(r, &isSome); err != nil { + return none, err + } + if !isSome { + return none, nil + } + + keyDesc, err := readKeyDesc(r) + if err != nil { + return none, err + } + + return fn.Some(keyDesc), nil +} + +// writeKeyDesc writes a key descriptor whose public key may be unset. +func writeKeyDesc(w io.Writer, keyDesc keychain.KeyDescriptor) error { + err := channeldb.WriteElements( + w, uint32(keyDesc.Family), keyDesc.Index, + ) + if err != nil { + return err + } + + return writeOptPubKey(w, keyDesc.PubKey) +} + +// readKeyDesc reads a key descriptor written by writeKeyDesc. +func readKeyDesc(r io.Reader) (keychain.KeyDescriptor, error) { + var ( + keyDesc keychain.KeyDescriptor + family uint32 + ) + err := channeldb.ReadElements(r, &family, &keyDesc.Index) + if err != nil { + return keyDesc, err + } + keyDesc.Family = keychain.KeyFamily(family) + + keyDesc.PubKey, err = readOptPubKey(r) + + return keyDesc, err +} + +// keyRingKeys returns the public keys of the context's key ring in the order +// they are encoded in. +func (c *auxBreachContext) keyRingKeys() []**btcec.PublicKey { + return []**btcec.PublicKey{ + &c.keyRing.CommitPoint, &c.keyRing.LocalHtlcKey, + &c.keyRing.RemoteHtlcKey, &c.keyRing.ToLocalKey, + &c.keyRing.ToRemoteKey, &c.keyRing.RevocationKey, + } +} + +// writeOptPubKey writes a public key that may be unset as a presence flag +// followed by the key. +func writeOptPubKey(w io.Writer, key *btcec.PublicKey) error { + err := channeldb.WriteElement(w, key != nil) + if err != nil || key == nil { + return err + } + + return channeldb.WriteElement(w, key) +} + +// readOptPubKey reads a public key written by writeOptPubKey. +func readOptPubKey(r io.Reader) (*btcec.PublicKey, error) { + var hasKey bool + if err := channeldb.ReadElement(r, &hasKey); err != nil { + return nil, err + } + if !hasKey { + return nil, nil + } + + var key *btcec.PublicKey + err := channeldb.ReadElement(r, &key) + + return key, err +} + +// encode serializes the aux breach context. +func (c *auxBreachContext) encode(w io.Writer) error { + err := channeldb.WriteElements( + w, auxBreachStateVersion, c.chanType, c.shortChanID, + c.initiator, c.commitFee, c.csvDelay, + ) + if err != nil { + return err + } + + if err := writeOptBlob(w, c.fundingBlob); err != nil { + return err + } + if err := writeOptBlob(w, c.commitBlob); err != nil { + return err + } + + // The breach transaction is unknown when the retribution was built + // without the spending transaction at hand. + err = channeldb.WriteElement(w, c.commitTx != nil) + if err != nil { + return err + } + if c.commitTx != nil { + err = channeldb.WriteElement(w, c.commitTx) + if err != nil { + return err + } + } + + for _, key := range c.keyRingKeys() { + if err := writeOptPubKey(w, *key); err != nil { + return err + } + } + err = wire.WriteVarBytes(w, 0, c.keyRing.LocalCommitKeyTweak) + if err != nil { + return err + } + err = wire.WriteVarBytes(w, 0, c.keyRing.LocalHtlcKeyTweak) + if err != nil { + return err + } + + err = wire.WriteVarInt(w, 0, uint64(len(c.htlcs))) + if err != nil { + return err + } + for op, htlc := range c.htlcs { + if err := graphdb.WriteOutpoint(w, &op); err != nil { + return err + } + if err := htlc.encode(w); err != nil { + return err + } + } + + return nil +} + +// decode deserializes the aux breach context. +func (c *auxBreachContext) decode(r io.Reader) error { + var version uint8 + err := channeldb.ReadElements( + r, &version, &c.chanType, &c.shortChanID, &c.initiator, + &c.commitFee, &c.csvDelay, + ) + if err != nil { + return err + } + if version != auxBreachStateVersion { + return fmt.Errorf("unknown aux breach context version %d", + version) + } + + if c.fundingBlob, err = readOptBlob(r); err != nil { + return err + } + if c.commitBlob, err = readOptBlob(r); err != nil { + return err + } + + var hasCommitTx bool + if err := channeldb.ReadElement(r, &hasCommitTx); err != nil { + return err + } + if hasCommitTx { + err = channeldb.ReadElement(r, &c.commitTx) + if err != nil { + return err + } + } + + for _, key := range c.keyRingKeys() { + if *key, err = readOptPubKey(r); err != nil { + return err + } + } + c.keyRing.LocalCommitKeyTweak, err = wire.ReadVarBytes( + r, 0, 1000, "commit key tweak", + ) + if err != nil { + return err + } + c.keyRing.LocalHtlcKeyTweak, err = wire.ReadVarBytes( + r, 0, 1000, "htlc key tweak", + ) + if err != nil { + return err + } + + numHtlcs, err := wire.ReadVarInt(r, 0) + if err != nil { + return err + } + + c.htlcs = make(map[wire.OutPoint]auxBreachHtlc) + for range numHtlcs { + var op wire.OutPoint + if err := graphdb.ReadOutpoint(r, &op); err != nil { + return err + } + + var htlc auxBreachHtlc + if err := htlc.decode(r); err != nil { + return err + } + + c.htlcs[op] = htlc + } + + return nil +} + +// encode serializes the HTLC specific part of an aux resolution request. +func (h *auxBreachHtlc) encode(w io.Writer) error { + err := channeldb.WriteElements( + w, h.htlcID.IsSome(), h.htlcID.UnwrapOr(0), + h.incoming.IsSome(), h.incoming.UnwrapOr(false), + h.payHash.IsSome(), h.payHash.UnwrapOr([32]byte{}), + h.cltvDelay.IsSome(), h.cltvDelay.UnwrapOr(0), + ) + if err != nil { + return err + } + + if err := wire.WriteVarBytes(w, 0, h.auxSig); err != nil { + return err + } + if err := writeKeyDesc(w, h.auxSigKeyDesc); err != nil { + return err + } + + return wire.WriteVarBytes(w, 0, h.auxSigTweak) +} + +// decode deserializes the HTLC specific part of an aux resolution request. +func (h *auxBreachHtlc) decode(r io.Reader) error { + var ( + hasID, hasIncoming, hasPayHash, hasCltv bool + htlcID uint64 + incoming bool + payHash [32]byte + cltvDelay uint32 + ) + err := channeldb.ReadElements( + r, &hasID, &htlcID, &hasIncoming, &incoming, &hasPayHash, + &payHash, &hasCltv, &cltvDelay, + ) + if err != nil { + return err + } + + if hasID { + h.htlcID = fn.Some(htlcID) + } + if hasIncoming { + h.incoming = fn.Some(incoming) + } + if hasPayHash { + h.payHash = fn.Some(payHash) + } + if hasCltv { + h.cltvDelay = fn.Some(cltvDelay) + } + + h.auxSig, err = wire.ReadVarBytes( + r, 0, wire.MaxMessagePayload, "aux sig", + ) + if err != nil { + return err + } + if h.auxSigKeyDesc, err = readKeyDesc(r); err != nil { + return err + } + h.auxSigTweak, err = wire.ReadVarBytes(r, 0, 1000, "aux sig tweak") + + return err +} + +// encodeJusticeTxCtx serializes what the breach arbiter needs to tell the +// aux sweeper about a justice transaction once it confirms. The transaction +// itself is not stored: it is taken from the spend that reports it. +func encodeJusticeTxCtx(w io.Writer, jtx *justiceTxCtx) error { + err := channeldb.WriteElements( + w, auxBreachStateVersion, jtx.fee, jtx.hasSecondLevel, + ) + if err != nil { + return err + } + + err = wire.WriteVarBytes(w, 0, jtx.sweepAddr.DeliveryAddress) + if err != nil { + return err + } + if err := writeOptKeyDesc(w, jtx.sweepAddr.InternalKey); err != nil { + return err + } + + err = channeldb.WriteElement(w, jtx.extraTxOut.IsSome()) + if err != nil { + return err + } + + return fn.MapOptionZ(jtx.extraTxOut, func(o sweep.SweepOutput) error { + err := channeldb.WriteElements(w, o.Value, o.IsExtra) + if err != nil { + return err + } + + err = wire.WriteVarBytes(w, 0, o.PkScript) + if err != nil { + return err + } + + return writeOptKeyDesc(w, o.InternalKey) + }) +} + +// decodeJusticeTxCtx deserializes a justice transaction context written by +// encodeJusticeTxCtx. +func decodeJusticeTxCtx(r io.Reader) (*justiceTxCtx, error) { + var ( + jtx justiceTxCtx + version uint8 + ) + err := channeldb.ReadElements( + r, &version, &jtx.fee, &jtx.hasSecondLevel, + ) + if err != nil { + return nil, err + } + if version != auxBreachStateVersion { + return nil, fmt.Errorf("unknown justice tx context version %d", + version) + } + + jtx.sweepAddr.DeliveryAddress, err = wire.ReadVarBytes( + r, 0, 1000, "sweep address", + ) + if err != nil { + return nil, err + } + if jtx.sweepAddr.InternalKey, err = readOptKeyDesc(r); err != nil { + return nil, err + } + + var hasExtraOut bool + if err := channeldb.ReadElement(r, &hasExtraOut); err != nil { + return nil, err + } + if !hasExtraOut { + return &jtx, nil + } + + var extraOut sweep.SweepOutput + err = channeldb.ReadElements(r, &extraOut.Value, &extraOut.IsExtra) + if err != nil { + return nil, err + } + extraOut.PkScript, err = wire.ReadVarBytes( + r, 0, 1000, "extra output script", + ) + if err != nil { + return nil, err + } + if extraOut.InternalKey, err = readOptKeyDesc(r); err != nil { + return nil, err + } + jtx.extraTxOut = fn.Some(extraOut) + + return &jtx, nil +} + +// putAuxBreachContext stores the aux resolution context of a retribution, +// if it has any. +func putAuxBreachContext(tx kvdb.RwTx, chanKey []byte, + ret *retributionInfo) error { + + ctx := auxBreachContextFromRetInfo(ret) + if ctx == nil { + return nil + } + + auxBucket, err := tx.CreateTopLevelBucket(auxRetributionBucket) + if err != nil { + return err + } + chanBucket, err := auxBucket.CreateBucketIfNotExists(chanKey) + if err != nil { + return err + } + + var b bytes.Buffer + if err := ctx.encode(&b); err != nil { + return err + } + + return chanBucket.Put(auxBreachContextKey, b.Bytes()) +} + +// fetchAuxBreachState loads the aux state stored for a retribution and +// applies it: the request templates of its HTLC outputs are restored, and +// the justice transactions created for it so far are attached. +func fetchAuxBreachState(tx kvdb.RTx, chanKey []byte, + ret *retributionInfo) error { + + auxBucket := tx.ReadBucket(auxRetributionBucket) + if auxBucket == nil { + return nil + } + chanBucket := auxBucket.NestedReadBucket(chanKey) + if chanBucket == nil { + return nil + } + + if ctxBytes := chanBucket.Get(auxBreachContextKey); ctxBytes != nil { + var ctx auxBreachContext + err := ctx.decode(bytes.NewReader(ctxBytes)) + if err != nil { + return fmt.Errorf("decode aux breach context: %w", err) + } + + ctx.apply(ret) + } + + justiceBucket := chanBucket.NestedReadBucket(auxBreachJusticeBucket) + if justiceBucket == nil { + return nil + } + + ret.justiceTxs = make(map[chainhash.Hash]*justiceTxCtx) + + return justiceBucket.ForEach(func(k, v []byte) error { + txid, err := chainhash.NewHash(k) + if err != nil { + return err + } + + jtx, err := decodeJusticeTxCtx(bytes.NewReader(v)) + if err != nil { + return fmt.Errorf("decode justice tx %v: %w", txid, err) + } + ret.justiceTxs[*txid] = jtx + + return nil + }) +} + +// deleteAuxBreachState removes the aux state stored for a retribution. +func deleteAuxBreachState(tx kvdb.RwTx, chanKey []byte) error { + auxBucket := tx.ReadWriteBucket(auxRetributionBucket) + if auxBucket == nil { + return nil + } + + err := auxBucket.DeleteNestedBucket(chanKey) + if err != nil && !errors.Is(err, kvdb.ErrBucketNotFound) { + return err + } + + return nil +} + +// RecordJusticeTxs persists the metadata of the given justice transactions +// of a breached channel, keyed by txid. Transactions recorded earlier are +// kept. +func (rs *RetributionStore) RecordJusticeTxs(chanPoint *wire.OutPoint, + justiceTxs map[chainhash.Hash]*justiceTxCtx) error { + + if len(justiceTxs) == 0 { + return nil + } + + return kvdb.Update(rs.db, func(tx kvdb.RwTx) error { + var chanBuf bytes.Buffer + err := graphdb.WriteOutpoint(&chanBuf, chanPoint) + if err != nil { + return err + } + + auxBucket, err := tx.CreateTopLevelBucket( + auxRetributionBucket, + ) + if err != nil { + return err + } + chanBucket, err := auxBucket.CreateBucketIfNotExists( + chanBuf.Bytes(), + ) + if err != nil { + return err + } + justiceBucket, err := chanBucket.CreateBucketIfNotExists( + auxBreachJusticeBucket, + ) + if err != nil { + return err + } + + for txid, jtx := range justiceTxs { + var b bytes.Buffer + if err := encodeJusticeTxCtx(&b, jtx); err != nil { + return err + } + + err := justiceBucket.Put(txid[:], b.Bytes()) + if err != nil { + return err + } + } + + return nil + }, func() {}) +} diff --git a/contractcourt/breach_aux_state_test.go b/contractcourt/breach_aux_state_test.go new file mode 100644 index 00000000000..b9e711ae357 --- /dev/null +++ b/contractcourt/breach_aux_state_test.go @@ -0,0 +1,517 @@ +package contractcourt + +import ( + "bytes" + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightningnetwork/lnd/channeldb" + "github.com/lightningnetwork/lnd/fn/v2" + graphdb "github.com/lightningnetwork/lnd/graph/db" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/keychain" + "github.com/lightningnetwork/lnd/kvdb" + "github.com/lightningnetwork/lnd/lnwallet" + "github.com/lightningnetwork/lnd/lnwire" + "github.com/lightningnetwork/lnd/sweep" + "github.com/lightningnetwork/lnd/tlv" + "github.com/stretchr/testify/require" +) + +// randPubKey returns a random public key. +func randPubKey(t *testing.T) *btcec.PublicKey { + t.Helper() + + priv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + return priv.PubKey() +} + +// newAuxRetribution builds the retribution of a breached aux channel the way +// newRetributionInfo does: a revoked commitment output with a resolution +// blob, and one HTLC in each direction, each with a first-level resolution +// blob and the resolution request template a second-level resolution needs. +// Both HTLCs share the HTLC index 0. +func newAuxRetribution(t *testing.T) *retributionInfo { + t.Helper() + + commitSecret, err := btcec.NewPrivateKey() + require.NoError(t, err) + revokeBase := randPubKey(t) + + commitTx := wire.NewMsgTx(2) + commitTx.AddTxIn(&wire.TxIn{}) + for range 3 { + commitTx.AddTxOut(&wire.TxOut{ + Value: 1000, PkScript: randomPkScript(t), + }) + } + commitHash := commitTx.TxHash() + + keyRing := &lnwallet.CommitmentKeyRing{ + CommitPoint: commitSecret.PubKey(), + LocalCommitKeyTweak: []byte{0x01, 0x02}, + LocalHtlcKeyTweak: []byte{0x03, 0x04}, + LocalHtlcKey: randPubKey(t), + RemoteHtlcKey: randPubKey(t), + ToLocalKey: randPubKey(t), + ToRemoteKey: randPubKey(t), + RevocationKey: randPubKey(t), + } + htlcBasePoint := keychain.KeyDescriptor{ + KeyLocator: keychain.KeyLocator{ + Family: keychain.KeyFamilyHtlcBase, + Index: 7, + }, + PubKey: randPubKey(t), + } + + ret := &retributionInfo{ + commitHash: commitHash, + chanPoint: wire.OutPoint{Hash: chainhash.Hash{0xaa}}, + chainHash: chainhash.Hash{0xbb}, + breachHeight: 321, + } + + // The revoked commitment output. + ret.breachedOutputs = append(ret.breachedOutputs, breachedOutput{ + amt: 1000, + outpoint: wire.OutPoint{Hash: commitHash, Index: 0}, + witnessType: input.TaprootCommitmentRevoke, + signDesc: input.SignDescriptor{ + KeyDesc: keychain.KeyDescriptor{PubKey: revokeBase}, + DoubleTweak: commitSecret, + Output: commitTx.TxOut[0], + HashType: txscript.SigHashDefault, + }, + resolutionBlob: fn.Some(tlv.Blob{0xc0}), + }) + + htlcOutput := func(index uint32, incoming bool, + auxSig []byte) breachedOutput { + + witnessType := input.TaprootHtlcOfferedRevoke + if incoming { + witnessType = input.TaprootHtlcAcceptedRevoke + } + + signDesc := input.SignDescriptor{ + KeyDesc: keychain.KeyDescriptor{PubKey: revokeBase}, + DoubleTweak: commitSecret, + Output: commitTx.TxOut[index], + HashType: txscript.SigHashDefault, + SignMethod: input.TaprootKeySpendSignMethod, + TapTweak: bytes.Repeat([]byte{byte(index)}, 32), + } + + req := &lnwallet.ResolutionReq{ + ChanPoint: ret.chanPoint, + ChanType: channeldb.SimpleTaprootFeatureBit, + ShortChanID: lnwire.NewShortChanIDFromInt(99), + Initiator: true, + CommitBlob: fn.Some(tlv.Blob{0x0c, 0x0b}), + FundingBlob: fn.Some(tlv.Blob{0x0f}), + HtlcID: fn.Some(uint64(0)), + HtlcIncoming: fn.Some(incoming), + HtlcAmt: 1000, + Type: witnessType, + CloseType: lnwallet.Breach, + CommitTx: commitTx, + CommitTxBlockHeight: ret.breachHeight, + CommitFee: 500, + SignDesc: signDesc, + KeyRing: keyRing, + CsvDelay: 144, + CltvDelay: fn.Some(700 + index), + PayHash: fn.Some([32]byte{byte(index)}), + } + if auxSig != nil { + //nolint:ll + req.AuxSigDesc = fn.Some(lnwallet.AuxSigDesc{ + AuxSig: auxSig, + SignDetails: input.SignDetails{ + SignDesc: input.SignDescriptor{ + KeyDesc: htlcBasePoint, + SingleTweak: keyRing.LocalHtlcKeyTweak, + SignMethod: input.TaprootScriptSpendSignMethod, + }, + }, + }) + } + + return breachedOutput{ + amt: 1000, + outpoint: wire.OutPoint{ + Hash: commitHash, Index: index, + }, + witnessType: witnessType, + signDesc: signDesc, + secondLevelWitnessScript: []byte{0x51}, + secondLevelTapTweak: [32]byte{0xee, byte(index)}, + resolveReq: req, + resolutionBlob: fn.Some( + tlv.Blob{0xf1, byte(index)}, + ), + } + } + + // One HTLC we received, whose revocation carried an aux sig, and one + // we offered, whose revocation did not. + ret.breachedOutputs = append( + ret.breachedOutputs, + htlcOutput(1, true, []byte{0xa5, 0x16}), + htlcOutput(2, false, nil), + ) + + return ret +} + +// requireSameResolveReq asserts that a resolution request restored from the +// store carries everything the original one did. +func requireSameResolveReq(t *testing.T, want, got *lnwallet.ResolutionReq) { + t.Helper() + + require.NotNil(t, got) + + // The key ring and the transaction are compared by value, everything + // else directly. + requireSameKey := func(a, b *btcec.PublicKey) { + require.True(t, a.IsEqual(b)) + } + requireSameKey(want.KeyRing.CommitPoint, got.KeyRing.CommitPoint) + requireSameKey(want.KeyRing.LocalHtlcKey, got.KeyRing.LocalHtlcKey) + requireSameKey(want.KeyRing.RemoteHtlcKey, got.KeyRing.RemoteHtlcKey) + requireSameKey(want.KeyRing.ToLocalKey, got.KeyRing.ToLocalKey) + requireSameKey(want.KeyRing.ToRemoteKey, got.KeyRing.ToRemoteKey) + requireSameKey(want.KeyRing.RevocationKey, got.KeyRing.RevocationKey) + require.Equal( + t, want.KeyRing.LocalCommitKeyTweak, + got.KeyRing.LocalCommitKeyTweak, + ) + require.Equal( + t, want.KeyRing.LocalHtlcKeyTweak, + got.KeyRing.LocalHtlcKeyTweak, + ) + + require.Equal(t, want.CommitTx.TxHash(), got.CommitTx.TxHash()) + + requireSameSignDesc := func(a, b input.SignDescriptor) { + requireSameKey(a.KeyDesc.PubKey, b.KeyDesc.PubKey) + require.Equal(t, a.KeyDesc.KeyLocator, b.KeyDesc.KeyLocator) + require.Equal(t, a.SingleTweak, b.SingleTweak) + require.Equal(t, a.DoubleTweak, b.DoubleTweak) + require.Equal(t, a.Output, b.Output) + require.Equal(t, a.HashType, b.HashType) + require.Equal(t, a.SignMethod, b.SignMethod) + require.Equal(t, a.TapTweak, b.TapTweak) + } + requireSameSignDesc(want.SignDesc, got.SignDesc) + + require.Equal(t, want.AuxSigDesc.IsSome(), got.AuxSigDesc.IsSome()) + want.AuxSigDesc.WhenSome(func(wantDesc lnwallet.AuxSigDesc) { + gotDesc := got.AuxSigDesc.UnwrapOr(lnwallet.AuxSigDesc{}) + + require.Equal(t, wantDesc.AuxSig, gotDesc.AuxSig) + requireSameSignDesc( + wantDesc.SignDetails.SignDesc, + gotDesc.SignDetails.SignDesc, + ) + }) + + wantRest, gotRest := *want, *got + for _, req := range []*lnwallet.ResolutionReq{&wantRest, &gotRest} { + req.KeyRing = nil + req.CommitTx = nil + req.SignDesc = input.SignDescriptor{} + req.AuxSigDesc = fn.None[lnwallet.AuxSigDesc]() + } + require.Equal(t, wantRest, gotRest) +} + +// loadRetribution returns the single retribution held by the store. +func loadRetribution(t *testing.T, rs *RetributionStore) *retributionInfo { + t.Helper() + + var rets []*retributionInfo + err := rs.ForAll(func(ret *retributionInfo) error { + rets = append(rets, ret) + + return nil + }, func() { + rets = nil + }) + require.NoError(t, err) + require.Len(t, rets, 1) + + return rets[0] +} + +// hasAuxRetributionState reports whether the store holds any aux state for +// the given channel. +func hasAuxRetributionState(t *testing.T, db kvdb.Backend, + chanPoint wire.OutPoint) bool { + + t.Helper() + + var chanKey bytes.Buffer + require.NoError(t, graphdb.WriteOutpoint(&chanKey, &chanPoint)) + + var found bool + err := kvdb.View(db, func(tx kvdb.RTx) error { + auxBucket := tx.ReadBucket(auxRetributionBucket) + if auxBucket == nil { + return nil + } + found = auxBucket.NestedReadBucket(chanKey.Bytes()) != nil + + return nil + }, func() { + found = false + }) + require.NoError(t, err) + + return found +} + +// TestRetributionStoreAuxState asserts that the retribution of a breached +// aux channel survives a restart with everything the breach arbiter needs to +// finish the job. Without the resolution request templates, an HTLC that is +// taken to the second level after the restart would be handled like the +// HTLC of a regular channel: its second-level output is never resolved, so +// the HTLC's aux value is not swept. Without the first-level blobs, the same +// goes for an HTLC that is swept straight from the commitment. +func TestRetributionStoreAuxState(t *testing.T) { + t.Parallel() + + db := channeldb.OpenForTesting(t, t.TempDir()) + rs := NewRetributionStore(db) + + original := newAuxRetribution(t) + require.True(t, original.hasAuxData()) + require.NoError(t, rs.Add(original)) + + // Restart: the retribution is loaded from disk. + loaded := loadRetribution(t, rs) + require.True(t, loaded.hasAuxData()) + require.Len(t, loaded.breachedOutputs, 3) + require.Empty(t, loaded.justiceTxs) + + for i := range original.breachedOutputs { + want := &original.breachedOutputs[i] + got := &loaded.breachedOutputs[i] + + require.Equal(t, want.outpoint, got.outpoint) + require.Equal(t, want.witnessType, got.witnessType) + + // Every output keeps its blob, HTLCs included. + require.Equal(t, want.resolutionBlob, got.resolutionBlob) + + // The commitment output never had a template. + if want.resolveReq == nil { + require.Nil(t, got.resolveReq) + + continue + } + + requireSameResolveReq(t, want.resolveReq, got.resolveReq) + } + + // The two HTLCs share an index and are told apart by direction. + require.Equal( + t, fn.Some(true), + loaded.breachedOutputs[1].resolveReq.HtlcIncoming, + ) + require.Equal( + t, fn.Some(false), + loaded.breachedOutputs[2].resolveReq.HtlcIncoming, + ) + + // Removing the retribution removes its aux state with it. + require.True(t, hasAuxRetributionState(t, db, original.chanPoint)) + require.NoError(t, rs.Remove(&original.chanPoint)) + require.False(t, hasAuxRetributionState(t, db, original.chanPoint)) + require.Zero(t, countRetributions(t, rs)) +} + +// TestRetributionStoreJusticeTxs asserts that the justice transactions +// recorded for a breach are handed back when the retribution is loaded after +// a restart, with what it takes to report the one that confirms to the aux +// sweeper. They are the only way to recognize a justice transaction that was +// broadcast before the restart: the ones built afterwards pay to a new +// address with a new fee and have different txids. +func TestRetributionStoreJusticeTxs(t *testing.T) { + t.Parallel() + + db := channeldb.OpenForTesting(t, t.TempDir()) + rs := NewRetributionStore(db) + + ret := newAuxRetribution(t) + require.NoError(t, rs.Add(ret)) + + internalKey := keychain.KeyDescriptor{ + KeyLocator: keychain.KeyLocator{Family: 9, Index: 4}, + PubKey: randPubKey(t), + } + auxKey := keychain.KeyDescriptor{ + KeyLocator: keychain.KeyLocator{Family: 212, Index: 1}, + PubKey: randPubKey(t), + } + + spendAll := &justiceTxCtx{ + fee: 1234, + hasSecondLevel: true, + sweepAddr: lnwallet.AddrWithKey{ + DeliveryAddress: lnwire.DeliveryAddress{0x51, 0x20}, + InternalKey: fn.Some(internalKey), + }, + extraTxOut: fn.Some(sweep.SweepOutput{ + TxOut: wire.TxOut{ + Value: 400, + PkScript: []byte{0x51, 0x21}, + }, + IsExtra: true, + InternalKey: fn.Some(auxKey), + }), + } + spendCommit := &justiceTxCtx{ + fee: 99, + sweepAddr: lnwallet.AddrWithKey{ + DeliveryAddress: lnwire.DeliveryAddress{0x00, 0x14}, + }, + } + + first := map[chainhash.Hash]*justiceTxCtx{ + {0x01}: spendAll, + } + second := map[chainhash.Hash]*justiceTxCtx{ + {0x02}: spendCommit, + } + + // The variants are recorded as they are created, over several + // rebuilds. Earlier ones are kept. + require.NoError(t, rs.RecordJusticeTxs(&ret.chanPoint, nil)) + require.NoError(t, rs.RecordJusticeTxs(&ret.chanPoint, first)) + require.NoError(t, rs.RecordJusticeTxs(&ret.chanPoint, second)) + + loaded := loadRetribution(t, rs) + require.Len(t, loaded.justiceTxs, 2) + + requireSameJusticeTx := func(want, got *justiceTxCtx) { + t.Helper() + + require.NotNil(t, got) + require.Equal(t, want.fee, got.fee) + require.Equal(t, want.hasSecondLevel, got.hasSecondLevel) + require.Equal( + t, want.sweepAddr.DeliveryAddress, + got.sweepAddr.DeliveryAddress, + ) + + requireSameKeyDesc := func( + a, b fn.Option[keychain.KeyDescriptor]) { + + require.Equal(t, a.IsSome(), b.IsSome()) + a.WhenSome(func(wantKey keychain.KeyDescriptor) { + gotKey := b.UnwrapOr(keychain.KeyDescriptor{}) + + require.Equal( + t, wantKey.KeyLocator, + gotKey.KeyLocator, + ) + require.True( + t, + wantKey.PubKey.IsEqual(gotKey.PubKey), + ) + }) + } + requireSameKeyDesc( + want.sweepAddr.InternalKey, got.sweepAddr.InternalKey, + ) + + require.Equal( + t, want.extraTxOut.IsSome(), got.extraTxOut.IsSome(), + ) + want.extraTxOut.WhenSome(func(wantOut sweep.SweepOutput) { + gotOut := got.extraTxOut.UnwrapOr(sweep.SweepOutput{}) + + require.Equal(t, wantOut.TxOut, gotOut.TxOut) + require.Equal(t, wantOut.IsExtra, gotOut.IsExtra) + requireSameKeyDesc( + wantOut.InternalKey, gotOut.InternalKey, + ) + }) + } + requireSameJusticeTx(spendAll, loaded.justiceTxs[chainhash.Hash{1}]) + requireSameJusticeTx(spendCommit, loaded.justiceTxs[chainhash.Hash{2}]) + + // The loaded history seeds the tracker of the retribution loop. + tracker := newJusticeTxTracker(loaded.justiceTxs) + require.Len(t, tracker.history, 2) + + // Cleaning the breach up removes the recorded transactions too. + require.NoError(t, rs.Remove(&ret.chanPoint)) + require.False(t, hasAuxRetributionState(t, db, ret.chanPoint)) +} + +// TestRetributionStoreRegularChannelNoAuxState asserts that nothing at all is +// written to the aux retribution bucket for the breach of a regular channel, +// and that such a retribution is loaded without any aux data. +func TestRetributionStoreRegularChannelNoAuxState(t *testing.T) { + t.Parallel() + + db := channeldb.OpenForTesting(t, t.TempDir()) + rs := NewRetributionStore(db) + + // The same retribution as for the aux channel, minus the aux data. + ret := newAuxRetribution(t) + for i := range ret.breachedOutputs { + ret.breachedOutputs[i].resolveReq = nil + ret.breachedOutputs[i].resolutionBlob = fn.None[tlv.Blob]() + } + require.False(t, ret.hasAuxData()) + require.NoError(t, rs.Add(ret)) + + require.False(t, hasAuxRetributionState(t, db, ret.chanPoint)) + + loaded := loadRetribution(t, rs) + require.False(t, loaded.hasAuxData()) + require.Nil(t, loaded.justiceTxs) + + require.NoError(t, rs.Remove(&ret.chanPoint)) +} + +// TestAuxBreachContextDecodeCorrupt asserts that truncated aux retribution +// records fail to decode instead of yielding a partial state. +func TestAuxBreachContextDecodeCorrupt(t *testing.T) { + t.Parallel() + + ctx := auxBreachContextFromRetInfo(newAuxRetribution(t)) + require.NotNil(t, ctx) + + var b bytes.Buffer + require.NoError(t, ctx.encode(&b)) + encoded := b.Bytes() + + var decoded auxBreachContext + require.NoError(t, decoded.decode(bytes.NewReader(encoded))) + require.Len(t, decoded.htlcs, 2) + + for _, cut := range []int{0, 1, len(encoded) / 2, len(encoded) - 1} { + var truncated auxBreachContext + err := truncated.decode(bytes.NewReader(encoded[:cut])) + require.Error(t, err, "cut at %d", cut) + } + + // An unknown version is refused. + unknown := bytes.Clone(encoded) + unknown[0] = auxBreachStateVersion + 1 + var versioned auxBreachContext + require.ErrorContains( + t, versioned.decode(bytes.NewReader(unknown)), + "unknown aux breach context version", + ) +} diff --git a/contractcourt/htlc_second_level_blob_test.go b/contractcourt/htlc_second_level_blob_test.go new file mode 100644 index 00000000000..862998c4fac --- /dev/null +++ b/contractcourt/htlc_second_level_blob_test.go @@ -0,0 +1,232 @@ +package contractcourt + +import ( + "errors" + "testing" + + "github.com/btcsuite/btcd/txscript/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightningnetwork/lnd/channeldb" + "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/lnwallet" + "github.com/lightningnetwork/lnd/tlv" + "github.com/stretchr/testify/require" +) + +// Channel types used by the second-level resolution blob tests. +const ( + // blobTestAuxChanType is an aux/custom (taproot asset) channel. + blobTestAuxChanType = channeldb.SimpleTaprootFeatureBit | + channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit | + channeldb.TapscriptRootBit + + // blobTestTaprootChanType is a regular simple taproot channel. + blobTestTaprootChanType = channeldb.SimpleTaprootFeatureBit | + channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit +) + +// secondLevelBlobTestCase describes a resolver whose second-level HTLC tx +// confirmed and that is about to sweep its output. +type secondLevelBlobTestCase struct { + name string + chanType channeldb.ChannelType + sigHashType txscript.SigHashType + resolveErr error + + // wantResolved is true if the blob must be resolved anew against the + // second-level tx. + wantResolved bool + + // wantBlob is the blob the output must be swept with. + wantBlob tlv.Blob +} + +// Blobs used by the second-level resolution blob tests. +var ( + // forceCloseBlob is the blob resolved at force close time. + forceCloseBlob = tlv.Blob{0x01} + + // secondLevelBlob is the blob resolved against the second-level tx. + secondLevelBlob = tlv.Blob{0x02} +) + +// secondLevelBlobTestCases covers the gate of the second-level blob +// re-resolution. Only a pre-signed SigHashDefault second-level tx, which +// exists on aux channels alone, confirms exactly as we hold it. A +// SINGLE|ANYONECANPAY one is rebuilt by the sweeper, so on such a channel the +// blob from force close time must be kept, aux channel or not: a blob +// resolved against our copy of the transaction would point at a transaction +// that never confirmed. +var secondLevelBlobTestCases = []secondLevelBlobTestCase{{ + name: "aux channel, SigHashDefault", + chanType: blobTestAuxChanType, + sigHashType: txscript.SigHashDefault, + wantResolved: true, + wantBlob: secondLevelBlob, +}, { + name: "aux channel, SINGLE|ANYONECANPAY", + chanType: blobTestAuxChanType, + sigHashType: txscript.SigHashSingle | + txscript.SigHashAnyOneCanPay, + wantBlob: forceCloseBlob, +}, { + // SigHashDefault is the zero value of the sighash type, so a regular + // channel that never sets it must not be mistaken for one that + // negotiated it. + name: "regular taproot channel", + chanType: blobTestTaprootChanType, + sigHashType: txscript.SigHashDefault, + wantBlob: forceCloseBlob, +}, { + // If the aux resolver fails, the blob from force close time is all + // we have. + name: "aux channel, SigHashDefault, resolver fails", + chanType: blobTestAuxChanType, + sigHashType: txscript.SigHashDefault, + resolveErr: errors.New("cannot resolve"), + wantResolved: true, + wantBlob: forceCloseBlob, +}} + +// newSecondLevelBlobTestConfig returns a resolver config with the given aux +// resolver attached, the way it is attached to every resolver of a node that +// runs with an aux resolver, whatever the channel type. +func newSecondLevelBlobTestConfig(resolver *auxTestResolver) ResolverConfig { + return ResolverConfig{ + ChannelArbitratorConfig: ChannelArbitratorConfig{ + ChainArbitratorConfig: ChainArbitratorConfig{ + //nolint:ll + AuxResolver: fn.Some[lnwallet.AuxContractResolver]( + resolver, + ), + }, + }, + } +} + +// requireSecondLevelBlob asserts the outcome of a second-level resolution +// blob test case. +func requireSecondLevelBlob(t *testing.T, tc secondLevelBlobTestCase, + resolver *auxTestResolver, secondLevelTx *wire.MsgTx, + witType input.WitnessType, blob fn.Option[tlv.Blob]) { + + t.Helper() + + require.Equal(t, fn.Some(tc.wantBlob), blob) + + if !tc.wantResolved { + require.Empty(t, resolver.reqs) + + return + } + + // The request targets the second-level output sweep and carries the + // second-level tx along with the height it confirmed at. + require.Len(t, resolver.reqs, 1) + req := resolver.reqs[0] + require.Equal(t, witType, req.Type) + + secondLevel, err := req.SecondLevel.UnwrapOrErr( + errors.New("no second-level info"), + ) + require.NoError(t, err) + require.Equal(t, secondLevelTx, secondLevel.Tx) + require.EqualValues(t, 800, secondLevel.BlockHeight) +} + +// TestHtlcSuccessResolverSecondLevelBlob asserts which resolution blob the +// success resolver sweeps the output of its second-level tx with. +func TestHtlcSuccessResolverSecondLevelBlob(t *testing.T) { + t.Parallel() + + witType := input.WitnessType( + input.TaprootHtlcAcceptedSuccessSecondLevel, + ) + + for _, tc := range secondLevelBlobTestCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + resolver := &auxTestResolver{ + blob: secondLevelBlob, + err: tc.resolveErr, + } + successTx := wire.NewMsgTx(2) + successTx.AddTxOut(&wire.TxOut{Value: 630}) + + cfg := newSecondLevelBlobTestConfig(resolver) + h := &htlcSuccessResolver{ + contractResolverKit: *newContractResolverKit( + cfg, + ), + htlcResolution: lnwallet.IncomingHtlcResolution{ + SignedSuccessTx: successTx, + SignDetails: &input.SignDetails{ + SigHashType: tc.sigHashType, + }, + ResolutionBlob: fn.Some(forceCloseBlob), + + ResolveReq: &lnwallet.ResolutionReq{}, + }, + chanType: tc.chanType, + } + h.initLogger("test") + + blob := h.secondLevelResolutionBlob(witType, 800) + requireSecondLevelBlob( + t, tc, resolver, successTx, witType, blob, + ) + }) + } +} + +// TestHtlcTimeoutResolverSecondLevelBlob asserts which resolution blob the +// timeout resolver sweeps the output of its second-level tx with. +func TestHtlcTimeoutResolverSecondLevelBlob(t *testing.T) { + t.Parallel() + + witType := input.WitnessType( + input.TaprootHtlcOfferedTimeoutSecondLevel, + ) + + for _, tc := range secondLevelBlobTestCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + resolver := &auxTestResolver{ + blob: secondLevelBlob, + err: tc.resolveErr, + } + timeoutTx := wire.NewMsgTx(2) + timeoutTx.AddTxOut(&wire.TxOut{Value: 630}) + + cfg := newSecondLevelBlobTestConfig(resolver) + h := &htlcTimeoutResolver{ + contractResolverKit: *newContractResolverKit( + cfg, + ), + htlcResolution: lnwallet.OutgoingHtlcResolution{ + SignedTimeoutTx: timeoutTx, + SignDetails: &input.SignDetails{ + SigHashType: tc.sigHashType, + }, + ResolutionBlob: fn.Some(forceCloseBlob), + + ResolveReq: &lnwallet.ResolutionReq{}, + }, + chanType: tc.chanType, + } + h.initLogger("test") + + blob := h.secondLevelResolutionBlob(witType, 800) + requireSecondLevelBlob( + t, tc, resolver, timeoutTx, witType, blob, + ) + }) + } +} diff --git a/contractcourt/htlc_success_resolver.go b/contractcourt/htlc_success_resolver.go index 1bf3b874055..0979a72d6c2 100644 --- a/contractcourt/htlc_success_resolver.go +++ b/contractcourt/htlc_success_resolver.go @@ -23,6 +23,7 @@ import ( "github.com/lightningnetwork/lnd/lnutils" "github.com/lightningnetwork/lnd/lnwallet" "github.com/lightningnetwork/lnd/sweep" + "github.com/lightningnetwork/lnd/tlv" ) // errInvalidSpendDetails identifies malformed notifier spend data. @@ -596,6 +597,98 @@ func (h *htlcSuccessResolver) isSigHashDefault() bool { ) } +// secondLevelResolutionBlob returns the aux resolution blob to sweep the +// output of the confirmed second-level HTLC success tx with. +// +// For a pre-signed SigHashDefault second-level tx the blob is resolved anew +// against that transaction: it is the exact transaction that confirmed, and +// the aux resolver needs it to re-anchor its proofs. The AuxResolver is a +// daemon-global option (present on every resolver whenever tapd is attached, +// regardless of channel type), and SigHashDefault second-level txs only +// exist on aux/custom (taproot asset) channels, so the gate guarantees this +// never runs for a non-custom channel. +// +// In every other case the blob resolved at force close time is returned +// unchanged. That includes aux channels whose second-level txs are signed +// with SINGLE|ANYONECANPAY: the sweeper rebuilds those with extra inputs, so +// the transaction that confirms is not the one we hold, and a blob resolved +// against ours would point at a transaction that never made it on chain. +func (h *htlcSuccessResolver) secondLevelResolutionBlob( + witType input.WitnessType, spendingHeight uint32) fn.Option[tlv.Blob] { + + resolutionBlob := h.htlcResolution.ResolutionBlob + if !h.isSigHashDefault() { + return resolutionBlob + } + + h.AuxResolver.WhenSome(func(a lnwallet.AuxContractResolver) { + secondLevelTx := h.htlcResolution.SignedSuccessTx + secondLevelReq, err := h.buildSecondLevelResolveReq( + witType, secondLevelTx, spendingHeight, + ) + if err != nil { + h.log.Errorf("Unable to build second-level success "+ + "ResolveReq (htlcID=%v): %v, falling back "+ + "to original blob", h.htlc.HtlcIndex, err) + + return + } + + resolveBlob := a.ResolveContract(*secondLevelReq) + if err := resolveBlob.Err(); err != nil { + h.log.Errorf("Unable to re-resolve aux blob for "+ + "second-level success output sweep "+ + "(htlcID=%v): %v, falling back to original "+ + "blob, output sweep may fail aux proof "+ + "verification", h.htlc.HtlcIndex, err) + + return + } + + h.log.Infof("re-resolved aux blob for second-level success "+ + "output sweep (htlcID=%v, secondLevelTxid=%v)", + h.htlc.HtlcIndex, secondLevelTx.TxHash()) + + resolutionBlob = resolveBlob.OkToSome() + }) + + return resolutionBlob +} + +// buildSecondLevelResolveReq returns a ResolutionReq targeting the +// just-confirmed second-level HTLC tx. The fast path clones the +// ResolveReq preserved on htlcResolution at force-close time and updates +// only the fields that differ for a second-level sweep. The slow path +// (used when the resolver was recovered from the briefcase and the +// in-memory ResolveReq is gone) reconstructs the request from historical +// channel state. +func (h *htlcSuccessResolver) buildSecondLevelResolveReq( + witType input.WitnessType, secondLevelTx *wire.MsgTx, + spendingHeight uint32) (*lnwallet.ResolutionReq, error) { + + if h.htlcResolution.ResolveReq != nil { + req := *h.htlcResolution.ResolveReq + req.Type = witType + req.SecondLevel = fn.Some(lnwallet.SecondLevelInfo{ + Tx: secondLevelTx, + BlockHeight: spendingHeight, + }) + + return &req, nil + } + + chanState, err := h.FetchHistoricalChannel() + if err != nil { + return nil, fmt.Errorf("fetch historical channel: %w", err) + } + + return lnwallet.NewSecondLevelResolveReq( + chanState, &h.htlc, h.htlcResolution.SignDetails, + h.htlcResolution.SweepSignDesc, h.htlcResolution.CsvDelay, + h.broadcastHeight, secondLevelTx, spendingHeight, witType, + ) +} + // publishSuccessTx directly broadcasts the pre-signed second-level HTLC // success transaction. This is used when the transaction was signed with // SigHashDefault (baked-in fees), where the sweeper's normal tx-rebuilding @@ -925,7 +1018,9 @@ func (h *htlcSuccessResolver) sweepSuccessTxOutput() error { witType = input.HtlcAcceptedSuccessSecondLevel } - resolutionBlob := h.htlcResolution.ResolutionBlob + resolutionBlob := h.secondLevelResolutionBlob( + witType, uint32(commitSpend.SpendingHeight), + ) inp := h.makeSweepInput( &secondLevelOutpoint, witType, diff --git a/contractcourt/htlc_timeout_resolver.go b/contractcourt/htlc_timeout_resolver.go index d7d2bb6577e..cf89d242848 100644 --- a/contractcourt/htlc_timeout_resolver.go +++ b/contractcourt/htlc_timeout_resolver.go @@ -22,6 +22,7 @@ import ( "github.com/lightningnetwork/lnd/lnwallet" "github.com/lightningnetwork/lnd/lnwire" "github.com/lightningnetwork/lnd/sweep" + "github.com/lightningnetwork/lnd/tlv" ) var errPreimageMismatch = errors.New("revealed preimage does not match HTLC") @@ -1007,6 +1008,98 @@ func (h *htlcTimeoutResolver) isSigHashDefault() bool { ) } +// secondLevelResolutionBlob returns the aux resolution blob to sweep the +// output of the confirmed second-level HTLC timeout tx with. +// +// For a pre-signed SigHashDefault second-level tx the blob is resolved anew +// against that transaction: it is the exact transaction that confirmed, and +// the aux resolver needs it to re-anchor its proofs. The AuxResolver is a +// daemon-global option (present on every resolver whenever tapd is attached, +// regardless of channel type), and SigHashDefault second-level txs only +// exist on aux/custom (taproot asset) channels, so the gate guarantees this +// never runs for a non-custom channel. +// +// In every other case the blob resolved at force close time is returned +// unchanged. That includes aux channels whose second-level txs are signed +// with SINGLE|ANYONECANPAY: the sweeper rebuilds those with extra inputs, so +// the transaction that confirms is not the one we hold, and a blob resolved +// against ours would point at a transaction that never made it on chain. +func (h *htlcTimeoutResolver) secondLevelResolutionBlob( + witType input.WitnessType, spendingHeight uint32) fn.Option[tlv.Blob] { + + resolutionBlob := h.htlcResolution.ResolutionBlob + if !h.isSigHashDefault() { + return resolutionBlob + } + + h.AuxResolver.WhenSome(func(a lnwallet.AuxContractResolver) { + secondLevelTx := h.htlcResolution.SignedTimeoutTx + secondLevelReq, err := h.buildSecondLevelResolveReq( + witType, secondLevelTx, spendingHeight, + ) + if err != nil { + h.log.Errorf("Unable to build second-level timeout "+ + "ResolveReq (htlcID=%v): %v, falling back "+ + "to original blob", h.htlc.HtlcIndex, err) + + return + } + + resolveBlob := a.ResolveContract(*secondLevelReq) + if err := resolveBlob.Err(); err != nil { + h.log.Errorf("Unable to re-resolve aux blob for "+ + "second-level timeout output sweep "+ + "(htlcID=%v): %v, falling back to original "+ + "blob, output sweep may fail aux proof "+ + "verification", h.htlc.HtlcIndex, err) + + return + } + + h.log.Infof("re-resolved aux blob for second-level timeout "+ + "output sweep (htlcID=%v, secondLevelTxid=%v)", + h.htlc.HtlcIndex, secondLevelTx.TxHash()) + + resolutionBlob = resolveBlob.OkToSome() + }) + + return resolutionBlob +} + +// buildSecondLevelResolveReq returns a ResolutionReq targeting the +// just-confirmed second-level HTLC tx. The fast path clones the +// ResolveReq preserved on htlcResolution at force-close time and updates +// only the fields that differ for a second-level sweep. The slow path +// (used when the resolver was recovered from the briefcase and the +// in-memory ResolveReq is gone) reconstructs the request from historical +// channel state. +func (h *htlcTimeoutResolver) buildSecondLevelResolveReq( + witType input.WitnessType, secondLevelTx *wire.MsgTx, + spendingHeight uint32) (*lnwallet.ResolutionReq, error) { + + if h.htlcResolution.ResolveReq != nil { + req := *h.htlcResolution.ResolveReq + req.Type = witType + req.SecondLevel = fn.Some(lnwallet.SecondLevelInfo{ + Tx: secondLevelTx, + BlockHeight: spendingHeight, + }) + + return &req, nil + } + + chanState, err := h.FetchHistoricalChannel() + if err != nil { + return nil, fmt.Errorf("fetch historical channel: %w", err) + } + + return lnwallet.NewSecondLevelResolveReq( + chanState, &h.htlc, h.htlcResolution.SignDetails, + h.htlcResolution.SweepSignDesc, h.htlcResolution.CsvDelay, + h.broadcastHeight, secondLevelTx, spendingHeight, witType, + ) +} + // publishTimeoutTx directly broadcasts the pre-signed second-level HTLC // timeout transaction. This is used when the transaction was signed with // SigHashDefault (baked-in fees), where the sweeper's normal tx-rebuilding @@ -1141,7 +1234,9 @@ func (h *htlcTimeoutResolver) sweepTimeoutTxOutput() error { witType = input.HtlcOfferedTimeoutSecondLevel } - resolutionBlob := h.htlcResolution.ResolutionBlob + resolutionBlob := h.secondLevelResolutionBlob( + witType, uint32(commitSpend.SpendingHeight), + ) // Let the sweeper sweep the second-level output now that the CSV/CLTV // locks have expired. diff --git a/docs/release-notes/unreleased/11112.md b/docs/release-notes/unreleased/11112.md new file mode 100644 index 00000000000..47b3632359c --- /dev/null +++ b/docs/release-notes/unreleased/11112.md @@ -0,0 +1,13 @@ +# New Features + +## Functional Enhancements + +* Aux (taproot asset) channels now support full HTLC revocation handling: + second-level HTLC transactions are [pre-signed deterministically with a CPFP + anchor](https://github.com/lightningnetwork/lnd/pull/11094), the revoking + party [hands over revocation aux signatures in + RevokeAndAck](https://github.com/lightningnetwork/lnd/pull/11111), and the + [breach machinery consumes them to punish revoked + commitments](https://github.com/lightningnetwork/lnd/pull/11112) across all + second-level spend paths while keeping asset proof chains intact. Regular + channels are unaffected. diff --git a/lnwallet/aux_leaf_store.go b/lnwallet/aux_leaf_store.go index a1553ffada0..25f3105c5d1 100644 --- a/lnwallet/aux_leaf_store.go +++ b/lnwallet/aux_leaf_store.go @@ -200,8 +200,11 @@ type AuxLeafStore interface { // FetchLeavesFromRevocation attempts to fetch the auxiliary leaves // from a channel revocation that stores balance + blob information. + // The chanState, keys, and commitTx fields on the request are needed + // to compute second-level HTLC auxiliary leaves at runtime, since + // these are not stored in the commitment blob. FetchLeavesFromRevocation( - r *channeldb.RevocationLog) fn.Result[CommitDiffAuxResult] + req RevocationLeavesReq) fn.Result[CommitDiffAuxResult] // ApplyHtlcView serves as the state transition function for the custom // channel's blob. Given the old blob, and an HTLC view, then a new @@ -209,6 +212,25 @@ type AuxLeafStore interface { ApplyHtlcView(in CommitDiffAuxInput) fn.Result[fn.Option[tlv.Blob]] } +// RevocationLeavesReq packages the inputs needed to derive aux leaves +// from a channel revocation. ChanState, Keys, and CommitTx are required +// to recompute second-level HTLC leaves that aren't stored in the +// commitment blob. +type RevocationLeavesReq struct { + // Revocation is the revocation log entry whose aux leaves are being + // fetched. + Revocation *channeldb.RevocationLog + + // ChanState is the channel state at the revoked commitment height. + ChanState AuxChanState + + // Keys is the key ring for the revoked commitment. + Keys CommitmentKeyRing + + // CommitTx is the revoked commitment transaction. + CommitTx *wire.MsgTx +} + // auxLeavesFromView is used to derive the set of commit aux leaves (if any), // that are needed to create a new commitment transaction using the original // (unfiltered) htlc view. diff --git a/lnwallet/aux_resolutions.go b/lnwallet/aux_resolutions.go index 8891da7d633..583d922c369 100644 --- a/lnwallet/aux_resolutions.go +++ b/lnwallet/aux_resolutions.go @@ -29,8 +29,12 @@ const ( // channels. type AuxSigDesc struct { // AuxSig is the second-level signature for the HTLC that we are trying - // to resolve. This is only present if this is a resolution request for - // an HTLC on our commitment transaction. + // to resolve. It is present for an HTLC on our commitment transaction, + // and for an HTLC on a revoked commitment of the remote party whose + // revocation carried their aux sig for it. In both cases it covers + // the one second-level path the HTLC has on the commitment it sits + // on: success for an HTLC incoming to the commitment's owner, timeout + // for one they offered. AuxSig []byte // SignDetails is the sign details for the second-level HTLC. This may @@ -65,6 +69,15 @@ type ResolutionReq struct { // only set if this is a resolution request for an HTLC. HtlcID fn.Option[input.HtlcIndex] + // HtlcIncoming states the direction of the HTLC that we are trying to + // resolve, from our point of view: true if we received it, false if + // we offered it. It is set for the HTLC resolutions of a breach. + // There the witness type of a second-level revocation no longer tells + // the direction, and the HTLC ID alone does not identify the HTLC: + // both parties count the HTLCs they offer from zero, so an incoming + // and an outgoing HTLC regularly share an ID. + HtlcIncoming fn.Option[bool] + // HtlcAmt is the amount of the HTLC that we are trying to resolve. HtlcAmt btcutil.Amount @@ -117,6 +130,23 @@ type ResolutionReq struct { // AuxSigDesc is an optional field that contains additional information // needed to sweep second level HTLCs. AuxSigDesc fn.Option[AuxSigDesc] + + // SecondLevel carries the on-chain context for a just-confirmed + // second-level HTLC tx. It is set only when resolving a + // TaprootHtlcSecondLevelRevoke so the resolver can re-anchor proofs + // to the second-level tx rather than the commitment tx. + SecondLevel fn.Option[SecondLevelInfo] +} + +// SecondLevelInfo carries the on-chain context for a second-level HTLC +// transaction. The fields are derived from the on-chain confirmation of +// the second-level tx and travel together as one inter-related unit. +type SecondLevelInfo struct { + // Tx is the confirmed second-level HTLC transaction. + Tx *wire.MsgTx + + // BlockHeight is the block height at which Tx was confirmed. + BlockHeight uint32 } // AuxContractResolver is an interface that is used to resolve contracts that diff --git a/lnwallet/aux_signer.go b/lnwallet/aux_signer.go index dfcb95b5ced..c22df7acb26 100644 --- a/lnwallet/aux_signer.go +++ b/lnwallet/aux_signer.go @@ -208,7 +208,9 @@ type BaseAuxJob struct { HTLC AuxHtlcDescriptor // Incoming is a boolean that indicates if the HTLC is incoming or - // outgoing. + // outgoing from the LOCAL party's perspective. This is used with + // WhoseCommit to determine the correct HTLC script variant + // (sender vs receiver). Incoming bool // CommitBlob is the commitment transaction blob that contains the aux @@ -218,6 +220,16 @@ type BaseAuxJob struct { // HtlcLeaf is the aux tap leaf that corresponds to the HTLC being // signed/verified. HtlcLeaf input.AuxTapLeaf + + // WhoseCommit indicates which party's commitment transaction the + // second-level HTLC belongs to. + WhoseCommit lntypes.ChannelParty + + // HtlcTimeout, if set, overrides the timeout logic in + // generateHtlcSignature and verifyHtlcSignature. When nil, + // the timeout is derived from Incoming (the normal CommitSig + // convention). When set, it is used directly. + HtlcTimeout fn.Option[uint32] } // AuxSigJob is a struct that contains all the information needed to sign an @@ -238,10 +250,24 @@ type AuxSigJob struct { Cancel <-chan struct{} } -// NewAuxSigJob creates a new AuxSigJob. +// NewAuxSigJob creates a new AuxSigJob. The whoseCommit parameter indicates +// which party's commitment the HTLC belongs to. +// +// HtlcTimeout is set explicitly to the CommitSig-time convention (an +// incoming HTLC signs the counterparty's timeout tx, which carries the CLTV; +// an outgoing HTLC signs their success tx, which has no locktime) so that +// the aux signer never has to re-derive it from the direction. Callers with +// a different convention (the revocation sign path, which signs the HTLC +// paths of our own commitment) override the field after construction. func NewAuxSigJob(sigJob SignJob, keyRing CommitmentKeyRing, incoming bool, htlc AuxHtlcDescriptor, commitBlob fn.Option[tlv.Blob], - htlcLeaf input.AuxTapLeaf, cancelChan <-chan struct{}) AuxSigJob { + htlcLeaf input.AuxTapLeaf, whoseCommit lntypes.ChannelParty, + cancelChan <-chan struct{}) AuxSigJob { + + htlcTimeout := fn.None[uint32]() + if incoming { + htlcTimeout = fn.Some(htlc.Timeout) + } return AuxSigJob{ SignDesc: sigJob.SignDesc, @@ -252,6 +278,8 @@ func NewAuxSigJob(sigJob SignJob, keyRing CommitmentKeyRing, incoming bool, Incoming: incoming, CommitBlob: commitBlob, HtlcLeaf: htlcLeaf, + WhoseCommit: whoseCommit, + HtlcTimeout: htlcTimeout, }, Resp: make(chan AuxSigJobResp, 1), Cancel: cancelChan, @@ -283,19 +311,34 @@ type AuxVerifyJob struct { BaseAuxJob } -// NewAuxVerifyJob creates a new AuxVerifyJob. +// NewAuxVerifyJob creates a new AuxVerifyJob for a signature the remote party +// sent for a second-level HTLC of our own commitment, which is what +// WhoseCommit is set to. +// +// HtlcTimeout is set explicitly to the CommitSig-time convention: on our +// local commitment an outgoing HTLC's signature covers our timeout tx +// (which carries the CLTV), while an incoming HTLC's signature covers our +// success tx (no locktime). Callers with a different convention (the +// revocation verify path) override the field after construction. func NewAuxVerifyJob(sig fn.Option[tlv.Blob], keyRing CommitmentKeyRing, incoming bool, htlc AuxHtlcDescriptor, commitBlob fn.Option[tlv.Blob], htlcLeaf input.AuxTapLeaf) AuxVerifyJob { + htlcTimeout := fn.None[uint32]() + if !incoming { + htlcTimeout = fn.Some(htlc.Timeout) + } + return AuxVerifyJob{ SigBlob: sig, BaseAuxJob: BaseAuxJob{ - KeyRing: keyRing, - HTLC: htlc, - Incoming: incoming, - CommitBlob: commitBlob, - HtlcLeaf: htlcLeaf, + KeyRing: keyRing, + HTLC: htlc, + Incoming: incoming, + CommitBlob: commitBlob, + HtlcLeaf: htlcLeaf, + WhoseCommit: lntypes.Local, + HtlcTimeout: htlcTimeout, }, } } diff --git a/lnwallet/breach_aux_retribution_test.go b/lnwallet/breach_aux_retribution_test.go new file mode 100644 index 00000000000..117d722db86 --- /dev/null +++ b/lnwallet/breach_aux_retribution_test.go @@ -0,0 +1,232 @@ +package lnwallet + +import ( + "errors" + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/lightningnetwork/lnd/channeldb" + "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/lnwire" + "github.com/lightningnetwork/lnd/tlv" + "github.com/stretchr/testify/require" +) + +// recordingAuxResolver is an AuxContractResolver that records the requests +// it receives and answers them with a canned blob or error. +type recordingAuxResolver struct { + reqs []ResolutionReq + blob tlv.Blob + err error +} + +// ResolveContract records the request and returns the canned answer. +func (r *recordingAuxResolver) ResolveContract( + req ResolutionReq) fn.Result[tlv.Blob] { + + r.reqs = append(r.reqs, req) + if r.err != nil { + return fn.Err[tlv.Blob](r.err) + } + + return fn.Ok(r.blob) +} + +// newAuxBreachHtlcEntry returns the revocation log entry of an HTLC on an aux +// channel, with the given custom records stored for it. +func newAuxBreachHtlcEntry(t *testing.T, incoming bool, htlcIndex uint64, + records lnwire.CustomRecords) *channeldb.HTLCEntry { + + t.Helper() + + htlc := &channeldb.HTLCEntry{ + Amt: tlv.NewRecordT[tlv.TlvType4]( + tlv.NewBigSizeT(btcutil.Amount(20_000)), + ), + Incoming: tlv.NewPrimitiveRecord[tlv.TlvType3](incoming), + OutputIndex: tlv.NewPrimitiveRecord[tlv.TlvType2, uint16](1), + HtlcIndex: tlv.SomeRecordT( + tlv.NewRecordT[tlv.TlvType6]( + tlv.NewBigSizeT(htlcIndex), + ), + ), + } + + if len(records) > 0 { + blob, err := records.Serialize() + require.NoError(t, err) + + htlc.CustomBlob = tlv.SomeRecordT( + tlv.NewPrimitiveRecord[tlv.TlvType5](blob), + ) + } + + return htlc +} + +// newAuxBreachTestChannel creates a custom (tapscript root) channel and the +// dummy parameters createHtlcRetribution takes. +func newAuxBreachTestChannel(t *testing.T) (*LightningChannel, + *btcec.PrivateKey) { + + t.Helper() + + chanType := channeldb.SimpleTaprootFeatureBit | + channeldb.TapscriptRootBit + + aliceChannel, _, err := CreateTestChannels(t, chanType) + require.NoError(t, err) + + dummyPrivate, _ := btcec.PrivKeyFromBytes([]byte{1}) + + return aliceChannel, dummyPrivate +} + +// TestCreateHtlcRetributionAuxDirection asserts that the resolution request +// of a breached HTLC on an aux channel states the HTLC's direction, both in +// the request sent to the aux resolver and in the template kept for a later +// second-level resolution. The HTLC index alone does not identify the HTLC, +// as both parties count the HTLCs they offer from zero. +func TestCreateHtlcRetributionAuxDirection(t *testing.T) { + t.Parallel() + + aliceChannel, dummyPrivate := newAuxBreachTestChannel(t) + chanState := aliceChannel.channelState + leaseExpiry, keyRing, commitHash := deriveDummyRetributionParams( + chanState, + ) + + for _, incoming := range []bool{true, false} { + resolver := &recordingAuxResolver{blob: tlv.Blob{0x01}} + htlc := newAuxBreachHtlcEntry(t, incoming, 0, nil) + + hr, err := createHtlcRetribution( + chanState, keyRing, commitHash, dummyPrivate, + leaseExpiry, htlc, fn.None[CommitAuxLeaves](), nil, + fn.Some[AuxContractResolver](resolver), nil, 0, + ) + require.NoError(t, err) + + // Both HTLCs share index 0. Only the direction tells them + // apart. + require.Len(t, resolver.reqs, 1) + require.Equal( + t, fn.Some(incoming), resolver.reqs[0].HtlcIncoming, + ) + require.Equal( + t, fn.Some[uint64](0), resolver.reqs[0].HtlcID, + ) + + require.NotNil(t, hr.ResolveReq) + require.Equal(t, fn.Some(incoming), hr.ResolveReq.HtlcIncoming) + require.Equal(t, incoming, hr.IsIncoming) + require.Equal(t, fn.Some(tlv.Blob{0x01}), hr.ResolutionBlob) + } +} + +// TestCreateHtlcRetributionAuxResolveFailure asserts that a failure of the +// aux resolver for one breached HTLC does not fail the retribution. Nothing +// retries a breach handoff that errors out, so one HTLC the resolver cannot +// handle would otherwise leave the commitment outputs and every other HTLC +// of the revoked state unpunished. The HTLC is instead handed over without a +// blob, with its template intact for a later second-level resolution. +func TestCreateHtlcRetributionAuxResolveFailure(t *testing.T) { + t.Parallel() + + aliceChannel, dummyPrivate := newAuxBreachTestChannel(t) + chanState := aliceChannel.channelState + leaseExpiry, keyRing, commitHash := deriveDummyRetributionParams( + chanState, + ) + + resolver := &recordingAuxResolver{err: errors.New("cannot resolve")} + htlc := newAuxBreachHtlcEntry(t, true, 3, nil) + + hr, err := createHtlcRetribution( + chanState, keyRing, commitHash, dummyPrivate, leaseExpiry, + htlc, fn.None[CommitAuxLeaves](), nil, + fn.Some[AuxContractResolver](resolver), nil, 0, + ) + require.NoError(t, err) + require.Len(t, resolver.reqs, 1) + + // The HTLC is still part of the retribution, just without a blob. + require.NotNil(t, hr.SignDesc.Output) + require.EqualValues(t, 20_000, hr.SignDesc.Output.Value) + require.True(t, hr.ResolutionBlob.IsNone()) + require.NotNil(t, hr.ResolveReq) +} + +// TestAuxSigDescFromHTLCBlobRevocationSigOnly asserts that the aux sig handed +// to the aux resolver for a breached HTLC is the remote party's revocation +// aux sig and nothing else. The CommitSig aux sig that can sit in the same +// custom records covers the second-level HTLC of our own commitment, which is +// a different transaction: passing it on would make the resolver build a +// proof around a sig that can never verify, instead of resolving the HTLC +// without one. +func TestAuxSigDescFromHTLCBlobRevocationSigOnly(t *testing.T) { + t.Parallel() + + aliceChannel, _ := newAuxBreachTestChannel(t) + chanState := aliceChannel.channelState + _, keyRing, _ := deriveDummyRetributionParams(chanState) + + revSigType := revocationAuxSigType + commitSigType := uint64(htlcCustomSigType.TypeVal()) + revSig := []byte{0x01, 0x02} + commitSig := []byte{0x03, 0x04} + + testCases := []struct { + name string + records lnwire.CustomRecords + want []byte + }{{ + name: "no custom records", + }, { + name: "revocation sig", + records: lnwire.CustomRecords{ + revSigType: revSig, + }, + want: revSig, + }, { + name: "revocation sig next to a commit sig", + records: lnwire.CustomRecords{ + revSigType: revSig, + commitSigType: commitSig, + }, + want: revSig, + }, { + // A state that was revoked without revocation aux sigs must + // not fall back to the sig made for our own commitment. + name: "commit sig only", + records: lnwire.CustomRecords{ + commitSigType: commitSig, + }, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + htlc := newAuxBreachHtlcEntry(t, true, 0, tc.records) + desc := auxSigDescFromHTLCBlob(htlc, chanState, keyRing) + + if tc.want == nil { + require.True(t, desc.IsNone()) + + return + } + + auxSigDesc, err := desc.UnwrapOrErr( + errors.New("no aux sig desc"), + ) + require.NoError(t, err) + require.Equal(t, tc.want, auxSigDesc.AuxSig) + require.Equal( + t, keyRing.LocalHtlcKeyTweak, + auxSigDesc.SignDetails.SignDesc.SingleTweak, + ) + }) + } +} diff --git a/lnwallet/btcwallet/psbt.go b/lnwallet/btcwallet/psbt.go index df41336ec49..d19161012c2 100644 --- a/lnwallet/btcwallet/psbt.go +++ b/lnwallet/btcwallet/psbt.go @@ -543,26 +543,45 @@ func prepareScriptsV0(in *psbt.PInput) []byte { func maybeTweakPrivKeyPsbt(unknowns []*psbt.Unknown, privKey *btcec.PrivateKey) *btcec.PrivateKey { - // There can be other custom/unknown keys in a PSBT that we just ignore. - // Key tweaking is optional and only one tweak (single _or_ double) can - // ever be applied (at least for any use cases described in the BOLT - // spec). + // There can be other custom/unknown keys in a PSBT that we just + // ignore. Key tweaking is optional. Historically only one tweak + // (single _or_ double) was ever applied, but second-level HTLC + // signing for aux (taproot asset) channels applies both: the + // revocation (double) tweak and the per-HTLC-index (single) tweak. + // This must mirror maybeTweakPrivKey in signer.go: collect both + // tweaks first, then apply double before single, so the remote + // signer PSBT path derives the same key as the local signing path. + var singleTweak, doubleTweak []byte for _, u := range unknowns { if bytes.Equal(u.Key, PsbtKeyTypeInputSignatureTweakSingle) { - return input.TweakPrivKey(privKey, u.Value) + singleTweak = u.Value } if bytes.Equal(u.Key, PsbtKeyTypeInputSignatureTweakDouble) { - doubleTweakKey, _ := btcec.PrivKeyFromBytes( - u.Value, - ) - return input.DeriveRevocationPrivKey( - privKey, doubleTweakKey, - ) + doubleTweak = u.Value } } - return privKey + switch { + case doubleTweak != nil && singleTweak != nil: + doubleTweakKey, _ := btcec.PrivKeyFromBytes(doubleTweak) + tweaked := input.DeriveRevocationPrivKey( + privKey, doubleTweakKey, + ) + + return input.TweakPrivKey(tweaked, singleTweak) + + case singleTweak != nil: + return input.TweakPrivKey(privKey, singleTweak) + + case doubleTweak != nil: + doubleTweakKey, _ := btcec.PrivKeyFromBytes(doubleTweak) + + return input.DeriveRevocationPrivKey(privKey, doubleTweakKey) + + default: + return privKey + } } // FinalizePsbt expects a partial transaction with all inputs and outputs fully diff --git a/lnwallet/btcwallet/psbt_test.go b/lnwallet/btcwallet/psbt_test.go index fe232512649..ea629244006 100644 --- a/lnwallet/btcwallet/psbt_test.go +++ b/lnwallet/btcwallet/psbt_test.go @@ -625,3 +625,84 @@ func TestBip32DerivationFromAddress(t *testing.T) { require.Equal(t, tc.expectedBip32Path, trD.Bip32Path) } } + +// TestMaybeTweakPrivKeyPsbt asserts that the PSBT signing path derives the +// same tweaked key as the direct signing path (maybeTweakPrivKey in +// signer.go) for every tweak combination, regardless of the order in which +// the tweak unknowns appear in the PSBT input. Second-level HTLC signing for +// aux (taproot asset) channels attaches both the revocation (double) tweak +// and the per-HTLC-index (single) tweak, and the remote signer receives them +// via these unknowns. +func TestMaybeTweakPrivKeyPsbt(t *testing.T) { + privKeyBytes, err := hex.DecodeString( + "e68abc8e2a7a5b9f0e4a3c7d8b9e6f5" + + "a4b3c2d1e0f9e8d7c6b5a4938271605", + ) + require.NoError(t, err) + privKey, _ := btcec.PrivKeyFromBytes(privKeyBytes) + + singleTweakBytes, err := hex.DecodeString( + "1234567890abcdef1234567890abcdef" + + "1234567890abcdef1234567890abcdef", + ) + require.NoError(t, err) + + doubleTweakBytes, err := hex.DecodeString( + "fedcba0987654321fedcba0987654321" + + "fedcba0987654321fedcba0987654321", + ) + require.NoError(t, err) + doubleTweak, _ := btcec.PrivKeyFromBytes(doubleTweakBytes) + + singleUnknown := &psbt.Unknown{ + Key: PsbtKeyTypeInputSignatureTweakSingle, + Value: singleTweakBytes, + } + doubleUnknown := &psbt.Unknown{ + Key: PsbtKeyTypeInputSignatureTweakDouble, + Value: doubleTweakBytes, + } + + // The expected combined derivation: double (revocation) tweak first, + // then the single (HTLC index) tweak, matching maybeTweakPrivKey. + combined := input.TweakPrivKey( + input.DeriveRevocationPrivKey(privKey, doubleTweak), + singleTweakBytes, + ) + + testCases := []struct { + name string + unknowns []*psbt.Unknown + expected *btcec.PrivateKey + }{{ + name: "no tweaks", + unknowns: nil, + expected: privKey, + }, { + name: "single tweak only", + unknowns: []*psbt.Unknown{singleUnknown}, + expected: input.TweakPrivKey(privKey, singleTweakBytes), + }, { + name: "double tweak only", + unknowns: []*psbt.Unknown{doubleUnknown}, + expected: input.DeriveRevocationPrivKey(privKey, doubleTweak), + }, { + name: "both tweaks, single first", + unknowns: []*psbt.Unknown{singleUnknown, doubleUnknown}, + expected: combined, + }, { + name: "both tweaks, double first", + unknowns: []*psbt.Unknown{doubleUnknown, singleUnknown}, + expected: combined, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + result := maybeTweakPrivKeyPsbt(tc.unknowns, privKey) + require.Equal( + t, tc.expected.Serialize(), + result.Serialize(), + ) + }) + } +} diff --git a/lnwallet/channel.go b/lnwallet/channel.go index c59c7eaa959..35f95a6cc56 100644 --- a/lnwallet/channel.go +++ b/lnwallet/channel.go @@ -2266,6 +2266,12 @@ type HtlcRetribution struct { // ResolutionBlob is a blob used for aux channels that permits a // spender of this output to claim all funds. ResolutionBlob fn.Option[tlv.Blob] + + // ResolveReq is the resolution request template used to generate + // the ResolutionBlob. It is preserved so the breach arbiter can + // re-resolve with a different witness type when an HTLC is taken + // to the second level. + ResolveReq *ResolutionReq } // BreachRetribution contains all the data necessary to bring a channel @@ -2409,7 +2415,14 @@ func NewBreachRetribution(chanState *chanstate.OpenChannel, stateNum uint64, auxResult, err := fn.MapOptionZ( leafStore, func(s AuxLeafStore) fn.Result[CommitDiffAuxResult] { - return s.FetchLeavesFromRevocation(revokedLog) + return s.FetchLeavesFromRevocation( + RevocationLeavesReq{ + Revocation: revokedLog, + ChanState: NewAuxChanState(chanState), + Keys: *keyRing, + CommitTx: spendTx, + }, + ) }, ).Unpack() if err != nil { @@ -2459,6 +2472,7 @@ func NewBreachRetribution(chanState *chanstate.OpenChannel, stateNum uint64, br, ourAmt, theirAmt, err = createBreachRetribution( revokedLog, spendTx, chanState, keyRing, commitmentSecret, leaseExpiry, auxResult.AuxLeaves, + auxResolver, breachHeight, ) if err != nil { return nil, err @@ -2473,7 +2487,8 @@ func NewBreachRetribution(chanState *chanstate.OpenChannel, stateNum uint64, // are confident that no legacy format is in use. br, ourAmt, theirAmt, err = createBreachRetributionLegacy( revokedLogLegacy, chanState, keyRing, commitmentSecret, - ourScript, theirScript, leaseExpiry, auxSigner, + ourScript, theirScript, leaseExpiry, auxResolver, + auxSigner, breachHeight, ) if err != nil { return nil, err @@ -2658,13 +2673,59 @@ func NewBreachRetribution(chanState *chanstate.OpenChannel, stateNum uint64, return br, nil } +// auxSigDescFromHTLCBlob extracts the AuxSigDesc for a breached HTLC from its +// custom-records blob, if present. The sig is the remote party's +// revocation-path aux sig (revocationAuxSigType), which it sent in the +// RevokeAndAck for exactly this state and which we verified against the +// second-level HTLC of its commitment before accepting the revocation. +// +// No other sig will do. In particular the CommitSig aux sig that may sit in +// the same records (htlcCustomSigType) is the one the remote party sent for +// the second-level HTLC of OUR commitment, a different transaction. Passing +// it on would make the aux resolver build a proof around a sig that cannot +// verify, where reporting no sig lets it fall back to resolving the HTLC +// without one. So for a state that was revoked without revocation aux sigs +// this returns None. +func auxSigDescFromHTLCBlob(htlc *channeldb.HTLCEntry, + chanState *chanstate.OpenChannel, + keyRing *CommitmentKeyRing) fn.Option[AuxSigDesc] { + + var auxSigDesc fn.Option[AuxSigDesc] + htlc.CustomBlob.WhenSome(func(r tlv.RecordT[tlv.TlvType5, tlv.Blob]) { + customRecords, err := lnwire.ParseCustomRecords(r.Val) + if err != nil { + return + } + + auxSig := customRecords[revocationAuxSigType] + if len(auxSig) == 0 { + return + } + + // Construct the sign desc for the second-level tx proof. + sd := input.SignDescriptor{ + KeyDesc: chanState.LocalChanCfg.HtlcBasePoint, + SingleTweak: keyRing.LocalHtlcKeyTweak, + SignMethod: input.TaprootScriptSpendSignMethod, + } + auxSigDesc = fn.Some(AuxSigDesc{ + AuxSig: auxSig, + SignDetails: input.SignDetails{SignDesc: sd}, + }) + }) + + return auxSigDesc +} + // createHtlcRetribution is a helper function to construct an HtlcRetribution // based on the passed params. func createHtlcRetribution(chanState *chanstate.OpenChannel, keyRing *CommitmentKeyRing, commitHash chainhash.Hash, commitmentSecret *btcec.PrivateKey, leaseExpiry uint32, - htlc *channeldb.HTLCEntry, - auxLeaves fn.Option[CommitAuxLeaves]) (HtlcRetribution, error) { + htlc *channeldb.HTLCEntry, auxLeaves fn.Option[CommitAuxLeaves], + spendTx *wire.MsgTx, auxResolver fn.Option[AuxContractResolver], + revokedLog *channeldb.RevocationLog, + breachHeight uint32) (HtlcRetribution, error) { var emptyRetribution HtlcRetribution @@ -2767,6 +2828,106 @@ func createHtlcRetribution(chanState *chanstate.OpenChannel, copy(secondLevelTapTweak[:], scriptTree.TapTweak()) } + // Determine the witness type for this HTLC revocation based on the + // channel type and whether it's incoming or outgoing. + var htlcWitnessType input.StandardWitnessType + isTaproot := chanState.ChanType.IsTaproot() + switch { + case isTaproot && htlc.Incoming.Val: + htlcWitnessType = input.TaprootHtlcAcceptedRevoke + + case isTaproot && !htlc.Incoming.Val: + htlcWitnessType = input.TaprootHtlcOfferedRevoke + + case !isTaproot && htlc.Incoming.Val: + htlcWitnessType = input.HtlcAcceptedRevoke + + case !isTaproot && !htlc.Incoming.Val: + htlcWitnessType = input.HtlcOfferedRevoke + } + + // Aux resolution data (the resolution blob and the preserved + // ResolveReq template used by the breach arbiter for second-level + // re-resolution) is exclusively an aux/custom channel concern. + // Custom channels are precisely the taproot channels that carry a + // tapscript root, so we gate on that here rather than on plain + // IsTaproot(): this guarantees non-custom taproot channels (e.g. + // simple taproot) get a nil ResolveReq and empty blob, leaving + // their breach handling byte-for-byte unchanged. + var resolutionBlob fn.Option[tlv.Blob] + var savedResolveReq *ResolutionReq + isAuxChannel := chanState.ChanType.HasTapscriptRoot() + if isAuxChannel { + htlcIDOpt := fn.MapOption( + func(v tlv.BigSizeT[uint64]) input.HtlcIndex { + return v.Int() + }, + )(htlc.HtlcIndex.ValOpt()) + + cs := chanState + resolveReq := ResolutionReq{ + ChanPoint: cs.FundingOutpoint, + ChanType: cs.ChanType, + ShortChanID: cs.ShortChanID(), + Initiator: cs.IsInitiator, + FundingBlob: cs.CustomBlob, + Type: htlcWitnessType, + CloseType: Breach, + CommitTx: spendTx, + CommitTxBlockHeight: breachHeight, + SignDesc: signDesc, + KeyRing: keyRing, + CsvDelay: theirDelay, + CommitFee: cs.RemoteCommitment.CommitFee, + HtlcAmt: htlc.Amt.Val.Int(), + PayHash: fn.Some( + [32]byte(htlc.RHash.Val), + ), + HtlcID: htlcIDOpt, + HtlcIncoming: fn.Some(htlc.Incoming.Val), + CltvDelay: fn.Some(htlc.RefundTimeout.Val), + } + + resolveReq.AuxSigDesc = auxSigDescFromHTLCBlob( + htlc, chanState, keyRing, + ) + if revokedLog != nil { + resolveReq.CommitBlob = revokedLog.CustomBlob.ValOpt() + } + + resolveBlob := fn.MapOptionZ( + auxResolver, + func(a AuxContractResolver) fn.Result[tlv.Blob] { + return a.ResolveContract(resolveReq) + }, + ) + + // A failure to resolve one HTLC must not cost us the whole + // retribution: the commitment outputs and every other HTLC + // are still ours to claim, and nothing retries a handoff that + // errors out. So this HTLC is degraded to a plain sweep of + // its BTC value, without a blob, and the error is surfaced. + if err := resolveBlob.Err(); err != nil { + walletLog.Errorf("Unable to aux resolve breached "+ + "HTLC(id=%v, incoming=%v) of "+ + "ChannelPoint(%v), sweeping it without aux "+ + "resolution: %v", + htlcIDOpt, htlc.Incoming.Val, + cs.FundingOutpoint, err) + } else { + resolutionBlob = resolveBlob.OkToSome() + } + + // Save the resolve request template so the breach arbiter + // can re-resolve when an HTLC is taken to second level. + // We deep-copy the key ring to prevent any potential + // mutation from affecting the saved request. + keyRingCopy := *keyRing + resolveReqCopy := resolveReq + resolveReqCopy.KeyRing = &keyRingCopy + savedResolveReq = &resolveReqCopy + } + return HtlcRetribution{ SignDesc: signDesc, OutPoint: wire.OutPoint{ @@ -2776,6 +2937,8 @@ func createHtlcRetribution(chanState *chanstate.OpenChannel, SecondLevelWitnessScript: secondLevelWitnessScript, IsIncoming: htlc.Incoming.Val, SecondLevelTapTweak: secondLevelTapTweak, + ResolutionBlob: resolutionBlob, + ResolveReq: savedResolveReq, }, nil } @@ -2789,9 +2952,9 @@ func createHtlcRetribution(chanState *chanstate.OpenChannel, func createBreachRetribution(revokedLog *channeldb.RevocationLog, spendTx *wire.MsgTx, chanState *chanstate.OpenChannel, keyRing *CommitmentKeyRing, commitmentSecret *btcec.PrivateKey, - leaseExpiry uint32, - auxLeaves fn.Option[CommitAuxLeaves]) (*BreachRetribution, int64, int64, - error) { + leaseExpiry uint32, auxLeaves fn.Option[CommitAuxLeaves], + auxResolver fn.Option[AuxContractResolver], + breachHeight uint32) (*BreachRetribution, int64, int64, error) { commitHash := revokedLog.CommitTxHash @@ -2800,7 +2963,8 @@ func createBreachRetribution(revokedLog *channeldb.RevocationLog, for i, htlc := range revokedLog.HTLCEntries { hr, err := createHtlcRetribution( chanState, keyRing, commitHash.Val, - commitmentSecret, leaseExpiry, htlc, auxLeaves, + commitmentSecret, leaseExpiry, htlc, auxLeaves, spendTx, + auxResolver, revokedLog, breachHeight, ) if err != nil { return nil, 0, 0, err @@ -2907,8 +3071,9 @@ func createBreachRetributionLegacy(revokedLog *channeldb.ChannelCommitment, chanState *chanstate.OpenChannel, keyRing *CommitmentKeyRing, commitmentSecret *btcec.PrivateKey, ourScript, theirScript input.ScriptDescriptor, leaseExpiry uint32, - auxSigner fn.Option[AuxSigner]) (*BreachRetribution, int64, int64, - error) { + auxResolver fn.Option[AuxContractResolver], + auxSigner fn.Option[AuxSigner], + breachHeight uint32) (*BreachRetribution, int64, int64, error) { commitHash := revokedLog.CommitTx.TxHash() ourOutpoint := wire.OutPoint{ @@ -2985,6 +3150,7 @@ func createBreachRetributionLegacy(revokedLog *channeldb.ChannelCommitment, chanState, keyRing, commitHash, commitmentSecret, leaseExpiry, entry, fn.None[CommitAuxLeaves](), + revokedLog.CommitTx, auxResolver, nil, breachHeight, ) if err != nil { return nil, 0, 0, err @@ -3780,7 +3946,8 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, auxSigBatch = append(auxSigBatch, NewAuxSigJob( sigJob, *keyRing, true, newAuxHtlcDescriptor(&htlc), - remoteCommitView.customBlob, auxLeaf, cancelChan, + remoteCommitView.customBlob, auxLeaf, + lntypes.Remote, cancelChan, )) } for _, htlc := range remoteCommitView.outgoingHTLCs { @@ -3863,13 +4030,952 @@ func genRemoteHtlcSigJobs(keyRing *CommitmentKeyRing, auxSigBatch = append(auxSigBatch, NewAuxSigJob( sigJob, *keyRing, false, newAuxHtlcDescriptor(&htlc), - remoteCommitView.customBlob, auxLeaf, cancelChan, + remoteCommitView.customBlob, auxLeaf, + lntypes.Remote, cancelChan, )) } return sigBatch, auxSigBatch, cancelChan, nil } +// revocationAuxSigType is the TLV type used to store the remote party's +// aux signatures for their own second-level HTLCs in the HTLC +// CustomRecords within the revocation log. We use a different type than +// htlcCustomSigType to avoid collisions with the sigs the remote sent +// for OUR local commitment (stored during genHtlcSigValidationJobs). The +// number was drawn at random from the custom range, as the HTLC custom +// records are shared with every other user of that range. +const revocationAuxSigType uint64 = 884256149 + +// revokeAndAckAuxSigType is the TLV type of the custom record of a +// revoke_and_ack that carries the packed revocation aux sigs. The number was +// drawn at random from the custom range to keep clear of other users of the +// custom records of this message. +const revokeAndAckAuxSigType uint64 = 3496008566 + +// revocationAuxSigKey identifies an HTLC on a revoked commitment. HTLC +// indexes are per-offerer counters that both start at zero, so an index alone +// is ambiguous: a commitment routinely carries an HTLC offered by each side +// under the same index. The direction disambiguates them. +type revocationAuxSigKey struct { + // signerIncoming is true if the HTLC is incoming to the party that + // revokes the commitment and signs the entry, i.e. it was offered by + // the party receiving the revocation. + signerIncoming bool + + // htlcIndex is the index of the HTLC in its offerer's counter. + htlcIndex uint64 +} + +// revocationAuxSigEntry holds a single HTLC's revocation AuxSig, tagged with +// the HTLC's direction and index so the receiver can match sigs to HTLCs +// unambiguously regardless of HTLC ordering differences between the local +// and remote views. +// +// The sig covers the one second-level path the HTLC has on the signer's own +// commitment: HTLC-success for an HTLC incoming to the signer, HTLC-timeout +// for one the signer offered. It is empty for an HTLC that carries no aux +// outputs. +// +// On the wire, each entry is encoded as a TLV stream with three records +// (HtlcIndex / Sig / SignerIncoming). The full blob is a BigSize-prefixed +// count followed by length-prefixed entry streams: TLV streams aren't +// natively self-delimiting at the list level, so we wrap each entry with +// its byte length so the decoder can frame the next entry. +type revocationAuxSigEntry struct { + revocationAuxSigKey + + sig []byte +} + +const ( + // revAuxSigIndexType is the TLV type of an entry's HTLC index. + revAuxSigIndexType tlv.Type = 0 + + // revAuxSigSigType is the TLV type of an entry's aux signature. + revAuxSigSigType tlv.Type = 1 + + // revAuxSigIncomingType is the TLV type of an entry's direction. + revAuxSigIncomingType tlv.Type = 2 +) + +// encode writes the entry as a TLV stream. +func (e *revocationAuxSigEntry) encode(w io.Writer) error { + htlcIdx := e.htlcIndex + sig := e.sig + + var incoming uint8 + if e.signerIncoming { + incoming = 1 + } + + stream, err := tlv.NewStream( + tlv.MakePrimitiveRecord(revAuxSigIndexType, &htlcIdx), + tlv.MakePrimitiveRecord(revAuxSigSigType, &sig), + tlv.MakePrimitiveRecord(revAuxSigIncomingType, &incoming), + ) + if err != nil { + return err + } + + return stream.Encode(w) +} + +// decode reads the entry from a TLV stream. The HTLC index and the direction +// are mandatory: without either the entry cannot be attributed to an HTLC. +func (e *revocationAuxSigEntry) decode(r io.Reader) error { + var incoming uint8 + + stream, err := tlv.NewStream( + tlv.MakePrimitiveRecord(revAuxSigIndexType, &e.htlcIndex), + tlv.MakePrimitiveRecord(revAuxSigSigType, &e.sig), + tlv.MakePrimitiveRecord(revAuxSigIncomingType, &incoming), + ) + if err != nil { + return err + } + + parsed, err := stream.DecodeWithParsedTypesP2P(r) + if err != nil { + return err + } + + if _, ok := parsed[revAuxSigIndexType]; !ok { + return errors.New("missing HTLC index") + } + if _, ok := parsed[revAuxSigIncomingType]; !ok { + return errors.New("missing HTLC direction") + } + if incoming > 1 { + return fmt.Errorf("invalid HTLC direction %d", incoming) + } + e.signerIncoming = incoming == 1 + + return nil +} + +// packRevocationAuxSigs encodes a list of tagged HTLC sigs into a single +// blob. Format: BigSize count + repeated [BigSize entryLen + +// entry-TLV-stream] records. Each entry's TLV stream carries records 0 +// (HtlcIndex), 1 (Sig), 2 (SignerIncoming). +func packRevocationAuxSigs(entries []revocationAuxSigEntry) ([]byte, error) { + var ( + buf bytes.Buffer + scratch [8]byte + ) + + if err := tlv.WriteVarInt( + &buf, uint64(len(entries)), &scratch, + ); err != nil { + return nil, fmt.Errorf("write entry count: %w", err) + } + + for i := range entries { + var inner bytes.Buffer + if err := entries[i].encode(&inner); err != nil { + return nil, fmt.Errorf("encode entry %d: %w", i, err) + } + + if err := tlv.WriteVarInt( + &buf, uint64(inner.Len()), &scratch, + ); err != nil { + return nil, fmt.Errorf("write entry %d length: %w", + i, err) + } + if _, err := buf.Write(inner.Bytes()); err != nil { + return nil, fmt.Errorf("write entry %d bytes: %w", + i, err) + } + } + + return buf.Bytes(), nil +} + +// unpackRevocationAuxSigs decodes a blob produced by packRevocationAuxSigs +// into a map of HTLC (direction, index) to its entry. +// +// The blob comes from the remote peer, so nothing in it is trusted. The +// entry count is never used to size an allocation, every entry must consume +// exactly the length it declares, an HTLC may appear only once, and no bytes +// may follow the last entry. +func unpackRevocationAuxSigs( + blob []byte) (map[revocationAuxSigKey]revocationAuxSigEntry, error) { + + r := bytes.NewReader(blob) + var scratch [8]byte + + count, err := tlv.ReadVarInt(r, &scratch) + if err != nil { + return nil, fmt.Errorf("read entry count: %w", err) + } + + // Every entry takes at least one byte (its length prefix), so a count + // beyond what is left of the blob can only be a lie. + if count > uint64(r.Len()) { + return nil, fmt.Errorf("entry count %d exceeds the %d bytes "+ + "of entry data", count, r.Len()) + } + + result := make(map[revocationAuxSigKey]revocationAuxSigEntry) + for i := range count { + entryLen, err := tlv.ReadVarInt(r, &scratch) + if err != nil { + return nil, fmt.Errorf("read entry %d length: %w", + i, err) + } + if entryLen > uint64(r.Len()) { + return nil, fmt.Errorf("entry %d length %d exceeds "+ + "the %d bytes left", i, entryLen, r.Len()) + } + + // The entry is decoded from a view of exactly its declared + // length. The TLV decoder reads until that view is exhausted, + // so the entry can neither run into the next one nor leave + // undeclared bytes behind. + entryBytes := make([]byte, entryLen) + if _, err := io.ReadFull(r, entryBytes); err != nil { + return nil, fmt.Errorf("read entry %d: %w", i, err) + } + + var entry revocationAuxSigEntry + err = entry.decode(bytes.NewReader(entryBytes)) + if err != nil { + return nil, fmt.Errorf("decode entry %d: %w", i, err) + } + + if _, ok := result[entry.revocationAuxSigKey]; ok { + return nil, fmt.Errorf("duplicate entry for HTLC "+ + "index %d (signer incoming=%v)", + entry.htlcIndex, entry.signerIncoming) + } + result[entry.revocationAuxSigKey] = entry + } + + if r.Len() != 0 { + return nil, fmt.Errorf("%d trailing bytes after the last "+ + "entry", r.Len()) + } + + return result, nil +} + +// injectRevocationAuxSigs takes the packed aux sig blob from a RevokeAndAck +// and injects individual HTLC sigs into the remote commitment's HTLC entries. +// This must be called before AdvanceCommitChainTail so the sigs are persisted +// in the revocation log. +func (lc *LightningChannel) injectRevocationAuxSigs(auxSigBlob []byte) { + sigMap, err := unpackRevocationAuxSigs(auxSigBlob) + if err != nil { + lc.log.Warnf("Unable to unpack revocation aux sigs: %v", err) + return + } + + sigType := revocationAuxSigType + htlcs := lc.channelState.RemoteCommitment.Htlcs + for i := range htlcs { + // The HTLC's custom records originate from the peer's + // UpdateAddHTLC for the HTLCs it offered. Whatever sits under + // our record type there was not verified as a revocation sig, + // so it must never make it into the revocation log, where the + // breach code would later take it for one. + delete(htlcs[i].CustomRecords, sigType) + + // Match sigs to HTLCs by direction and HTLC index. An HTLC + // that is incoming to us was offered by us to the signer, so + // it is outgoing for the signer and vice versa. + entry, ok := sigMap[revocationAuxSigKey{ + signerIncoming: !htlcs[i].Incoming, + htlcIndex: htlcs[i].HtlcIndex, + }] + if !ok || len(entry.sig) == 0 { + continue + } + + if htlcs[i].CustomRecords == nil { + htlcs[i].CustomRecords = make(lnwire.CustomRecords) + } + htlcs[i].CustomRecords[sigType] = entry.sig + } +} + +// exchangesRevocationAuxSigs is the single gate deciding whether revocation +// AuxSigs are attached to the outgoing RevokeAndAck that revokes the given +// commitment, and verified on the incoming one. This is strictly a +// custom-channel feature, and the gate requires ALL of: +// +// 1. The channel type carries a tapscript root. Only the aux/custom (taproot +// asset) funding path ever sets TapscriptRootBit, so no vanilla lnd +// channel can pass this check. +// +// 2. An aux signer is attached to the channel. +// +// 3. The commitment being revoked was built with SigHashDefault second-level +// HTLCs (DeterministicHTLCs). The commitment already exists, so this +// reads the sighash recorded in its own custom blob. Both peers hold the +// same record for the same commitment, so they always agree on whether +// its revocation carries the signatures, even while the sighash type +// used for new commitments is changing. +// +// For every other channel this returns false: nothing is signed, no custom +// records are attached to or read from RevokeAndAck, and the message stays +// byte-identical to before this feature existed. +func (lc *LightningChannel) exchangesRevocationAuxSigs( + revoked *commitment) bool { + + // Explicit hard gate on the channel type. The sighash check below + // can only ever be true for tapscript-root channels anyway (see + // ResolveHtlcSigHashType), but checking it here first makes the + // custom-channel-only isolation locally auditable. + if !lc.channelState.ChanType.HasTapscriptRoot() { + return false + } + + if lc.auxSigner.IsNone() || revoked == nil { + return false + } + + return lc.commitSigHashDefault(revoked.customBlob) +} + +// revocationAuxVerifyJob builds the verification job for a single HTLC's +// revocation aux sig entry. +// +// The sig covers the HTLC's second-level path on the signer's own +// commitment. From OUR perspective the direction is mirrored: an HTLC that +// is incoming to us is outgoing for the signer, whose second-level path for +// it is the timeout, and an HTLC that is outgoing for us is incoming for the +// signer, whose second-level path for it is the success. +// +// So: our incoming -> signer's outgoing -> timeout path +// +// our outgoing -> signer's incoming -> success path +// +// A job is built even when the entry carries no sig: only the aux signer +// knows whether the HTLC carries aux outputs and therefore owes one, so it +// is the one to reject a missing sig. +func revocationAuxVerifyJob(sigEntry revocationAuxSigEntry, + htlc *paymentDescriptor, incoming bool, keyRing *CommitmentKeyRing, + commitBlob fn.Option[tlv.Blob], auxLeaf input.AuxTapLeaf) AuxVerifyJob { + + sigBlob := fn.None[tlv.Blob]() + if len(sigEntry.sig) > 0 { + sigBlob = fn.Some[tlv.Blob](sigEntry.sig) + } + + job := AuxVerifyJob{ + SigBlob: sigBlob, + BaseAuxJob: BaseAuxJob{ + OutputIndex: htlc.remoteOutputIndex, + KeyRing: *keyRing, + HTLC: newAuxHtlcDescriptor(htlc), + Incoming: incoming, + CommitBlob: commitBlob, + HtlcLeaf: auxLeaf, + WhoseCommit: lntypes.Remote, + }, + } + + // Our incoming is the signer's outgoing, which goes through the + // timeout path and needs the timeout. The success path does not. + if incoming { + job.HtlcTimeout = fn.Some(htlc.Timeout) + } + + return job +} + +// verifyRevocationAuxSigs verifies the aux sigs received in a RevokeAndAck +// message. It derives the same key ring that the breach-time code will use +// (DeriveCommitmentKeys with whoseCommit=Remote and our local configs) and +// verifies the signatures against the remote commitment's HTLCs. If the +// signatures don't verify now, they won't work at breach time either. +// +// The commitPoint must be the RemoteCurrentRevocation BEFORE it is rotated. +func (lc *LightningChannel) verifyRevocationAuxSigs( + auxSigBlob []byte, commitPoint *btcec.PublicKey) error { + + // Get the remote commitment view (about to be revoked). + remoteCommitView := lc.commitChains.Remote.tail() + + // Defense in depth: this must only ever run for aux/custom channels + // revoking a DeterministicHTLCs commitment (the caller already + // checks). + if !lc.exchangesRevocationAuxSigs(remoteCommitView) { + return nil + } + + // If there's no aux signer, nothing to verify. + if lc.auxSigner.IsNone() { + return nil + } + + auxSigner, _ := lc.auxSigner.UnwrapOrErr( + fmt.Errorf("no aux signer"), + ) + + // Unpack the tagged blob. An absent blob simply means zero entries: + // the per-HTLC loop below is what decides whether that is acceptable + // (all HTLCs dust or none at all) or a withheld signature (any + // non-dust HTLC present). + sigMap := make(map[revocationAuxSigKey]revocationAuxSigEntry) + if len(auxSigBlob) > 0 { + var err error + sigMap, err = unpackRevocationAuxSigs(auxSigBlob) + if err != nil { + return fmt.Errorf("unable to unpack revocation aux "+ + "sigs for verification: %w", err) + } + } + + numHTLCs := len(remoteCommitView.incomingHTLCs) + + len(remoteCommitView.outgoingHTLCs) + if numHTLCs == 0 { + return nil + } + + // Derive the key ring the same way the breach code does. + keyRing := DeriveCommitmentKeys( + commitPoint, lntypes.Remote, + lc.channelState.ChanType, + &lc.channelState.LocalChanCfg, + &lc.channelState.RemoteChanCfg, + ) + + chanState := lc.channelState + chanType := chanState.ChanType + remoteChanCfg := chanState.RemoteChanCfg + feePerKw := remoteCommitView.feePerKw + dustLimit := remoteChanCfg.DustLimit + + // The gate above established that the commitment being revoked was + // built with SigHashDefault second-level HTLCs, so that is what its + // dust decisions are made against. + const sigHashDefault = true + + // Fetch aux leaves for the remote commitment. + diskCommit := remoteCommitView.toDiskCommit(lntypes.Remote) + auxResult, err := fn.MapOptionZ( + lc.leafStore, + func(s AuxLeafStore) fn.Result[CommitDiffAuxResult] { + return s.FetchLeavesFromCommit( + NewAuxChanState(chanState), *diskCommit, + *keyRing, lntypes.Remote, + ) + }, + ).Unpack() + if err != nil { + return fmt.Errorf("unable to fetch aux leaves for "+ + "revocation verification: %w", err) + } + + // Build a verify job for each non-dust HTLC, matched by direction and + // HTLC index from the unpacked sig map. + type htlcEntry struct { + htlc *paymentDescriptor + incoming bool + } + var htlcList []htlcEntry + for i := range remoteCommitView.incomingHTLCs { + htlcList = append(htlcList, htlcEntry{ + htlc: &remoteCommitView.incomingHTLCs[i], + incoming: true, + }) + } + for i := range remoteCommitView.outgoingHTLCs { + htlcList = append(htlcList, htlcEntry{ + htlc: &remoteCommitView.outgoingHTLCs[i], + incoming: false, + }) + } + + auxVerifyJobs := make([]AuxVerifyJob, 0, numHTLCs) + commitBlob := remoteCommitView.customBlob + consumedEntries := make(map[revocationAuxSigKey]struct{}, len(sigMap)) + + for _, entry := range htlcList { + htlc := entry.htlc + incoming := entry.incoming + + if HtlcIsDust( + chanType, incoming, lntypes.Remote, feePerKw, + htlc.Amount.ToSatoshis(), dustLimit, + sigHashDefault, + ) { + + continue + } + + // An HTLC incoming to us was offered by us, so it is incoming + // from the signer's point of view when it is outgoing from + // ours. + key := revocationAuxSigKey{ + signerIncoming: !incoming, + htlcIndex: htlc.HtlcIndex, + } + sigEntry, ok := sigMap[key] + if !ok { + return fmt.Errorf("no revocation aux sig for HTLC "+ + "index %d (incoming=%v)", htlc.HtlcIndex, + incoming) + } + consumedEntries[key] = struct{}{} + + // Determine the aux leaf for this HTLC. + var auxLeaf input.AuxTapLeaf + if incoming { + auxLeaf = fn.FlatMapOption( + func(l CommitAuxLeaves) input.AuxTapLeaf { + idx := htlc.HtlcIndex + leaves := l.IncomingHtlcLeaves + return leaves[idx].SecondLevelLeaf + }, + )(auxResult.AuxLeaves) + } else { + auxLeaf = fn.FlatMapOption( + func(l CommitAuxLeaves) input.AuxTapLeaf { + idx := htlc.HtlcIndex + leaves := l.OutgoingHtlcLeaves + return leaves[idx].SecondLevelLeaf + }, + )(auxResult.AuxLeaves) + } + + auxVerifyJobs = append(auxVerifyJobs, revocationAuxVerifyJob( + sigEntry, htlc, incoming, keyRing, commitBlob, + auxLeaf, + )) + } + + // Every received entry must correspond to a non-dust HTLC on the + // revoked commitment: an honest signer never packs anything else, so + // entries with unknown or dust HTLC indexes are garbage we refuse to + // accept a revocation over. + for key := range sigMap { + if _, ok := consumedEntries[key]; !ok { + return fmt.Errorf("unexpected revocation aux sig "+ + "entry for HTLC index %d (signer incoming=%v)", + key.htlcIndex, key.signerIncoming) + } + } + + if len(auxVerifyJobs) == 0 { + return nil + } + + lc.log.Infof("Verifying revocation aux sigs of %d HTLCs against "+ + "breach-time key ring", len(auxVerifyJobs)) + + err = auxSigner.VerifySecondLevelSigs( + NewAuxChanState(lc.channelState), + remoteCommitView.txn, auxVerifyJobs, + ) + if err != nil { + return fmt.Errorf("revocation aux sig verification "+ + "failed: %w", err) + } + + lc.log.Infof("Revocation aux sig verification passed") + + return nil +} + +// htlcAuxSigParams bundles the parameters shared across both the incoming +// and outgoing HTLC aux-signing loops. +type htlcAuxSigParams struct { + chanType channeldb.ChannelType + isRemoteInitiator bool + localChanCfg channeldb.ChannelConfig + localHtlcKeyTweak []byte + feePerKw chainfee.SatPerKWeight + dustLimit btcutil.Amount + txHash chainhash.Hash + ourDelay uint32 + leaseExpiry uint32 + sigHashDefault bool + sigHashType txscript.SigHashType + keyRing *CommitmentKeyRing + auxResult CommitDiffAuxResult + commitView *commitment + cancelChan chan struct{} +} + +// signHTLCAuxSigs creates the aux sig jobs for the non-dust HTLCs of one +// direction on the local commitment. Each HTLC is signed for the one +// second-level path it has on our own commitment: success for an incoming +// HTLC, timeout for an outgoing one. +func (p *htlcAuxSigParams) signHTLCAuxSigs(htlcs []paymentDescriptor, + incoming bool) ([]AuxSigJob, error) { + + var jobs []AuxSigJob + for i := range htlcs { + htlc := &htlcs[i] + if HtlcIsDust( + p.chanType, incoming, lntypes.Local, + p.feePerKw, htlc.Amount.ToSatoshis(), + p.dustLimit, p.sigHashDefault, + ) { + + continue + } + + job, err := p.signHTLC(htlc, incoming) + if err != nil { + return nil, err + } + + jobs = append(jobs, job) + } + + return jobs, nil +} + +// signHTLC creates the AuxSigJob for the second-level path of an HTLC on our +// own commitment: the success tx for an incoming HTLC, the timeout tx for an +// outgoing one. +func (p *htlcAuxSigParams) signHTLC(htlc *paymentDescriptor, + incoming bool) (AuxSigJob, error) { + + auxLeaf := p.getAuxLeaf(htlc, incoming) + op := wire.OutPoint{ + Hash: p.txHash, + Index: uint32(htlc.localOutputIndex), + } + + secondLevelTx, _, err := p.createSecondLevelTx( + op, htlc, incoming, auxLeaf, + ) + if err != nil { + return AuxSigJob{}, err + } + + amt := htlc.Amount.ToSatoshis() + txOut := p.commitView.txn.TxOut[htlc.localOutputIndex] + prevFetcher := txscript.NewCannedPrevOutputFetcher( + txOut.PkScript, int64(amt), + ) + + job, err := p.buildSigJob( + secondLevelTx, txOut, prevFetcher, htlc, incoming, auxLeaf, + ) + if err != nil { + return AuxSigJob{}, err + } + + // The success path has no timeout, the timeout path carries the + // HTLC's. + if incoming { + job.HtlcTimeout = fn.None[uint32]() + } else { + job.HtlcTimeout = fn.Some(htlc.Timeout) + } + + return job, nil +} + +// createSecondLevelTx creates the second-level HTLC transaction for +// the given path. When incoming is true a success-tx is created; +// when false a timeout-tx is created. Returns the tx and its fee. +func (p *htlcAuxSigParams) createSecondLevelTx( + op wire.OutPoint, htlc *paymentDescriptor, + incoming bool, auxLeaf input.AuxTapLeaf, +) (*wire.MsgTx, btcutil.Amount, error) { + + if incoming { + fee := HtlcSuccessFee( + p.chanType, p.feePerKw, p.sigHashDefault, + ) + amt := htlc.Amount.ToSatoshis() - fee + tx, err := CreateHtlcSuccessTx( + p.chanType, p.isRemoteInitiator, op, + amt, p.ourDelay, p.leaseExpiry, + p.keyRing.RevocationKey, + p.keyRing.ToLocalKey, auxLeaf, + p.sigHashDefault, + ) + + return tx, fee, err + } + + fee := HtlcTimeoutFee( + p.chanType, p.feePerKw, p.sigHashDefault, + ) + amt := htlc.Amount.ToSatoshis() - fee + tx, err := CreateHtlcTimeoutTx( + p.chanType, p.isRemoteInitiator, op, amt, + htlc.Timeout, p.ourDelay, p.leaseExpiry, + p.keyRing.RevocationKey, + p.keyRing.ToLocalKey, auxLeaf, + p.sigHashDefault, + ) + + return tx, fee, err +} + +// buildSigJob creates an AuxSigJob for a second-level HTLC +// transaction, wrapping the sign descriptor and script generation. +func (p *htlcAuxSigParams) buildSigJob( + tx *wire.MsgTx, txOut *wire.TxOut, + prevFetcher txscript.PrevOutputFetcher, + htlc *paymentDescriptor, incoming bool, + auxLeaf input.AuxTapLeaf, +) (AuxSigJob, error) { + + hashCache := txscript.NewTxSigHashes(tx, prevFetcher) + htlcScript, err := genHtlcScript( + p.chanType, incoming, lntypes.Local, + htlc.Timeout, htlc.RHash, p.keyRing, + fn.None[txscript.TapLeaf](), + ) + if err != nil { + return AuxSigJob{}, err + } + + ws := htlcScript.WitnessScriptToSign() + sigJob := SignJob{ + SignDesc: input.SignDescriptor{ + KeyDesc: p.localChanCfg.HtlcBasePoint, + SingleTweak: p.localHtlcKeyTweak, + WitnessScript: ws, + Output: txOut, + PrevOutputFetcher: prevFetcher, + HashType: p.sigHashType, + SigHashes: hashCache, + InputIndex: 0, + }, + Tx: tx, + OutputIndex: htlc.localOutputIndex, + } + if p.chanType.IsTaproot() { + sigJob.SignDesc.SignMethod = input.TaprootScriptSpendSignMethod + } + + auxJob := NewAuxSigJob( + sigJob, *p.keyRing, incoming, + newAuxHtlcDescriptor(htlc), + p.commitView.customBlob, auxLeaf, + lntypes.Local, p.cancelChan, + ) + + return auxJob, nil +} + +// getAuxLeaf returns the aux tap leaf for the given HTLC. +func (p *htlcAuxSigParams) getAuxLeaf( + htlc *paymentDescriptor, incoming bool, +) input.AuxTapLeaf { + + if incoming { + return fn.FlatMapOption( + func(l CommitAuxLeaves) input.AuxTapLeaf { + idx := htlc.HtlcIndex + leaves := l.IncomingHtlcLeaves + return leaves[idx].SecondLevelLeaf + }, + )(p.auxResult.AuxLeaves) + } + + return fn.FlatMapOption( + func(l CommitAuxLeaves) input.AuxTapLeaf { + idx := htlc.HtlcIndex + leaves := l.OutgoingHtlcLeaves + return leaves[idx].SecondLevelLeaf + }, + )(p.auxResult.AuxLeaves) +} + +// signLocalHtlcAuxSigs signs the second-level HTLC virtual packets for the +// current local commitment (the one being revoked). These signatures allow +// the remote party to reconstruct valid aux proofs for the +// commitment-to-second-level transition if a breach occurs. The returned +// blob is packed in the same format as CommitSig aux sigs and can be +// attached to RevokeAndAck.CustomRecords. +// +// This method must be called BEFORE advanceTail() since it needs access to the +// current local commitment view and the commitment secret at currentHeight. +func (lc *LightningChannel) signLocalHtlcAuxSigs() ([]byte, error) { + // Get the current local commitment view (about to be revoked). + localCommitView := lc.commitChains.Local.tail() + + // Defense in depth: this must only ever run for aux/custom channels + // revoking a DeterministicHTLCs commitment (the caller already + // checks). + if !lc.exchangesRevocationAuxSigs(localCommitView) { + return nil, nil + } + + // If there's no aux signer, nothing to do. + if lc.auxSigner.IsNone() { + return nil, nil + } + + // Check if there are any HTLCs to sign. + numHTLCs := len(localCommitView.incomingHTLCs) + + len(localCommitView.outgoingHTLCs) + if numHTLCs == 0 { + return nil, nil + } + + // Derive the key ring for our local commitment using the + // standard perspective (whoseCommit=Local, standard config + // order). This matches how the commitment was originally + // built, so the AuxSig will be over the actual on-chain + // second-level HTLC outputs. + commitSecret, err := lc.channelState.RevocationProducer.AtIndex( + lc.currentHeight, + ) + if err != nil { + return nil, err + } + commitPoint := input.ComputeCommitmentPoint(commitSecret[:]) + keyRing := DeriveCommitmentKeys( + commitPoint, lntypes.Local, + lc.channelState.ChanType, + &lc.channelState.LocalChanCfg, + &lc.channelState.RemoteChanCfg, + ) + + chanState := lc.channelState + chanType := chanState.ChanType + + var leaseExpiry uint32 + if chanType.HasLeaseExpiration() { + leaseExpiry = chanState.ThawHeight + } + + // Sign with the sighash recorded for the commitment being revoked, + // which the gate above established to be SigHashDefault. This is the + // sighash its second-level HTLC transactions were built with, no + // matter what new commitments use by now. + sigHashType := lc.commitSigHashType(localCommitView.customBlob) + sigHashDefault := sigHashType == txscript.SigHashDefault + + // Fetch aux leaves for our local commitment, matching how + // the commitment was originally constructed. + diskCommit := localCommitView.toDiskCommit(lntypes.Local) + auxResult, err := fn.MapOptionZ( + lc.leafStore, + func(s AuxLeafStore) fn.Result[CommitDiffAuxResult] { + return s.FetchLeavesFromCommit( + NewAuxChanState(chanState), *diskCommit, + *keyRing, lntypes.Local, + ) + }, + ).Unpack() + if err != nil { + return nil, fmt.Errorf("unable to fetch aux leaves: %w", err) + } + + cancelChan := make(chan struct{}) + + localChanCfg := chanState.LocalChanCfg + params := htlcAuxSigParams{ + chanType: chanType, + isRemoteInitiator: !chanState.IsInitiator, + localChanCfg: localChanCfg, + localHtlcKeyTweak: keyRing.LocalHtlcKeyTweak, + feePerKw: localCommitView.feePerKw, + dustLimit: chanState.LocalChanCfg.DustLimit, + txHash: localCommitView.txn.TxHash(), + ourDelay: uint32(localChanCfg.CsvDelay), + leaseExpiry: leaseExpiry, + sigHashDefault: sigHashDefault, + sigHashType: sigHashType, + keyRing: keyRing, + auxResult: auxResult, + commitView: localCommitView, + cancelChan: cancelChan, + } + + // Sign the second-level path of every non-dust HTLC: success for the + // incoming ones, timeout for the outgoing ones. + inJobs, err := params.signHTLCAuxSigs( + localCommitView.incomingHTLCs, true, + ) + if err != nil { + return nil, err + } + + outJobs, err := params.signHTLCAuxSigs( + localCommitView.outgoingHTLCs, false, + ) + if err != nil { + return nil, err + } + + auxSigBatch := append(inJobs, outJobs...) //nolint:gocritic + + if len(auxSigBatch) == 0 { + return nil, nil + } + + // Sort by output index, the order the aux signer processes a batch + // in elsewhere (same as genRemoteHtlcSigJobs). + slices.SortFunc(auxSigBatch, func(i, j AuxSigJob) int { + return cmp.Compare(i.OutputIndex, j.OutputIndex) + }) + + // Submit the signing batch using the standard chanState + // (matching the commitment construction perspective). + auxSigner, _ := lc.auxSigner.UnwrapOrErr( + fmt.Errorf("no aux signer"), + ) + err = auxSigner.SubmitSecondLevelSigBatch( + NewAuxChanState(lc.channelState), + localCommitView.txn, auxSigBatch, + ) + if err != nil { + return nil, fmt.Errorf("unable to submit aux sig batch: %w", + err) + } + + // Collect the signatures from the batch into entries tagged with the + // HTLC's direction and index. The index alone would not do: both + // parties count the HTLCs they offer from zero, so an incoming and an + // outgoing HTLC regularly share one. + entries := make([]revocationAuxSigEntry, len(auxSigBatch)) + for i, sigJob := range auxSigBatch { + resp := <-sigJob.Resp + if resp.Err != nil { + close(cancelChan) + return nil, fmt.Errorf("aux sig job %d "+ + "failed: %w", i, resp.Err) + } + + entries[i] = revocationAuxSigEntry{ + revocationAuxSigKey: revocationAuxSigKey{ + signerIncoming: sigJob.Incoming, + htlcIndex: sigJob.HTLC.HtlcIndex, + }, + sig: resp.SigBlob.UnwrapOr(nil), + } + } + + // Pack the entries in a deterministic order. + slices.SortFunc(entries, func(i, j revocationAuxSigEntry) int { + if i.signerIncoming != j.signerIncoming { + if i.signerIncoming { + return 1 + } + + return -1 + } + + return cmp.Compare(i.htlcIndex, j.htlcIndex) + }) + + // The blob is packed and attached even if no entry carries actual sig + // data (e.g. all non-dust HTLCs are BTC-only): the receiver requires + // one entry per non-dust HTLC, in lockstep with the BTC-level + // signatures, so it can tell a sig-less HTLC apart from a withheld + // signature. + packed, err := packRevocationAuxSigs(entries) + if err != nil { + return nil, fmt.Errorf("pack revocation aux sigs: %w", err) + } + + return packed, nil +} + // createCommitDiff will create a commit diff given a new pending commitment // for the remote party and the necessary signatures for the remote party to // validate this new state. This function is called right before sending the @@ -4948,6 +6054,24 @@ func (lc *LightningChannel) ProcessChanSyncMsg(ctx context.Context, return nil, nil, nil, err } + // Re-attach the revocation aux sigs that accompanied the + // original RevokeAndAck. This is a custom-channel-only + // concern: RevocationAuxSigs is only ever set (persisted + // atomically with our commitment tail advance) when + // exchangesRevocationAuxSigs held at revocation time, and the + // receiving peer requires the sigs for every non-dust HTLC on + // the revoked commitment. + lc.channelState.RevocationAuxSigs.WhenSome( + func(sigs tlv.Blob) { + revocationMsg.CustomRecords = make( + lnwire.CustomRecords, + ) + + recType := revokeAndAckAuxSigType + revocationMsg.CustomRecords[recType] = sigs + }, + ) + updates = append(updates, revocationMsg) // Next, as a precaution, we'll check a special edge case. If @@ -6219,6 +7343,37 @@ func (lc *LightningChannel) RevokeCurrentCommitment() (*lnwire.RevokeAndAck, lc.commitChains.Local.tail().height, lc.currentHeight+1) + // Attach revocation AuxSigs to the RevokeAndAck, but ONLY for + // aux/custom (taproot asset) channels with the DeterministicHTLCs + // feature negotiated: see exchangesRevocationAuxSigs. A vanilla lnd + // channel never signs or appends these records and its RevokeAndAck + // is byte-identical to before this feature. Without + // DeterministicHTLCs the remote party has no use for the signatures + // (and wouldn't know how to parse them). + revocationAuxSigs := fn.None[tlv.Blob]() + if lc.exchangesRevocationAuxSigs(lc.commitChains.Local.tail()) { + // A signing failure fails the revocation as a whole: the + // receiving peer requires the sigs for every non-dust HTLC, + // so sending a sig-less RevokeAndAck would just fail the + // channel on their side instead. Nothing has been advanced or + // persisted yet, so failing here is safe and retryable. + auxSigBlob, err := lc.signLocalHtlcAuxSigs() + if err != nil { + return nil, nil, nil, fmt.Errorf("unable to sign "+ + "local HTLC aux sigs for revocation: %w", err) + } + if auxSigBlob != nil { + revocationMsg.CustomRecords = + make(lnwire.CustomRecords) + + recType := revokeAndAckAuxSigType + revocationMsg.CustomRecords[recType] = + auxSigBlob + + revocationAuxSigs = fn.Some[tlv.Blob](auxSigBlob) + } + } + // Advance our tail, as we've revoked our previous state. lc.commitChains.Local.advanceTail() lc.currentHeight++ @@ -6228,8 +7383,11 @@ func (lc *LightningChannel) RevokeCurrentCommitment() (*lnwire.RevokeAndAck, chainTail := lc.commitChains.Local.tail() newCommitment := chainTail.toDiskCommit(lntypes.Local) + // The aux sigs (custom channels only, None otherwise) are persisted + // atomically with the commitment advance, so a retransmission of this + // RevokeAndAck carries the exact same signatures. finalHtlcs, err := lc.channelState.UpdateCommitment( - newCommitment, unsignedAckedUpdates, + newCommitment, unsignedAckedUpdates, revocationAuxSigs, ) if err != nil { return nil, nil, nil, err @@ -6508,6 +7666,36 @@ func (lc *LightningChannel) ReceiveRevocation(revMsg *lnwire.RevokeAndAck) ( lc.musigSessions.RemoteSession = session } + // Revocation AuxSigs are a custom-channel-only concern. On aux/custom + // (taproot asset) channels with DeterministicHTLCs negotiated, the + // RevokeAndAck carries aux sigs for the remote party's second-level + // HTLCs; we verify them against the breach-time key ring before + // accepting the revocation, then store them in the revocation log for + // breach recovery. For every non-custom channel + // exchangesRevocationAuxSigs is false, so we skip this block entirely + // and never inspect CustomRecords. + if lc.exchangesRevocationAuxSigs(lc.commitChains.Remote.tail()) { + recType := revokeAndAckAuxSigType + auxSigBlob := revMsg.CustomRecords[recType] + + // The blob is verified unconditionally: an absent blob is not + // a pass. The peer owes us one entry per non-dust HTLC on the + // revoked commitment (mirroring the aux sig count check on + // CommitSig), otherwise withholding the sigs would silently + // strip our breach protection. + err = lc.verifyRevocationAuxSigs( + auxSigBlob, currentCommitPoint, + ) + if err != nil { + return nil, nil, fmt.Errorf("invalid "+ + "revocation aux sigs: %w", err) + } + + if len(auxSigBlob) > 0 { + lc.injectRevocationAuxSigs(auxSigBlob) + } + } + // At this point, the revocation has been accepted, and we've rotated // the current revocation key+hash for the remote party. Therefore we // sync now to ensure the revocation producer state is consistent with @@ -7773,6 +8961,15 @@ type IncomingHtlcResolution struct { // spender of the output to properly resolve it in the case of a force // close. ResolutionBlob fn.Option[tlv.Blob] + + // ResolveReq is the resolution request template used to generate the + // ResolutionBlob. It is preserved so the htlc success resolver can + // re-resolve with a second-level witness type once the pre-signed + // second-level HTLC tx confirms (under DeterministicHTLCs the + // resolver publishes the second-level tx directly via PublishTx, + // bypassing the sweeper's NotifyBroadcast, so tapd must import the + // second-level proof retroactively before the output sweep runs). + ResolveReq *ResolutionReq } // OutgoingHtlcResolution houses the information necessary to sweep any @@ -7827,6 +9024,10 @@ type OutgoingHtlcResolution struct { // spender of the output to properly resolve it in the case of a force // close. ResolutionBlob fn.Option[tlv.Blob] + + // ResolveReq is the resolution request template used to generate the + // ResolutionBlob. See IncomingHtlcResolution.ResolveReq for details. + ResolveReq *ResolutionReq } // HtlcResolutions contains the items necessary to sweep HTLC's on chain @@ -8171,39 +9372,37 @@ func newOutgoingHtlcResolution(signer input.Signer, // This might be an aux channel, so we'll go ahead and attempt to // generate the resolution blob for the channel so we can pass along to // the sweeping sub-system. + resReq := ResolutionReq{ + ChanPoint: chanState.FundingOutpoint, + ChanType: chanType, + ShortChanID: chanState.ShortChanID(), + Initiator: chanState.IsInitiator, + CommitBlob: chanState.LocalCommitment.CustomBlob, + FundingBlob: chanState.CustomBlob, + Type: input.TaprootHtlcLocalOfferedTimeout, + CloseType: LocalForceClose, + CommitTx: commitTx, + CommitTxBlockHeight: commitTxHeight, + ContractPoint: op, + SignDesc: sweepSignDesc, + KeyRing: keyRing, + CsvDelay: htlcCsvDelay, + HtlcAmt: btcutil.Amount(txOut.Value), + CommitCsvDelay: csvDelay, + CltvDelay: fn.Some(htlc.RefundTimeout), + CommitFee: chanState.LocalCommitment.CommitFee, + HtlcID: fn.Some(htlc.HtlcIndex), + PayHash: fn.Some(htlc.RHash), + AuxSigDesc: fn.Some(AuxSigDesc{ + SignDetails: *txSignDetails, + AuxSig: func() []byte { + tlvType := htlcCustomSigType.TypeVal() + return htlc.CustomRecords[uint64(tlvType)] + }(), + }), + } resolveRes := fn.MapOptionZ( auxResolver, func(a AuxContractResolver) fn.Result[tlv.Blob] { - //nolint:ll - resReq := ResolutionReq{ - ChanPoint: chanState.FundingOutpoint, - ChanType: chanType, - ShortChanID: chanState.ShortChanID(), - Initiator: chanState.IsInitiator, - CommitBlob: chanState.LocalCommitment.CustomBlob, - FundingBlob: chanState.CustomBlob, - Type: input.TaprootHtlcLocalOfferedTimeout, - CloseType: LocalForceClose, - CommitTx: commitTx, - CommitTxBlockHeight: commitTxHeight, - ContractPoint: op, - SignDesc: sweepSignDesc, - KeyRing: keyRing, - CsvDelay: htlcCsvDelay, - HtlcAmt: btcutil.Amount(txOut.Value), - CommitCsvDelay: csvDelay, - CltvDelay: fn.Some(htlc.RefundTimeout), - CommitFee: chanState.LocalCommitment.CommitFee, - HtlcID: fn.Some(htlc.HtlcIndex), - PayHash: fn.Some(htlc.RHash), - AuxSigDesc: fn.Some(AuxSigDesc{ - SignDetails: *txSignDetails, - AuxSig: func() []byte { - tlvType := htlcCustomSigType.TypeVal() - return htlc.CustomRecords[uint64(tlvType)] - }(), - }), - } - return a.ResolveContract(resReq) }, ) @@ -8212,12 +9411,15 @@ func newOutgoingHtlcResolution(signer input.Signer, } resolutionBlob := resolveRes.OkToSome() + resReqCopy := resReq + return &OutgoingHtlcResolution{ Expiry: htlc.RefundTimeout, SignedTimeoutTx: timeoutTx, SignDetails: txSignDetails, CsvDelay: csvDelay, ResolutionBlob: resolutionBlob, + ResolveReq: &resReqCopy, ClaimOutpoint: wire.OutPoint{ Hash: timeoutTx.TxHash(), Index: 0, @@ -8545,39 +9747,37 @@ func newIncomingHtlcResolution(signer input.Signer, }, nil } + resReq := ResolutionReq{ + ChanPoint: chanState.FundingOutpoint, + ChanType: chanType, + ShortChanID: chanState.ShortChanID(), + Initiator: chanState.IsInitiator, + CommitBlob: chanState.LocalCommitment.CustomBlob, + Type: input.TaprootHtlcAcceptedLocalSuccess, + FundingBlob: chanState.CustomBlob, + CloseType: LocalForceClose, + CommitTx: commitTx, + CommitTxBlockHeight: commitTxHeight, + ContractPoint: op, + SignDesc: sweepSignDesc, + KeyRing: keyRing, + HtlcID: fn.Some(htlc.HtlcIndex), + CsvDelay: htlcCsvDelay, + CommitFee: chanState.LocalCommitment.CommitFee, + PayHash: fn.Some(htlc.RHash), + AuxSigDesc: fn.Some(AuxSigDesc{ + SignDetails: *txSignDetails, + AuxSig: func() []byte { + tlvType := htlcCustomSigType.TypeVal() + return htlc.CustomRecords[uint64(tlvType)] + }(), + }), + CommitCsvDelay: csvDelay, + HtlcAmt: btcutil.Amount(txOut.Value), + CltvDelay: fn.Some(htlc.RefundTimeout), + } resolveRes := fn.MapOptionZ( auxResolver, func(a AuxContractResolver) fn.Result[tlv.Blob] { - //nolint:ll - resReq := ResolutionReq{ - ChanPoint: chanState.FundingOutpoint, - ChanType: chanType, - ShortChanID: chanState.ShortChanID(), - Initiator: chanState.IsInitiator, - CommitBlob: chanState.LocalCommitment.CustomBlob, - Type: input.TaprootHtlcAcceptedLocalSuccess, - FundingBlob: chanState.CustomBlob, - CloseType: LocalForceClose, - CommitTx: commitTx, - CommitTxBlockHeight: commitTxHeight, - ContractPoint: op, - SignDesc: sweepSignDesc, - KeyRing: keyRing, - HtlcID: fn.Some(htlc.HtlcIndex), - CsvDelay: htlcCsvDelay, - CommitFee: chanState.LocalCommitment.CommitFee, - PayHash: fn.Some(htlc.RHash), - AuxSigDesc: fn.Some(AuxSigDesc{ - SignDetails: *txSignDetails, - AuxSig: func() []byte { - tlvType := htlcCustomSigType.TypeVal() - return htlc.CustomRecords[uint64(tlvType)] - }(), - }), - CommitCsvDelay: csvDelay, - HtlcAmt: btcutil.Amount(txOut.Value), - CltvDelay: fn.Some(htlc.RefundTimeout), - } - return a.ResolveContract(resReq) }, ) @@ -8587,11 +9787,14 @@ func newIncomingHtlcResolution(signer input.Signer, resolutionBlob := resolveRes.OkToSome() + resReqCopy := resReq + return &IncomingHtlcResolution{ SignedSuccessTx: successTx, SignDetails: txSignDetails, CsvDelay: csvDelay, ResolutionBlob: resolutionBlob, + ResolveReq: &resReqCopy, ClaimOutpoint: wire.OutPoint{ Hash: successTx.TxHash(), Index: 0, @@ -8624,6 +9827,116 @@ func (r *OutgoingHtlcResolution) HtlcPoint() wire.OutPoint { return r.ClaimOutpoint } +// NewSecondLevelResolveReq reconstructs a ResolutionReq for re-resolving a +// second-level HTLC sweep after the pre-signed second-level tx has confirmed +// on chain. It is intended to be called from the htlc success / timeout +// resolvers when, under DeterministicHTLCs, the resolver published the +// pre-signed second-level tx directly via PublishTx (bypassing the aux +// sweeper's NotifyBroadcast) and the upcoming second-level output sweep +// would otherwise fail to fetch its input proof from the aux sweeper's +// archive. +// +// The ResolveReq returned mirrors the live request that +// newIncomingHtlcResolution / newOutgoingHtlcResolution built at +// force-close time. We rebuild it here from the persisted channel state +// because IncomingHtlcResolution / OutgoingHtlcResolution don't currently +// round-trip the original ResolveReq through the briefcase log. +// +// chanState must be the historical channel state (e.g. via +// FetchHistoricalChannel). htlc is the HTLC entry whose second-level +// sweep we're about to perform. signDetails is the SignDetails captured +// on the resolution at force-close time. htlcCsvDelay is the CSV delay +// for the second-level output (taken from +// IncomingHtlcResolution.CsvDelay / OutgoingHtlcResolution.CsvDelay). +// commitTxBlockHeight is the height at which the force-close commitment +// confirmed. secondLevelTx and secondLevelTxBlockHeight describe the +// just-confirmed second-level tx. witType is the second-level output +// witness type LND is about to offer to the sweeper +// (TaprootHtlcAcceptedSuccessSecondLevel for the success path or +// TaprootHtlcOfferedTimeoutSecondLevel for the timeout path). +// +// We always treat this as the local commitment because the success / +// timeout resolvers only run for HTLCs on our local force-close +// commitment. +func NewSecondLevelResolveReq(chanState *channeldb.OpenChannel, + htlc *channeldb.HTLC, signDetails *input.SignDetails, + sweepSignDesc input.SignDescriptor, htlcCsvDelay, + commitTxBlockHeight uint32, secondLevelTx *wire.MsgTx, + secondLevelTxBlockHeight uint32, + witType input.WitnessType) (*ResolutionReq, error) { + + if chanState == nil { + return nil, fmt.Errorf("chanState is nil") + } + if secondLevelTx == nil || len(secondLevelTx.TxIn) == 0 { + return nil, fmt.Errorf("invalid second-level tx") + } + + revocation, err := chanState.RevocationProducer.AtIndex( + chanState.LocalCommitment.CommitHeight, + ) + if err != nil { + return nil, fmt.Errorf("derive revocation: %w", err) + } + commitPoint := input.ComputeCommitmentPoint(revocation[:]) + keyRing := DeriveCommitmentKeys( + commitPoint, lntypes.Local, chanState.ChanType, + &chanState.LocalChanCfg, &chanState.RemoteChanCfg, + ) + keyRingCopy := *keyRing + + htlcAmt := htlc.Amt.ToSatoshis() + commitCsvDelay := uint32(chanState.LocalChanCfg.CsvDelay) + contractPoint := secondLevelTx.TxIn[0].PreviousOutPoint + + // AuxSigDesc is populated when we have both the SignDetails captured + // on the resolution and the remote party's aux sig in the HTLC's + // custom records. signSecondLevelImport uses the breach-style + // 2-of-2 witness construction when AuxSigDesc is present, producing + // a fully verifiable proof transition; the placeholder-witness + // fallback is reserved for the breach path where we don't have the + // remote sig. + var auxSigDesc fn.Option[AuxSigDesc] + if signDetails != nil { + sigType := htlcCustomSigType.TypeVal() + auxSig := htlc.CustomRecords[uint64(sigType)] + if len(auxSig) > 0 { + auxSigDesc = fn.Some(AuxSigDesc{ + SignDetails: *signDetails, + AuxSig: auxSig, + }) + } + } + + return &ResolutionReq{ + ChanPoint: chanState.FundingOutpoint, + ChanType: chanState.ChanType, + ShortChanID: chanState.ShortChanID(), + Initiator: chanState.IsInitiator, + CommitBlob: chanState.LocalCommitment.CustomBlob, + FundingBlob: chanState.CustomBlob, + HtlcID: fn.Some(htlc.HtlcIndex), + HtlcAmt: htlcAmt, + Type: witType, + CloseType: LocalForceClose, + CommitTx: chanState.LocalCommitment.CommitTx, + CommitTxBlockHeight: commitTxBlockHeight, + CommitFee: chanState.LocalCommitment.CommitFee, + ContractPoint: contractPoint, + SignDesc: sweepSignDesc, + KeyRing: &keyRingCopy, + CsvDelay: htlcCsvDelay, + CommitCsvDelay: commitCsvDelay, + CltvDelay: fn.Some(htlc.RefundTimeout), + PayHash: fn.Some(htlc.RHash), + AuxSigDesc: auxSigDesc, + SecondLevel: fn.Some(SecondLevelInfo{ + Tx: secondLevelTx, + BlockHeight: secondLevelTxBlockHeight, + }), + }, nil +} + // extractHtlcResolutions creates a series of outgoing HTLC resolutions, and // the local key used when generating the HTLC scrips. This function is to be // used in two cases: force close, or a unilateral close. diff --git a/lnwallet/channel_test.go b/lnwallet/channel_test.go index a29fceb01c7..25cb9e23098 100644 --- a/lnwallet/channel_test.go +++ b/lnwallet/channel_test.go @@ -10457,6 +10457,7 @@ func TestCreateHtlcRetribution(t *testing.T) { hr, err := createHtlcRetribution( aliceChannel.channelState, keyRing, commitHash, dummyPrivate, leaseExpiry, htlc, fn.None[CommitAuxLeaves](), + nil, fn.None[AuxContractResolver](), nil, 0, ) // Expect no error. require.NoError(t, err) @@ -10662,6 +10663,7 @@ func TestCreateBreachRetribution(t *testing.T) { aliceChannel.channelState, keyRing, dummyPrivate, leaseExpiry, fn.None[CommitAuxLeaves](), + fn.None[AuxContractResolver](), 0, ) // Check the error if expected. @@ -10720,7 +10722,7 @@ func TestCreateBreachRetributionLegacy(t *testing.T) { br, ourAmt, theirAmt, err := createBreachRetributionLegacy( &revokedLog, aliceChannel.channelState, keyRing, dummyPrivate, ourScript, theirScript, leaseExpiry, - fn.None[AuxSigner](), + fn.None[AuxContractResolver](), fn.None[AuxSigner](), 0, ) require.NoError(t, err) @@ -10815,7 +10817,8 @@ func TestCreateBreachRetributionLegacyDustHtlcs(t *testing.T) { // Create the breach retribution using the legacy format. br, _, _, err := createBreachRetributionLegacy( &revokedLog, chanState, keyRing, dummyPrivate, ourScript, - theirScript, leaseExpiry, fn.None[AuxSigner](), + theirScript, leaseExpiry, fn.None[AuxContractResolver](), + fn.None[AuxSigner](), 0, ) require.NoError(t, err) @@ -13233,7 +13236,8 @@ func TestLegacyBreachRetributionUsesRevokedSigHash(t *testing.T) { br, _, _, err := createBreachRetributionLegacy( &revokedLog, chanState, keyRing, dummyPrivate, ourScript, theirScript, leaseExpiry, - fn.Some[AuxSigner](signer), + fn.None[AuxContractResolver](), + fn.Some[AuxSigner](signer), 0, ) require.NoError(t, err) diff --git a/lnwallet/mock.go b/lnwallet/mock.go index 9ca85df0aa4..bf9b733ab4d 100644 --- a/lnwallet/mock.go +++ b/lnwallet/mock.go @@ -462,7 +462,7 @@ func (*MockAuxLeafStore) FetchLeavesFromCommit(_ AuxChanState, // FetchLeavesFromRevocation attempts to fetch the auxiliary leaves // from a channel revocation that stores balance + blob information. func (*MockAuxLeafStore) FetchLeavesFromRevocation( - _ *channeldb.RevocationLog) fn.Result[CommitDiffAuxResult] { + _ RevocationLeavesReq) fn.Result[CommitDiffAuxResult] { return fn.Ok(CommitDiffAuxResult{}) } diff --git a/lnwallet/revocation_aux_sig_test.go b/lnwallet/revocation_aux_sig_test.go new file mode 100644 index 00000000000..bf8a2f73c67 --- /dev/null +++ b/lnwallet/revocation_aux_sig_test.go @@ -0,0 +1,1434 @@ +package lnwallet + +import ( + "bytes" + "cmp" + "crypto/sha256" + "errors" + "fmt" + "math" + "runtime" + "slices" + "testing" + + "github.com/btcsuite/btcd/btcec/v2/schnorr/musig2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightningnetwork/lnd/channeldb" + "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/lntypes" + "github.com/lightningnetwork/lnd/lnwallet/chainfee" + "github.com/lightningnetwork/lnd/lnwire" + "github.com/lightningnetwork/lnd/tlv" + "github.com/stretchr/testify/require" +) + +// newRevAuxSigEntry is a shorthand for building a revocation aux sig entry. +func newRevAuxSigEntry(signerIncoming bool, htlcIndex uint64, + sig []byte) revocationAuxSigEntry { + + return revocationAuxSigEntry{ + revocationAuxSigKey: revocationAuxSigKey{ + signerIncoming: signerIncoming, + htlcIndex: htlcIndex, + }, + sig: sig, + } +} + +// TestPackUnpackRevocationAuxSigs tests the round-trip encoding and decoding +// of revocation aux sig entries. +func TestPackUnpackRevocationAuxSigs(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + entries []revocationAuxSigEntry + }{ + { + name: "empty entries", + entries: []revocationAuxSigEntry{}, + }, + { + name: "single entry with one HTLC", + entries: []revocationAuxSigEntry{ + newRevAuxSigEntry( + true, 42, []byte{0xaa, 0xbb, 0xcc}, + ), + }, + }, + { + name: "multiple entries with various HTLC indices", + entries: []revocationAuxSigEntry{ + newRevAuxSigEntry(false, 0, []byte{0x01}), + newRevAuxSigEntry( + true, 100, []byte{0x04, 0x05, 0x06}, + ), + newRevAuxSigEntry( + false, 999, []byte{0x08, 0x09}, + ), + }, + }, + { + // Both parties count the HTLCs they offer from zero, + // so the same index in both directions is the normal + // case and must not collapse into one entry. + name: "same HTLC index in both directions", + entries: []revocationAuxSigEntry{ + newRevAuxSigEntry(false, 0, []byte{0x0a}), + newRevAuxSigEntry(true, 0, []byte{0x0b}), + }, + }, + { + name: "entry without a sig", + entries: []revocationAuxSigEntry{ + newRevAuxSigEntry(true, 7, []byte{}), + }, + }, + { + name: "max uint64 HTLC index", + entries: []revocationAuxSigEntry{ + newRevAuxSigEntry( + false, math.MaxUint64, + []byte{0xde, 0xad}, + ), + }, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + packed, err := packRevocationAuxSigs(tc.entries) + require.NoError(t, err) + + sigMap, err := unpackRevocationAuxSigs(packed) + require.NoError(t, err) + + require.Len(t, sigMap, len(tc.entries)) + + for _, entry := range tc.entries { + got, ok := sigMap[entry.revocationAuxSigKey] + require.True(t, ok, "missing HTLC index %d "+ + "(signer incoming=%v)", + entry.htlcIndex, entry.signerIncoming) + + require.Equal( + t, entry.revocationAuxSigKey, + got.revocationAuxSigKey, + ) + require.Equal(t, entry.sig, got.sig) + } + }) + } +} + +// TestRevokeAndAckAuxSigsCustomOnly asserts the custom-channel-only gating of +// the revocation AuxSig hooks: on a NON-custom taproot channel, even with an +// aux signer present that negotiates SigHashDefault, RevokeCurrentCommitment +// must not attach any custom records to the RevokeAndAck, and +// ReceiveRevocation must accept a revocation while ignoring any custom +// records it may carry. +func TestRevokeAndAckAuxSigsCustomOnly(t *testing.T) { + t.Parallel() + + chanType := channeldb.SimpleTaprootFeatureBit | + channeldb.AnchorOutputsBit | channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit + + aliceChannel, bobChannel, err := CreateTestChannels(t, chanType) + require.NoError(t, err, "unable to create test channels") + + // An aux signer that would negotiate SigHashDefault. Since the + // channel type carries no tapscript root, the custom-channel gate + // must ignore it entirely. It is attached right before the + // revocation steps below (rather than at channel creation) so the + // unrelated CommitSig-time aux machinery stays out of the picture. + pushySigner := fn.Some[AuxSigner](&sigHashOverrideSigner{ + MockAuxSigner: NewAuxSignerMock(nil), + sigHash: txscript.SigHashDefault, + }) + + // Lock in an HTLC so the revoked commitment actually carries one. + paymentPreimage := bytes.Repeat([]byte{1}, 32) + paymentHash := sha256.Sum256(paymentPreimage) + htlcAmt := lnwire.NewMSatFromSatoshis(btcutil.SatoshiPerBitcoin) + htlc := &lnwire.UpdateAddHTLC{ + PaymentHash: paymentHash, + Amount: htlcAmt, + Expiry: uint32(5), + } + _, err = aliceChannel.AddHTLC(htlc, nil) + require.NoError(t, err) + _, err = bobChannel.ReceiveHTLC(htlc) + require.NoError(t, err) + + aliceNewCommit, err := aliceChannel.SignNextCommitment(t.Context()) + require.NoError(t, err) + err = bobChannel.ReceiveNewCommitment(aliceNewCommit.CommitSigs) + require.NoError(t, err) + + // Bob revokes: the resulting RevokeAndAck must carry NO custom + // records on a non-custom channel. + bobChannel.auxSigner = pushySigner + bobRevocation, _, _, err := bobChannel.RevokeCurrentCommitment() + require.NoError(t, err) + require.Empty(t, bobRevocation.CustomRecords, + "non-custom channel must not attach revocation aux sigs") + + // Alice processes the revocation: even if the message carried stray + // custom records, a non-custom channel must ignore them and accept + // the revocation. + bobRevocation.CustomRecords = lnwire.CustomRecords{ + revokeAndAckAuxSigType: []byte{0xde, 0xad}, + } + aliceChannel.auxSigner = pushySigner + _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) + require.NoError(t, err, + "non-custom channel must ignore revocation custom records") +} + +// fakeAuxSigFor returns the canned signature blob fakeRevocationAuxSigner +// hands out for an HTLC. It is distinct per direction and index, so tests can +// assert that a sig is never attributed to another HTLC between signing, +// packing, wire transfer, verification and persistence. +func fakeAuxSigFor(signerIncoming bool, htlcIndex uint64) []byte { + direction := byte(0x00) + if signerIncoming { + direction = 0x01 + } + + return []byte{0x51, direction, byte(htlcIndex)} +} + +// fakeRevocationAuxSigner is a minimal AuxSigner used to exercise the +// revocation AuxSig paths end to end on a custom channel. It negotiates +// SigHashDefault, answers every sign job with the canned signature blob of +// the job's HTLC, and records the sign and verify jobs it processes. +type fakeRevocationAuxSigner struct { + signJobs []AuxSigJob + verifyJobs []AuxVerifyJob + verifyErr error + + // noneSigs makes every sign job respond without a signature blob, + // simulating BTC-only HTLCs on a custom channel that need no aux + // sigs. + noneSigs bool + + // signErr makes SubmitSecondLevelSigBatch fail as a whole, + // simulating an aux signer that cannot take the batch at all. + signErr error + + // respErr makes every sign job respond with an error, simulating an + // aux signer that fails while signing. + respErr error + + // strict makes verification behave like a real aux signer for a + // commitment whose every HTLC carries aux outputs: a job must carry + // a sig, and it must be the sig of exactly that HTLC, direction + // included. + strict bool +} + +func (s *fakeRevocationAuxSigner) SubmitSecondLevelSigBatch(_ AuxChanState, + _ *wire.MsgTx, jobs []AuxSigJob) error { + + if s.signErr != nil { + return s.signErr + } + + s.signJobs = append(s.signJobs, jobs...) + for _, job := range jobs { + if s.respErr != nil { + job.Resp <- AuxSigJobResp{ + HtlcIndex: job.HTLC.HtlcIndex, + Err: s.respErr, + } + + continue + } + if s.noneSigs { + job.Resp <- AuxSigJobResp{ + SigBlob: fn.None[tlv.Blob](), + HtlcIndex: job.HTLC.HtlcIndex, + } + + continue + } + + // The job describes an HTLC of the signer's own commitment, + // so its direction is already the signer's. + blob := fakeAuxSigFor(job.Incoming, job.HTLC.HtlcIndex) + job.Resp <- AuxSigJobResp{ + SigBlob: fn.Some[tlv.Blob](blob), + HtlcIndex: job.HTLC.HtlcIndex, + } + } + + return nil +} + +func (s *fakeRevocationAuxSigner) PackSigs( + []fn.Option[tlv.Blob]) fn.Result[fn.Option[tlv.Blob]] { + + return fn.Ok(fn.None[tlv.Blob]()) +} + +func (s *fakeRevocationAuxSigner) UnpackSigs( + fn.Option[tlv.Blob]) fn.Result[[]fn.Option[tlv.Blob]] { + + return fn.Ok([]fn.Option[tlv.Blob]{}) +} + +func (s *fakeRevocationAuxSigner) VerifySecondLevelSigs(_ AuxChanState, + _ *wire.MsgTx, jobs []AuxVerifyJob) error { + + s.verifyJobs = append(s.verifyJobs, jobs...) + + if s.verifyErr != nil { + return s.verifyErr + } + if !s.strict { + return nil + } + + for _, job := range jobs { + idx := job.HTLC.HtlcIndex + if job.SigBlob.IsNone() { + return fmt.Errorf("missing aux sig for HTLC index %d "+ + "(incoming=%v)", idx, job.Incoming) + } + + // The job describes an HTLC of the remote commitment from + // the verifier's point of view, so the signer saw it in the + // opposite direction. + want := fakeAuxSigFor(!job.Incoming, idx) + if !bytes.Equal(want, job.SigBlob.UnwrapOr(nil)) { + return fmt.Errorf("aux sig of another HTLC for HTLC "+ + "index %d (incoming=%v)", idx, job.Incoming) + } + } + + return nil +} + +func (s *fakeRevocationAuxSigner) HtlcSigHashType( + _ HtlcSigHashReq) fn.Option[txscript.SigHashType] { + + return fn.Some(txscript.SigHashDefault) +} + +// setupRevocationAuxSigTest creates a custom (tapscript root) channel pair, +// locks in the HTLCs of setupRevocationAuxSigChannels, then lets Bob revoke +// the commitment carrying them. Bob's fake aux signer is attached right +// before his revocation, so the sigs it produces end up in the returned +// RevokeAndAck. Alice's fake signer is returned unattached: callers attach +// it (after optionally configuring it) right before feeding the revocation +// to Alice. +func setupRevocationAuxSigTest(t *testing.T, + bobSigner *fakeRevocationAuxSigner) (*LightningChannel, + *LightningChannel, *lnwire.RevokeAndAck, *fakeRevocationAuxSigner) { + + t.Helper() + + aliceChannel, bobChannel := setupRevocationAuxSigChannels(t) + + // Attach Bob's fake signer only now, so only the revocation-time aux + // paths see it. + bobChannel.auxSigner = fn.Some[AuxSigner](bobSigner) + + bobRevocation, _, _, err := bobChannel.RevokeCurrentCommitment() + require.NoError(t, err) + + return aliceChannel, bobChannel, bobRevocation, + &fakeRevocationAuxSigner{} +} + +// markChanSigHashDefault emulates a channel whose aux signer negotiated +// DeterministicHTLCs (SigHashDefault), by setting the sighash type the +// channel uses for new commitments to the value NewLightningChannel would +// have resolved. +func markChanSigHashDefault(c *LightningChannel) { + c.htlcSigHashType.Store(uint32(txscript.SigHashDefault)) +} + +// Amounts of the HTLCs the revocation aux sig tests lock in. +const ( + // revAuxNonDustAmt is far above every dust threshold. + revAuxNonDustAmt = btcutil.Amount(100_000) + + // revAuxDustAmt is dust on both commitments once the second-level + // fee and anchor are accounted for. + revAuxDustAmt = btcutil.Amount(400) + + // revAuxBobDustAmt sits between the two parties' dust thresholds: it + // is dust on Bob's commitment and would not be on Alice's. It is what + // tells the two dust limits apart in these tests. + revAuxBobDustAmt = btcutil.Amount(1_000) +) + +// revAuxHtlcAdder adds HTLCs to a pair of channels in either direction, +// keeping the per-offerer HTLC counters the way the wire protocol does. +type revAuxHtlcAdder struct { + t *testing.T + + alice *LightningChannel + bob *LightningChannel + + nextPreimage byte +} + +// add offers an HTLC of the given amount from one channel to the other and +// returns its HTLC index. +func (a *revAuxHtlcAdder) add(from, to *LightningChannel, + amt btcutil.Amount) uint64 { + + a.t.Helper() + + a.nextPreimage++ + preimage := bytes.Repeat([]byte{a.nextPreimage}, 32) + htlc := &lnwire.UpdateAddHTLC{ + PaymentHash: sha256.Sum256(preimage), + Amount: lnwire.NewMSatFromSatoshis(amt), + Expiry: uint32(10), + } + + htlcIndex, err := from.AddHTLC(htlc, nil) + require.NoError(a.t, err) + + htlc.ID = htlcIndex + _, err = to.ReceiveHTLC(htlc) + require.NoError(a.t, err) + + return htlcIndex +} + +// fromAlice offers an HTLC from Alice to Bob. +func (a *revAuxHtlcAdder) fromAlice(amt btcutil.Amount) uint64 { + return a.add(a.alice, a.bob, amt) +} + +// fromBob offers an HTLC from Bob to Alice. +func (a *revAuxHtlcAdder) fromBob(amt btcutil.Amount) uint64 { + return a.add(a.bob, a.alice, amt) +} + +// newRevocationAuxSigChannels creates the custom channel pair the revocation +// aux sig tests run on, with DeterministicHTLCs negotiated on both sides. +func newRevocationAuxSigChannels(t *testing.T) (*LightningChannel, + *LightningChannel, *revAuxHtlcAdder) { + + t.Helper() + + chanType := channeldb.SimpleTaprootFeatureBit | + channeldb.TapscriptRootBit + + aliceChannel, bobChannel, err := CreateTestChannels(t, chanType) + require.NoError(t, err, "unable to create test channels") + + // Emulate channels whose aux signer negotiated DeterministicHTLCs: + // the sighash type used for new commitments is set to exactly what + // NewLightningChannel would have resolved had a + // SigHashDefault-negotiating signer been attached from the start. A + // late signer swap (as done below for the fake revocation signers) + // does not change it, as it is only re-resolved on request. + markChanSigHashDefault(aliceChannel) + markChanSigHashDefault(bobChannel) + + // The tests rely on the two parties having different dust limits, so + // that using the wrong party's limit shows. + aliceDust := aliceChannel.channelState.LocalChanCfg.DustLimit + bobDust := bobChannel.channelState.LocalChanCfg.DustLimit + require.Less(t, aliceDust, bobDust) + + return aliceChannel, bobChannel, &revAuxHtlcAdder{ + t: t, + alice: aliceChannel, + bob: bobChannel, + } +} + +// signRevokedCommitment makes Alice sign a new commitment for Bob and Bob +// accept it, which leaves Bob about to revoke his previous commitment. No +// aux signer is attached yet, so the CommitSig-time aux machinery stays out +// of the picture. +func signRevokedCommitment(t *testing.T, aliceChannel, + bobChannel *LightningChannel) { + + t.Helper() + + aliceNewCommit, err := aliceChannel.SignNextCommitment(t.Context()) + require.NoError(t, err) + err = bobChannel.ReceiveNewCommitment(aliceNewCommit.CommitSigs) + require.NoError(t, err) +} + +// setupRevocationAuxSigChannels creates the custom channel pair and runs the +// commitment dance right up to (but not including) Bob's revocation of the +// commitment carrying three HTLCs offered by Alice: index 0 (non-dust), index +// 1 (dust for both parties) and index 2 (dust under Bob's dust limit only). +// No fake revocation aux signer is attached yet. +func setupRevocationAuxSigChannels(t *testing.T) (*LightningChannel, + *LightningChannel) { + + t.Helper() + + aliceChannel, bobChannel, adder := newRevocationAuxSigChannels(t) + + require.EqualValues(t, 0, adder.fromAlice(revAuxNonDustAmt)) + require.EqualValues(t, 1, adder.fromAlice(revAuxDustAmt)) + require.EqualValues(t, 2, adder.fromAlice(revAuxBobDustAmt)) + + // The HTLC at index 2 is dust on the commitment Bob revokes, which is + // built with Bob's dust limit, and would not be with Alice's. + bobState := bobChannel.channelState + feePerKw := chainfee.SatPerKWeight(bobState.LocalCommitment.FeePerKw) + isDust := func(dustLimit btcutil.Amount) bool { + return HtlcIsDust( + bobState.ChanType, true, lntypes.Local, feePerKw, + revAuxBobDustAmt, dustLimit, true, + ) + } + require.True(t, isDust(bobState.LocalChanCfg.DustLimit)) + require.False(t, isDust(bobState.RemoteChanCfg.DustLimit)) + + // Lock the HTLCs into both commitments. + require.NoError(t, ForceStateTransition(aliceChannel, bobChannel)) + + // A further add triggers the state transition whose revocation we + // care about: Bob will revoke the commitment carrying HTLCs 0 to 2. + adder.fromAlice(revAuxNonDustAmt) + signRevokedCommitment(t, aliceChannel, bobChannel) + + return aliceChannel, bobChannel +} + +// revokedHtlcAuxSigs returns the revocation aux sig persisted for each HTLC +// of the given revoked state, keyed by direction and HTLC index. +func revokedHtlcAuxSigs(t *testing.T, channel *LightningChannel, + revokedHeight uint64) map[revocationAuxSigKey][]byte { + + t.Helper() + + revokedLog, _, err := channel.channelState.FindPreviousState( + revokedHeight, + ) + require.NoError(t, err) + + sigType := revocationAuxSigType + sigs := make(map[revocationAuxSigKey][]byte) + for _, htlcEntry := range revokedLog.HTLCEntries { + htlcIndex, err := htlcEntry.HtlcIndex.ValOpt().UnwrapOrErr( + errors.New("revocation log entry without HTLC index"), + ) + require.NoError(t, err) + + key := revocationAuxSigKey{ + // The log is ours, so an HTLC incoming to us is + // outgoing for the party that revoked the state. + signerIncoming: !htlcEntry.Incoming.Val, + htlcIndex: htlcIndex.Int(), + } + + blob := htlcEntry.CustomBlob.ValOpt().UnwrapOr(nil) + if len(blob) == 0 { + sigs[key] = nil + + continue + } + + records, err := lnwire.ParseCustomRecords(blob) + require.NoError(t, err) + sigs[key] = records[sigType] + } + + return sigs +} + +// TestRevocationAuxSigsRoundTrip exercises the full happy path on a custom +// channel: Bob's revocation signs the second-level path of every non-dust +// HTLC on the revoked commitment, ships the sigs in +// RevokeAndAck.CustomRecords, and Alice verifies them before accepting the +// revocation and persists them into the remote commitment's HTLC custom +// records. Dust HTLCs are excluded on both sides, as decided by the dust +// limit of the commitment's owner. +func TestRevocationAuxSigsRoundTrip(t *testing.T) { + t.Parallel() + + bobSigner := &fakeRevocationAuxSigner{} + aliceChannel, _, bobRevocation, aliceSigner := + setupRevocationAuxSigTest(t, bobSigner) + + // The remote chain tail is the commitment Bob is revoking; its height + // keys the revocation log entry we'll inspect below. + revokedHeight := aliceChannel.commitChains.Remote.tail().height + + // Bob signed exactly one HTLC: the two dust HTLCs must not have + // produced sign jobs. The HTLC is incoming to him, so the path he + // signs is the success, which carries no timeout. + require.Len(t, bobSigner.signJobs, 1) + signJob := bobSigner.signJobs[0] + require.True(t, signJob.Incoming) + require.EqualValues(t, 0, signJob.HTLC.HtlcIndex) + require.Equal(t, lntypes.Local, signJob.WhoseCommit) + require.True(t, signJob.HtlcTimeout.IsNone()) + + // The RevokeAndAck carries the packed sig for HTLC index 0 only. + recType := revokeAndAckAuxSigType + blob := bobRevocation.CustomRecords[recType] + require.NotEmpty(t, blob, "revocation aux sig blob missing") + + sigMap, err := unpackRevocationAuxSigs(blob) + require.NoError(t, err) + require.Len(t, sigMap, 1) + + htlcKey := revocationAuxSigKey{signerIncoming: true, htlcIndex: 0} + entry, ok := sigMap[htlcKey] + require.True(t, ok, "expected sig for HTLC index 0") + require.Equal(t, fakeAuxSigFor(true, 0), entry.sig) + + // Alice verifies and accepts. Her verifier insists on the sig of + // exactly this HTLC. + aliceSigner.strict = true + aliceChannel.auxSigner = fn.Some[AuxSigner](aliceSigner) + _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) + require.NoError(t, err) + + // Alice verified the non-dust HTLC only. From her side it is an + // outgoing HTLC on the remote commitment. + require.Len(t, aliceSigner.verifyJobs, 1) + verifyJob := aliceSigner.verifyJobs[0] + require.False(t, verifyJob.Incoming) + require.EqualValues(t, 0, verifyJob.HTLC.HtlcIndex) + require.Equal(t, lntypes.Remote, verifyJob.WhoseCommit) + require.True(t, verifyJob.HtlcTimeout.IsNone()) + require.Equal( + t, fakeAuxSigFor(true, 0), verifyJob.SigBlob.UnwrapOr(nil), + ) + + // The verified sig is persisted in the revocation log entry of the + // revoked commitment (the breach-time source of truth). The dust + // HTLCs have no entry there at all. + require.Equal(t, map[revocationAuxSigKey][]byte{ + htlcKey: fakeAuxSigFor(true, 0), + }, revokedHtlcAuxSigs(t, aliceChannel, revokedHeight)) +} + +// TestRevocationAuxSigsSameIndexBothDirections asserts that the revocation +// aux sigs of an HTLC offered by each party under the same HTLC index stay +// apart. Both parties count the HTLCs they offer from zero, so this is the +// normal state of any channel that carries traffic in both directions. +// Keying the sigs by the bare index would fold the two HTLCs into one entry: +// the receiver would then either reject an honest revocation, leaving the +// channel unusable, or store one HTLC's sig for the other, leaving it +// without breach protection. +func TestRevocationAuxSigsSameIndexBothDirections(t *testing.T) { + t.Parallel() + + aliceChannel, bobChannel, adder := newRevocationAuxSigChannels(t) + + // One HTLC in each direction, both at index 0. + require.EqualValues(t, 0, adder.fromAlice(revAuxNonDustAmt)) + require.EqualValues(t, 0, adder.fromBob(revAuxNonDustAmt)) + + // Lock both HTLCs into both commitments. + require.NoError(t, ForceStateTransition(aliceChannel, bobChannel)) + require.NoError(t, ForceStateTransition(bobChannel, aliceChannel)) + + // Bob is about to revoke the commitment carrying both. + adder.fromAlice(revAuxNonDustAmt) + signRevokedCommitment(t, aliceChannel, bobChannel) + + bobSigner := &fakeRevocationAuxSigner{} + bobChannel.auxSigner = fn.Some[AuxSigner](bobSigner) + bobRevocation, _, _, err := bobChannel.RevokeCurrentCommitment() + require.NoError(t, err) + + // Bob signed each HTLC once: the success path of the one he + // received, the timeout path of the one he offered. + require.Len(t, bobSigner.signJobs, 2) + for _, job := range bobSigner.signJobs { + require.EqualValues(t, 0, job.HTLC.HtlcIndex) + require.Equal(t, !job.Incoming, job.HtlcTimeout.IsSome()) + } + require.NotEqual( + t, bobSigner.signJobs[0].Incoming, + bobSigner.signJobs[1].Incoming, + ) + + // The blob carries one entry per HTLC, each with its own sig. + recType := revokeAndAckAuxSigType + sigMap, err := unpackRevocationAuxSigs( + bobRevocation.CustomRecords[recType], + ) + require.NoError(t, err) + require.Len(t, sigMap, 2) + + receivedKey := revocationAuxSigKey{signerIncoming: true} + offeredKey := revocationAuxSigKey{signerIncoming: false} + require.Equal(t, fakeAuxSigFor(true, 0), sigMap[receivedKey].sig) + require.Equal(t, fakeAuxSigFor(false, 0), sigMap[offeredKey].sig) + + // Alice's verifier rejects a sig that belongs to another HTLC, so + // accepting the revocation proves each sig reached the right one. + revokedHeight := aliceChannel.commitChains.Remote.tail().height + aliceSigner := &fakeRevocationAuxSigner{strict: true} + aliceChannel.auxSigner = fn.Some[AuxSigner](aliceSigner) + _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) + require.NoError(t, err) + require.Len(t, aliceSigner.verifyJobs, 2) + + // And each HTLC keeps its own sig in the revocation log. + require.Equal(t, map[revocationAuxSigKey][]byte{ + receivedKey: fakeAuxSigFor(true, 0), + offeredKey: fakeAuxSigFor(false, 0), + }, revokedHtlcAuxSigs(t, aliceChannel, revokedHeight)) +} + +// TestRevocationAuxSigsRejected asserts that ReceiveRevocation rejects the +// revocation BEFORE advancing the remote chain tail whenever the received +// aux sigs are unverifiable, malformed, or missing for a non-dust HTLC. +func TestRevocationAuxSigsRejected(t *testing.T) { + t.Parallel() + + recType := revokeAndAckAuxSigType + + // appendEntry adds the given entry to the blob of a revocation. + appendEntry := func(entry revocationAuxSigEntry) func( + *lnwire.RevokeAndAck, *fakeRevocationAuxSigner) { + + return func(rev *lnwire.RevokeAndAck, + _ *fakeRevocationAuxSigner) { + + mutatePackedEntries(t, rev, + func(entries []revocationAuxSigEntry, + ) []revocationAuxSigEntry { + + return append(entries, entry) + }, + ) + } + } + + testCases := []struct { + name string + mutate func(*lnwire.RevokeAndAck, *fakeRevocationAuxSigner) + wantErr string + }{{ + name: "verification failure", + mutate: func(_ *lnwire.RevokeAndAck, + s *fakeRevocationAuxSigner) { + + s.verifyErr = fmt.Errorf("sig does not verify") + }, + wantErr: "invalid revocation aux sigs", + }, { + name: "malformed blob", + mutate: func(rev *lnwire.RevokeAndAck, + _ *fakeRevocationAuxSigner) { + + rev.CustomRecords[recType] = []byte{0xde, 0xad} + }, + wantErr: "invalid revocation aux sigs", + }, { + name: "missing sig for non-dust HTLC", + mutate: func(rev *lnwire.RevokeAndAck, + _ *fakeRevocationAuxSigner) { + + // A well-formed blob whose sig is tagged with an HTLC + // index that isn't on the commitment. + packed, err := packRevocationAuxSigs( + []revocationAuxSigEntry{newRevAuxSigEntry( + true, 99, fakeAuxSigFor(true, 99), + )}, + ) + if err != nil { + panic(err) + } + rev.CustomRecords[recType] = packed + }, + wantErr: "no revocation aux sig for HTLC index 0", + }, { + name: "sig tagged with the wrong direction", + mutate: func(rev *lnwire.RevokeAndAck, + _ *fakeRevocationAuxSigner) { + + // The right index, but for an HTLC the signer would + // have offered. The HTLC on the commitment is one it + // received. + packed, err := packRevocationAuxSigs( + []revocationAuxSigEntry{newRevAuxSigEntry( + false, 0, fakeAuxSigFor(true, 0), + )}, + ) + if err != nil { + panic(err) + } + rev.CustomRecords[recType] = packed + }, + wantErr: "no revocation aux sig for HTLC index 0", + }, { + name: "withheld blob", + mutate: func(rev *lnwire.RevokeAndAck, + _ *fakeRevocationAuxSigner) { + + // A peer that strips the records entirely must not + // get its revocation accepted while non-dust HTLCs + // sit on the revoked commitment. + rev.CustomRecords = nil + }, + wantErr: "no revocation aux sig for HTLC index 0", + }, { + // An entry is there, but it carries no sig. Only the aux + // signer knows that the HTLC carries aux outputs and owes + // one, so it must be asked, and its refusal must fail the + // revocation. Otherwise a peer could opt out of the breach + // protection for exactly the states it means to broadcast. + name: "sig withheld from the entry", + mutate: func(rev *lnwire.RevokeAndAck, + s *fakeRevocationAuxSigner) { + + s.strict = true + mutatePackedEntries(t, rev, + func(entries []revocationAuxSigEntry, + ) []revocationAuxSigEntry { + + entries[0].sig = nil + + return entries + }, + ) + }, + wantErr: "missing aux sig for HTLC index 0", + }, { + name: "sig of another HTLC", + mutate: func(rev *lnwire.RevokeAndAck, + s *fakeRevocationAuxSigner) { + + s.strict = true + mutatePackedEntries(t, rev, + func(entries []revocationAuxSigEntry, + ) []revocationAuxSigEntry { + + entries[0].sig = fakeAuxSigFor( + false, 0, + ) + + return entries + }, + ) + }, + wantErr: "aux sig of another HTLC", + }, { + name: "extra entry for unknown HTLC index", + mutate: appendEntry( + newRevAuxSigEntry(true, 99, []byte{0x99}), + ), + wantErr: "unexpected revocation aux sig entry for HTLC " + + "index 99", + }, { + // The same index as the HTLC on the commitment, but in the + // direction nothing was offered in. + name: "extra entry for the other direction", + mutate: appendEntry( + newRevAuxSigEntry(false, 0, []byte{0x99}), + ), + wantErr: "unexpected revocation aux sig entry for HTLC " + + "index 0", + }, { + // HTLC index 1 is dust for both parties: an honest signer + // never packs an entry for it. + name: "entry for dust HTLC", + mutate: appendEntry( + newRevAuxSigEntry(true, 1, []byte{0x01}), + ), + wantErr: "unexpected revocation aux sig entry for HTLC " + + "index 1", + }, { + // HTLC index 2 is dust on the revoked commitment, which is + // built with the signer's dust limit. It would not be dust + // under ours, so this entry is only refused if the dust + // limit of the right party is applied. + name: "entry for HTLC that is dust for the signer only", + mutate: appendEntry( + newRevAuxSigEntry(true, 2, []byte{0x02}), + ), + wantErr: "unexpected revocation aux sig entry for HTLC " + + "index 2", + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + aliceChannel, _, bobRevocation, aliceSigner := + setupRevocationAuxSigTest( + t, &fakeRevocationAuxSigner{}, + ) + + tc.mutate(bobRevocation, aliceSigner) + + tailBefore := aliceChannel.commitChains.Remote. + tail().height + + aliceChannel.auxSigner = fn.Some[AuxSigner](aliceSigner) + _, _, err := aliceChannel.ReceiveRevocation( + bobRevocation, + ) + require.ErrorContains(t, err, tc.wantErr) + + // The revocation must not have been accepted. + require.Equal( + t, tailBefore, + aliceChannel.commitChains.Remote.tail().height, + ) + }) + } +} + +// TestRevocationAuxSigsBtcOnlyHtlcs asserts the lockstep-entry semantics for +// HTLCs that need no aux signature (BTC-only HTLCs on a custom channel): the +// revoking party still attaches one entry per non-dust HTLC, just without +// signature data. The receiver still hands the HTLC to its aux signer, which +// is the one to know that no sig is owed for it, and accepts the revocation +// when the signer agrees. This is what lets the receiver tell a sig-less +// HTLC apart from a withheld signature. +func TestRevocationAuxSigsBtcOnlyHtlcs(t *testing.T) { + t.Parallel() + + bobSigner := &fakeRevocationAuxSigner{noneSigs: true} + aliceChannel, _, bobRevocation, aliceSigner := + setupRevocationAuxSigTest(t, bobSigner) + + // The non-dust HTLC was still offered to the signer. + require.Len(t, bobSigner.signJobs, 1) + + // The RevokeAndAck carries a blob with a sig-less entry for the + // non-dust HTLC. + recType := revokeAndAckAuxSigType + blob := bobRevocation.CustomRecords[recType] + require.NotEmpty(t, blob, "lockstep entry blob missing") + + sigMap, err := unpackRevocationAuxSigs(blob) + require.NoError(t, err) + require.Len(t, sigMap, 1) + + htlcKey := revocationAuxSigKey{signerIncoming: true, htlcIndex: 0} + entry, ok := sigMap[htlcKey] + require.True(t, ok) + require.Empty(t, entry.sig) + + // Alice's aux signer is asked about the HTLC, with no sig attached, + // and has no objection. + revokedHeight := aliceChannel.commitChains.Remote.tail().height + aliceChannel.auxSigner = fn.Some[AuxSigner](aliceSigner) + _, _, err = aliceChannel.ReceiveRevocation(bobRevocation) + require.NoError(t, err) + + require.Len(t, aliceSigner.verifyJobs, 1) + require.True(t, aliceSigner.verifyJobs[0].SigBlob.IsNone()) + + // Nothing is stored for the HTLC. + require.Equal(t, map[revocationAuxSigKey][]byte{ + htlcKey: nil, + }, revokedHtlcAuxSigs(t, aliceChannel, revokedHeight)) +} + +// TestRevocationAuxSigsPeerRecordNotPersisted asserts that a custom record +// the peer put on its own UpdateAddHTLC under the type we store verified +// revocation aux sigs with never reaches the revocation log. The breach code +// reads that type back as a sig we verified, so a record the peer chose +// itself must not survive there, whether or not the revocation carries a sig +// for the HTLC. +func TestRevocationAuxSigsPeerRecordNotPersisted(t *testing.T) { + t.Parallel() + + sigType := revocationAuxSigType + + testCases := []struct { + name string + noneSigs bool + want []byte + }{{ + name: "replaced by the verified sig", + want: fakeAuxSigFor(false, 0), + }, { + name: "dropped when the revocation carries no sig", + noneSigs: true, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + aliceChannel, bobChannel, adder := + newRevocationAuxSigChannels(t) + + // Bob offers an HTLC and plants a record of our + // storage type on it. + preimage := bytes.Repeat([]byte{9}, 32) + htlc := &lnwire.UpdateAddHTLC{ + PaymentHash: sha256.Sum256(preimage), + Amount: lnwire.NewMSatFromSatoshis( + revAuxNonDustAmt, + ), + Expiry: uint32(10), + CustomRecords: lnwire.CustomRecords{ + sigType: []byte{0xba, 0xad}, + }, + } + htlcIndex, err := bobChannel.AddHTLC(htlc, nil) + require.NoError(t, err) + htlc.ID = htlcIndex + _, err = aliceChannel.ReceiveHTLC(htlc) + require.NoError(t, err) + + require.NoError( + t, + ForceStateTransition(bobChannel, aliceChannel), + ) + require.NoError( + t, + ForceStateTransition(aliceChannel, bobChannel), + ) + + // Bob revokes the commitment carrying the HTLC. + adder.fromAlice(revAuxNonDustAmt) + signRevokedCommitment(t, aliceChannel, bobChannel) + + bobChannel.auxSigner = fn.Some[AuxSigner]( + &fakeRevocationAuxSigner{noneSigs: tc.noneSigs}, + ) + bobRevocation, _, _, err := + bobChannel.RevokeCurrentCommitment() + require.NoError(t, err) + + revokedHeight := aliceChannel.commitChains.Remote. + tail().height + aliceChannel.auxSigner = fn.Some[AuxSigner]( + &fakeRevocationAuxSigner{}, + ) + _, _, err = aliceChannel.ReceiveRevocation( + bobRevocation, + ) + require.NoError(t, err) + + sigs := revokedHtlcAuxSigs( + t, aliceChannel, revokedHeight, + ) + require.Equal(t, tc.want, sigs[revocationAuxSigKey{ + signerIncoming: false, + htlcIndex: htlcIndex, + }]) + }) + } +} + +// TestRevocationAuxSigsRetransmission asserts that a retransmitted +// RevokeAndAck carries the exact same revocation aux sigs as the original: +// the packed blob is persisted atomically with the commitment advance and +// survives a restart, so a peer that never processed the original still +// receives the sigs it is owed on reestablish, and accepts them. +func TestRevocationAuxSigsRetransmission(t *testing.T) { + t.Parallel() + + bobSigner := &fakeRevocationAuxSigner{} + aliceChannel, bobChannel, bobRevocation, aliceSigner := + setupRevocationAuxSigTest(t, bobSigner) + + // Sanity check: Bob's original RevokeAndAck carries the sigs. + require.NotEmpty(t, bobRevocation.CustomRecords) + + // Alice never processes the revocation. On reconnect, her channel + // reestablish message tells Bob her view of his commitment tail is + // one behind, so Bob owes her the revocation again. + aliceSyncMsg, err := aliceChannel.channelState.ChanSyncMsg() + require.NoError(t, err) + + // Bob restarts: his channel is rebuilt from what is on disk, with a + // fresh signer. The retransmission must come from the persisted + // blob, not from signing the revoked commitment again. + bobState := bobChannel.channelState + bobState.RevocationAuxSigs = fn.None[tlv.Blob]() + require.NoError(t, bobState.Refresh()) + require.True( + t, bobState.RevocationAuxSigs.IsSome(), + "revocation aux sigs not persisted to disk", + ) + + restartedSigner := &fakeRevocationAuxSigner{} + restartedBob, err := NewLightningChannel( + bobChannel.Signer, bobState, bobChannel.sigPool, + WithLeafStore(&MockAuxLeafStore{}), + WithAuxSigner(restartedSigner), + ) + require.NoError(t, err) + + bobSyncMsg, err := bobState.ChanSyncMsg() + require.NoError(t, err) + + // Simulate the link/peer binding the generated musig nonces on + // reconnect. + aliceChannel.pendingVerificationNonce = &musig2.Nonces{ + PubNonce: aliceSyncMsg.LocalNonce.UnwrapOrFail(t).Val, + } + restartedBob.pendingVerificationNonce = &musig2.Nonces{ + PubNonce: bobSyncMsg.LocalNonce.UnwrapOrFail(t).Val, + } + + // Bob processes Alice's reestablish and must retransmit a single + // RevokeAndAck carrying the exact same aux sig records. + bobMsgs, _, _, err := restartedBob.ProcessChanSyncMsg( + t.Context(), aliceSyncMsg, + ) + require.NoError(t, err) + + // Bob may also owe Alice a CommitSig for the pending state + // transition; the RevokeAndAck retransmission is what we care about + // here. + var reRevoke *lnwire.RevokeAndAck + for _, msg := range bobMsgs { + if rev, ok := msg.(*lnwire.RevokeAndAck); ok { + reRevoke = rev + } + } + require.NotNil(t, reRevoke, "expected RevokeAndAck retransmission") + require.Equal( + t, bobRevocation.CustomRecords, reRevoke.CustomRecords, + "retransmitted RevokeAndAck must carry the original aux sigs", + ) + + // Whatever the restarted signer was asked to sign is a CommitSig for + // Alice's commitment, never the HTLCs of Bob's own revoked one. + for _, job := range restartedSigner.signJobs { + require.Equal(t, lntypes.Remote, job.WhoseCommit) + } + + // Alice verifies the retransmitted sigs like the original ones and + // accepts the revocation. + revokedHeight := aliceChannel.commitChains.Remote.tail().height + aliceSigner.strict = true + aliceChannel.auxSigner = fn.Some[AuxSigner](aliceSigner) + _, _, err = aliceChannel.ReceiveRevocation(reRevoke) + require.NoError(t, err) + require.Len(t, aliceSigner.verifyJobs, 1) + + htlcKey := revocationAuxSigKey{signerIncoming: true, htlcIndex: 0} + require.Equal(t, map[revocationAuxSigKey][]byte{ + htlcKey: fakeAuxSigFor(true, 0), + }, revokedHtlcAuxSigs(t, aliceChannel, revokedHeight)) +} + +// mutatePackedEntries unpacks the aux sig blob carried by the given +// RevokeAndAck, applies f to the entries (sorted by direction, then HTLC +// index), and packs the result back into the message. +func mutatePackedEntries(t *testing.T, rev *lnwire.RevokeAndAck, + f func([]revocationAuxSigEntry) []revocationAuxSigEntry) { + + t.Helper() + + recType := revokeAndAckAuxSigType + sigMap, err := unpackRevocationAuxSigs(rev.CustomRecords[recType]) + require.NoError(t, err) + + entries := make([]revocationAuxSigEntry, 0, len(sigMap)) + for _, entry := range sigMap { + entries = append(entries, entry) + } + slices.SortFunc(entries, func(i, j revocationAuxSigEntry) int { + if i.signerIncoming != j.signerIncoming { + if i.signerIncoming { + return 1 + } + + return -1 + } + + return cmp.Compare(i.htlcIndex, j.htlcIndex) + }) + + packed, err := packRevocationAuxSigs(f(entries)) + require.NoError(t, err) + + rev.CustomRecords[recType] = packed +} + +// TestRevocationAuxSigsSignFailure asserts that a failure of the aux signer +// at revocation time fails RevokeCurrentCommitment as a whole, BEFORE any +// state is advanced or persisted: sending a sig-less RevokeAndAck would only +// fail the channel on the peer's side. +func TestRevocationAuxSigsSignFailure(t *testing.T) { + t.Parallel() + + testCases := []struct { + name string + signer *fakeRevocationAuxSigner + }{{ + name: "batch submission fails", + signer: &fakeRevocationAuxSigner{ + signErr: fmt.Errorf("signer offline"), + }, + }, { + name: "sign job fails", + signer: &fakeRevocationAuxSigner{ + respErr: fmt.Errorf("cannot sign"), + }, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + _, bobChannel := setupRevocationAuxSigChannels(t) + bobChannel.auxSigner = fn.Some[AuxSigner](tc.signer) + + tailBefore := bobChannel.commitChains.Local. + tail().height + heightBefore := bobChannel.currentHeight + + _, _, _, err := bobChannel.RevokeCurrentCommitment() + require.ErrorContains( + t, err, "unable to sign local HTLC aux sigs", + ) + + // Nothing advanced: the revocation can be retried. + require.Equal( + t, tailBefore, + bobChannel.commitChains.Local.tail().height, + ) + require.Equal( + t, heightBefore, bobChannel.currentHeight, + ) + }) + } +} + +// revAuxSigBlob assembles a raw revocation aux sig blob from an entry count +// and already framed entries, bypassing the encoder so tests can build blobs +// an honest peer never would. +func revAuxSigBlob(t *testing.T, count uint64, framed ...[]byte) []byte { + t.Helper() + + var ( + buf bytes.Buffer + scratch [8]byte + ) + require.NoError(t, tlv.WriteVarInt(&buf, count, &scratch)) + for _, entry := range framed { + buf.Write(entry) + } + + return buf.Bytes() +} + +// framedRevAuxSigEntry returns the length-prefixed encoding of an entry, the +// way it sits in a blob. +func framedRevAuxSigEntry(t *testing.T, entry revocationAuxSigEntry) []byte { + t.Helper() + + var inner bytes.Buffer + require.NoError(t, entry.encode(&inner)) + + return framedRevAuxSigBytes(t, inner.Bytes()) +} + +// framedRevAuxSigBytes length-prefixes raw entry bytes. +func framedRevAuxSigBytes(t *testing.T, entry []byte) []byte { + t.Helper() + + var ( + buf bytes.Buffer + scratch [8]byte + ) + require.NoError( + t, tlv.WriteVarInt(&buf, uint64(len(entry)), &scratch), + ) + buf.Write(entry) + + return buf.Bytes() +} + +// TestUnpackRevocationAuxSigsCorrupt asserts that corrupt and hostile packed +// blobs are rejected by the decoder rather than yielding partial results. +func TestUnpackRevocationAuxSigsCorrupt(t *testing.T) { + t.Parallel() + + first := newRevAuxSigEntry(true, 0, fakeAuxSigFor(true, 0)) + second := newRevAuxSigEntry(true, 1, fakeAuxSigFor(true, 1)) + + valid, err := packRevocationAuxSigs( + []revocationAuxSigEntry{first, second}, + ) + require.NoError(t, err) + + // An entry stream with a single record of the given type and value. + record := func(typ tlv.Type, val []byte) []byte { + return append([]byte{byte(typ), byte(len(val))}, val...) + } + indexRecord := record(revAuxSigIndexType, make([]byte, 8)) + incomingRecord := record(revAuxSigIncomingType, []byte{1}) + + testCases := []struct { + name string + blob []byte + wantErr string + }{{ + name: "truncated mid-entry", + blob: valid[:len(valid)-3], + }, { + name: "truncated to first entry", + blob: valid[:len(valid)/2], + }, { + name: "garbage", + blob: []byte{0xde, 0xad, 0xbe, 0xef}, + }, { + // Two entries for the same HTLC: the second must not + // silently replace the first. + name: "duplicate entry", + blob: revAuxSigBlob( + t, 2, framedRevAuxSigEntry(t, first), + framedRevAuxSigEntry(t, first), + ), + wantErr: "duplicate entry for HTLC index 0", + }, { + name: "trailing bytes", + blob: append(slices.Clone(valid), 0x00), + wantErr: "1 trailing bytes after the last entry", + }, { + // Fewer entries declared than present leaves a whole entry + // behind as trailing data. + name: "undeclared entry", + blob: revAuxSigBlob( + t, 1, framedRevAuxSigEntry(t, first), + framedRevAuxSigEntry(t, second), + ), + wantErr: "trailing bytes after the last entry", + }, { + name: "count beyond the blob", + blob: revAuxSigBlob(t, 3, framedRevAuxSigEntry(t, first)), + wantErr: "read entry 1 length", + }, { + name: "entry length beyond the blob", + blob: append(revAuxSigBlob(t, 1), 0x40, 0x00), + wantErr: "entry 0 length 64 exceeds the 1 bytes left", + }, { + // The entry's declared length covers more than its records, + // so the stream ends in a record that is cut short. + name: "entry with a cut-off record", + blob: revAuxSigBlob(t, 1, framedRevAuxSigBytes( + t, append( + append(slices.Clone(indexRecord), + incomingRecord..., + ), 0x05, 0x04, 0x00, + ), + )), + wantErr: "decode entry 0", + }, { + name: "entry without an HTLC index", + blob: revAuxSigBlob( + t, 1, framedRevAuxSigBytes(t, incomingRecord), + ), + wantErr: "missing HTLC index", + }, { + name: "entry without a direction", + blob: revAuxSigBlob( + t, 1, framedRevAuxSigBytes(t, indexRecord), + ), + wantErr: "missing HTLC direction", + }, { + name: "entry with an invalid direction", + blob: revAuxSigBlob(t, 1, framedRevAuxSigBytes( + t, append( + slices.Clone(indexRecord), + record(revAuxSigIncomingType, []byte{2})..., + ), + )), + wantErr: "invalid HTLC direction 2", + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + _, err := unpackRevocationAuxSigs(tc.blob) + require.Error(t, err) + require.ErrorContains(t, err, tc.wantErr) + }) + } +} + +// TestUnpackRevocationAuxSigsHugeCount asserts that the entry count a peer +// declares is never used to size an allocation. The blob is a handful of +// bytes long; a count of billions must be rejected without the decoder ever +// reserving memory for that many entries, which would take the node down. +func TestUnpackRevocationAuxSigsHugeCount(t *testing.T) { + // Not parallel: the test measures this goroutine's allocations. + for _, count := range []uint64{1 << 22, 1 << 32, math.MaxUint64} { + blob := revAuxSigBlob(t, count) + require.LessOrEqual(t, len(blob), 9) + + var unpackErr error + allocated := testing.AllocsPerRun(1, func() { + _, unpackErr = unpackRevocationAuxSigs(blob) + }) + require.ErrorContains(t, unpackErr, "exceeds the 0 bytes") + + // A map sized for the declared count would be a single + // allocation as well, so bound the bytes, not the count. + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + _, _ = unpackRevocationAuxSigs(blob) + runtime.ReadMemStats(&after) + + require.Less(t, allocated, float64(32)) + require.Less( + t, after.TotalAlloc-before.TotalAlloc, + uint64(1<<20), "decoding a %d byte blob allocated "+ + "memory for its declared entry count", + len(blob), + ) + } +} + +// TestRevocationAuxSigsGateFollowsRevokedCommitment asserts that whether a +// revocation carries aux sigs is decided by the sighash recorded for the +// commitment being revoked, not by the one new commitments use. While the +// sighash type of a channel is switching, the two differ, and both peers +// must still agree on which revocations carry the signatures. +func TestRevocationAuxSigsGateFollowsRevokedCommitment(t *testing.T) { + t.Parallel() + + channel, signer := newLiveAuxSignerChannel(t) + + legacyCommit := &commitment{} + deterministicCommit := &commitment{ + customBlob: fn.Some(sigHashDefaultBlob), + } + + // New commitments use the legacy sighash, yet revoking a commitment + // that was built with SigHashDefault still exchanges the sigs. + require.False(t, channel.IsChanSigHashDefault()) + require.False(t, channel.exchangesRevocationAuxSigs(legacyCommit)) + require.True( + t, channel.exchangesRevocationAuxSigs(deterministicCommit), + ) + + // New commitments switch to SigHashDefault. Revoking a commitment + // that predates the switch must not start exchanging the sigs: its + // second-level HTLCs are not deterministic and the peer does not + // expect any. + signer.live = fn.Some(txscript.SigHashDefault) + channel.RefreshHtlcSigHashType() + require.True(t, channel.IsChanSigHashDefault()) + require.False(t, channel.exchangesRevocationAuxSigs(legacyCommit)) + require.True( + t, channel.exchangesRevocationAuxSigs(deterministicCommit), + ) + + // Without a commitment or an aux signer nothing is exchanged. + require.False(t, channel.exchangesRevocationAuxSigs(nil)) + channel.auxSigner = fn.None[AuxSigner]() + require.False( + t, channel.exchangesRevocationAuxSigs(deterministicCommit), + ) +} diff --git a/lnwire/revoke_and_ack.go b/lnwire/revoke_and_ack.go index e2a4c930798..222ef35e13e 100644 --- a/lnwire/revoke_and_ack.go +++ b/lnwire/revoke_and_ack.go @@ -42,6 +42,13 @@ type RevokeAndAck struct { // nonces, keyed by TXID. This is used for splice nonce coordination. LocalNonces OptLocalNonces + // CustomRecords is a set of custom TLV records that can be used to + // attach auxiliary data to the revocation message. For custom + // channels, this carries the revoking party's aux signatures for + // the second-level HTLC transactions on the commitment being + // revoked. + CustomRecords CustomRecords + // ExtraData is the set of data that was appended to this message to // fill out the full maximum transport message size. These fields can // be used to specify optional data such as custom TLV fields. @@ -50,9 +57,7 @@ type RevokeAndAck struct { // NewRevokeAndAck creates a new RevokeAndAck message. func NewRevokeAndAck() *RevokeAndAck { - return &RevokeAndAck{ - ExtraData: make([]byte, 0), - } + return &RevokeAndAck{} } // A compile time check to ensure RevokeAndAck implements the lnwire.Message @@ -68,43 +73,41 @@ var _ SizeableMessage = (*RevokeAndAck)(nil) // // This is part of the lnwire.Message interface. func (c *RevokeAndAck) Decode(r io.Reader, pver uint32) error { + // msgExtraData is a temporary variable used to read the message extra + // data field from the reader. + var msgExtraData ExtraOpaqueData + err := ReadElements(r, &c.ChanID, c.Revocation[:], &c.NextRevocationKey, + &msgExtraData, ) if err != nil { return err } - var tlvRecords ExtraOpaqueData - if err := ReadElements(r, &tlvRecords); err != nil { - return err - } - - var ( - localNonce = c.LocalNonce.Zero() - localNoncesData LocalNoncesData - ) + // Extract TLV records from the extra data field. + localNonce := c.LocalNonce.Zero() + var localNoncesData LocalNoncesData - typeMap, err := tlvRecords.ExtractRecords( - &localNonce, &localNoncesData, + customRecords, parsed, extraData, err := ParseAndExtractCustomRecords( + msgExtraData, &localNonce, &localNoncesData, ) if err != nil { return err } // Set the corresponding TLV types if they were included in the stream. - if val, ok := typeMap[c.LocalNonce.TlvType()]; ok && val == nil { + if _, ok := parsed[localNonce.TlvType()]; ok { c.LocalNonce = tlv.SomeRecordT(localNonce) } - if val, ok := typeMap[(LocalNoncesRecordTypeDef)(nil).TypeVal()]; ok && val == nil { //nolint:ll + if _, ok := parsed[(LocalNoncesRecordTypeDef)(nil).TypeVal()]; ok { c.LocalNonces = SomeLocalNonces(localNoncesData) } - if len(tlvRecords) != 0 { - c.ExtraData = tlvRecords - } + c.CustomRecords = customRecords + c.ExtraData = extraData return nil } @@ -121,7 +124,10 @@ func (c *RevokeAndAck) Encode(w *bytes.Buffer, pver uint32) error { c.LocalNonces.WhenSome(func(ln LocalNoncesData) { recordProducers = append(recordProducers, &ln) }) - err := EncodeMessageExtraData(&c.ExtraData, recordProducers...) + + extraData, err := MergeAndEncode( + recordProducers, c.ExtraData, c.CustomRecords, + ) if err != nil { return err } @@ -138,7 +144,7 @@ func (c *RevokeAndAck) Encode(w *bytes.Buffer, pver uint32) error { return err } - return WriteBytes(w, c.ExtraData) + return WriteBytes(w, extraData) } // MsgType returns the integer uniquely identifying this message type on the diff --git a/lnwire/revoke_and_ack_test.go b/lnwire/revoke_and_ack_test.go new file mode 100644 index 00000000000..93098919d35 --- /dev/null +++ b/lnwire/revoke_and_ack_test.go @@ -0,0 +1,110 @@ +package lnwire + +import ( + "bytes" + "fmt" + "testing" + + "github.com/stretchr/testify/require" +) + +// TestRevokeAndAckEncodeDecode tests RevokeAndAck message encoding and +// decoding with and without custom records, asserting that a message without +// custom records is byte-identical to its pre-CustomRecords encoding. +func TestRevokeAndAckEncodeDecode(t *testing.T) { + t.Parallel() + + chanIDBytes, err := generateRandomBytes(32) + require.NoError(t, err) + var chanID ChannelID + copy(chanID[:], chanIDBytes) + + revBytes, err := generateRandomBytes(32) + require.NoError(t, err) + var revocation [32]byte + copy(revocation[:], revBytes) + + nextRevKey, err := pubkeyFromHex( + "0228f2af0abe322403480fb3ee172f7f1601e67d1da6cad40b54c4468d4" + + "8236c39", + ) + require.NoError(t, err) + + recordValue, err := generateRandomBytes(10) + require.NoError(t, err) + customRecords := CustomRecords{ + uint64(MinCustomRecordsTlvType): recordValue, + } + + testCases := []struct { + name string + msg RevokeAndAck + expectEncodeError bool + }{{ + name: "with custom records", + msg: RevokeAndAck{ + ChanID: chanID, + Revocation: revocation, + NextRevocationKey: nextRevKey, + CustomRecords: customRecords, + }, + }, { + name: "without custom records", + msg: RevokeAndAck{ + ChanID: chanID, + Revocation: revocation, + NextRevocationKey: nextRevKey, + }, + }, { + name: "invalid custom records", + msg: RevokeAndAck{ + ChanID: chanID, + Revocation: revocation, + NextRevocationKey: nextRevKey, + CustomRecords: CustomRecords{ + MinCustomRecordsTlvType - 1: recordValue, + }, + }, + expectEncodeError: true, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var buf bytes.Buffer + err := tc.msg.Encode(&buf, 0) + if tc.expectEncodeError { + require.Error(t, err) + return + } + require.NoError(t, err) + + var decoded RevokeAndAck + err = decoded.Decode(bytes.NewReader(buf.Bytes()), 0) + require.NoError(t, err) + require.Equal(t, tc.msg, decoded) + }) + } + + // A message without custom records must be byte-identical to the + // legacy encoding: fixed fields only, no TLV appendix at all. + var legacyBuf bytes.Buffer + require.NoError( + t, WriteChannelID(&legacyBuf, chanID), + ) + require.NoError(t, WriteBytes(&legacyBuf, revocation[:])) + require.NoError(t, WritePublicKey(&legacyBuf, nextRevKey)) + + var noRecordsBuf bytes.Buffer + msg := RevokeAndAck{ + ChanID: chanID, + Revocation: revocation, + NextRevocationKey: nextRevKey, + } + require.NoError(t, msg.Encode(&noRecordsBuf, 0)) + require.Equal( + t, legacyBuf.Bytes(), noRecordsBuf.Bytes(), + fmt.Sprintf("no-records encoding must stay byte-identical "+ + "to the legacy wire format, got %x", + noRecordsBuf.Bytes()), + ) +} diff --git a/server.go b/server.go index 45aec781856..527a2e211ad 100644 --- a/server.go +++ b/server.go @@ -1543,7 +1543,8 @@ func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr, Store: contractcourt.NewRetributionStore( dbs.ChanStateDB, ), - AuxSweeper: s.implCfg.AuxSweeper, + AuxSweeper: s.implCfg.AuxSweeper, + AuxResolver: s.implCfg.AuxContractResolver, }, ) diff --git a/sweep/fee_bumper.go b/sweep/fee_bumper.go index 57b933a2dd5..196e4b26320 100644 --- a/sweep/fee_bumper.go +++ b/sweep/fee_bumper.go @@ -1257,6 +1257,7 @@ func (t *TxPublisher) broadcast(record *monitorRecord) (*BumpResult, error) { err := fn.MapOptionZ(t.cfg.AuxSweeper, func(aux AuxSweeper) error { return aux.NotifyBroadcast( record.req, tx, record.fee, record.outpointToTxIndex, + AuxNotifyOpts{}, ) }) if err != nil { diff --git a/sweep/interface.go b/sweep/interface.go index 98863e2e115..ad75e878760 100644 --- a/sweep/interface.go +++ b/sweep/interface.go @@ -75,6 +75,33 @@ type SweepOutput struct { //nolint:revive InternalKey fn.Option[keychain.KeyDescriptor] } +// AuxNotifyOpts contains options for the NotifyBroadcast call on the +// AuxSweeper interface. +type AuxNotifyOpts struct { + // SkipBroadcast indicates that the transaction is already confirmed + // on-chain and must not be broadcast again. It is set by the breach + // arbiter, which only reports a justice transaction once it has + // confirmed. + SkipBroadcast bool + + // ConfirmHeight is an optional confirmation height hint for the + // transaction. When set, the porter uses this as the height hint + // when scanning for the on-chain confirmation instead of the + // current chain tip. This is critical for breach justice sweeps + // where NotifyBroadcast is called after the tx has already been + // confirmed and the chain has advanced past the confirmation + // block. + ConfirmHeight uint32 + + // LookupInputProofs indicates that the aux sweeper should look + // up the input proofs from its proof archive rather than using + // the proofs embedded in the resolution blob. This is needed + // when the resolution blob carries a stale proof (e.g. the + // commit-level proof for a second-level HTLC output that has + // since been imported with a proper second-level proof). + LookupInputProofs bool +} + // AuxSweeper is used to enable a 3rd party to further shape the sweeping // transaction by adding a set of extra outputs to the sweeping transaction. type AuxSweeper interface { @@ -101,5 +128,6 @@ type AuxSweeper interface { // of a sweep transaction, generated by the passed BumpRequest. NotifyBroadcast(req *BumpRequest, tx *wire.MsgTx, totalFees btcutil.Amount, - outpointToTxIndex map[wire.OutPoint]int) error + outpointToTxIndex map[wire.OutPoint]int, + opts AuxNotifyOpts) error } diff --git a/sweep/mock_test.go b/sweep/mock_test.go index 88065bfc024..02b00ae7671 100644 --- a/sweep/mock_test.go +++ b/sweep/mock_test.go @@ -366,7 +366,7 @@ func (m *MockAuxSweeper) ExtraBudgetForInputs( // NotifyBroadcast is used to notify external callers of the broadcast // of a sweep transaction, generated by the passed BumpRequest. func (*MockAuxSweeper) NotifyBroadcast(_ *BumpRequest, _ *wire.MsgTx, - _ btcutil.Amount, _ map[wire.OutPoint]int) error { + _ btcutil.Amount, _ map[wire.OutPoint]int, _ AuxNotifyOpts) error { return nil }