Merge pull request #11330 from Roasbeef/remote-next-rev-option
What changed, and why it matters
This commit hardens how LND handles revocation messages during Lightning channel state updates. Previously, parts of the code treated a missing 'next revocation point' as a nil pointer, which could lead to state updates being applied in the wrong order or to invalid revocations partially updating the channel state. The change makes the optional nature of that point explicit, validates the revocation before touching stored secrets, and rejects unexpected revocations cleanly. It is a defensive bug-fix rather than a confirmed exploited vulnerability.
Treat this as a security-hardening bug fix and include it in the next maintenance release. Operators should upgrade to a version containing this commit. No immediate incident-response action is required unless anomalous channel-force-close patterns are already observed, in which case channels should be monitored for unexpected revocation errors.
Security signals we found
State-transition validation reordered before destructive bookkeeping in ReceiveRevocation
New error ErrUnexpectedRevocation returned when no unacked remote commitment exists
New error ErrNoNextRevocation returned when the remote next revocation point is unknown
Revocation secret added to RevocationStore only after point validation succeeds
Nil-pointer-like optional field converted to explicit fn.Option type
chain_watcher now refuses to sign a remote pending commitment if next revocation point is absent
Release notes explicitly label the change as a bug fix for revocation processing
Evidence from the diff
The patch refactors RemoteNextRevocation from a *btcec.PublicKey pointer to fn.Option[btcec.PublicKey] across channeldb, chanstate, lnwallet, htlcswitch, peer and funding packages. This forces every caller to handle the ‘not yet known’ case explicitly. The key behavioral change is in lnwallet/channel.go ReceiveRevocation: it now (1) checks that the remote commitment chain has an unacked commitment, (2) requires the next revocation point to be known, (3) verifies the revealed secret derives the current revocation point, and only then (4) adds the secret to the revocation store and advances the revocation state. New tests verify that invalid or unexpected revocations leave state unchanged and do not block later valid transitions. Release notes describe this as ordering ‘state-transition and key checks before their corresponding bookkeeping updates’.
Changed components
lnwallet/channel.gochanneldb/channel.gochanstate/open_channel.gochanstate/kv_commitment.gochanstate/kv_close_summary.gofunding/manager.gohtlcswitch/link.gopeer/brontide.gocontractcourt/chain_watcher.goInspect captured patch +578 / −148
### channeldb/channel.go
@@ -1316,9 +1316,9 @@ func (c *ChannelStateDB) RemoteUnsignedLocalUpdates(channel *OpenChannel) (
// InsertNextRevocation inserts the next commitment point into the persisted
// channel state.
func (c *ChannelStateDB) InsertNextRevocation(channel *OpenChannel,
- revKey *btcec.PublicKey) error {
+ revKey btcec.PublicKey) error {
- channel.RemoteNextRevocation = revKey
+ channel.RemoteNextRevocation = fn.Some(revKey)
err := kvdb.Update(c.backend, func(tx kvdb.RwTx) error {
chanBucket, err := fetchChanBucketRw(
### channeldb/channel_test.go
@@ -256,7 +256,9 @@ func createTestChannel(t *testing.T, cdb *ChannelStateDB,
err = params.channel.CloseChannel(&ChannelCloseSummary{
RemotePub: params.channel.IdentityPub,
RemoteCurrentRevocation: params.channel.IdentityPub,
- RemoteNextRevocation: params.channel.IdentityPub,
+ RemoteNextRevocation: fn.Some(
+ *params.channel.IdentityPub,
+ ),
})
require.NoError(t, err, "unable to close channel")
}
@@ -410,7 +412,7 @@ func createTestChannelState(t *testing.T, cdb *ChannelStateDB) *OpenChannel {
},
NumConfsRequired: 4,
RemoteCurrentRevocation: privKey.PubKey(),
- RemoteNextRevocation: privKey.PubKey(),
+ RemoteNextRevocation: fn.Some(*privKey.PubKey()),
RevocationProducer: producer,
RevocationStore: store,
Db: cdb,
@@ -479,7 +481,7 @@ func TestOpenChannelPutGetDelete(t *testing.T) {
// post-funding revocation exchange.
nextRevKey, err := btcec.NewPrivateKey()
require.NoError(t, err, "unable to create new private key")
- if err := state.InsertNextRevocation(nextRevKey.PubKey()); err != nil {
+ if err := state.InsertNextRevocation(*nextRevKey.PubKey()); err != nil {
t.Fatalf("unable to update revocation: %v", err)
}
@@ -488,9 +490,11 @@ func TestOpenChannelPutGetDelete(t *testing.T) {
updatedChan := openChannels[0]
// Ensure that the revocation was set properly.
- if !nextRevKey.PubKey().IsEqual(updatedChan.RemoteNextRevocation) {
- t.Fatalf("next revocation wasn't updated")
- }
+ require.Equal(
+ t, fn.Some(*nextRevKey.PubKey()),
+ updatedChan.RemoteNextRevocation,
+ "next revocation wasn't updated",
+ )
// Finally to wrap up the test, delete the state of the channel within
// the database. This involves "closing" the channel which removes all
@@ -837,10 +841,11 @@ func TestChannelStateTransition(t *testing.T) {
// needed to rectify any fishy behavior by the remote party. Modify the
// current uncollapsed revocation state to simulate a state transition
// by the remote party.
- channel.RemoteCurrentRevocation = channel.RemoteNextRevocation
+ nextPoint := channel.RemoteNextRevocation.UnwrapOrFail(t)
+ channel.RemoteCurrentRevocation = &nextPoint
newPriv, err := btcec.NewPrivateKey()
require.NoError(t, err, "unable to generate key")
- channel.RemoteNextRevocation = newPriv.PubKey()
+ channel.RemoteNextRevocation = fn.Some(*newPriv.PubKey())
fwdPkg := NewFwdPkg(channel.ShortChanID(), oldRemoteCommit.CommitHeight,
diskCommitDiff.LogUpdates, nil)
@@ -932,9 +937,11 @@ func TestChannelStateTransition(t *testing.T) {
if !channel.RemoteCurrentRevocation.IsEqual(updatedChannel[0].RemoteCurrentRevocation) {
t.Fatalf("revocation state was not synced")
}
- if !channel.RemoteNextRevocation.IsEqual(updatedChannel[0].RemoteNextRevocation) {
- t.Fatalf("revocation state was not synced")
- }
+ require.Equal(
+ t, channel.RemoteNextRevocation,
+ updatedChannel[0].RemoteNextRevocation,
+ "revocation state was not synced",
+ )
// At this point, we should have 2 forwarding packages added.
fwdPkgs := loadFwdPkgs(
@@ -1117,6 +1124,70 @@ func TestFetchPendingChannels(t *testing.T) {
}
}
+// TestRemoteNextRevocationOptional tests that a channel without the remote
+// party's next revocation point round trips through the database as None,
+// that inserting the point later persists it, and that close summaries keep
+// the point, or the lack of one, as well.
+func TestRemoteNextRevocationOptional(t *testing.T) {
+ t.Parallel()
+
+ fullDB, err := MakeTestDB(t)
+ require.NoError(t, err)
+
+ cdb := fullDB.ChannelStateDB()
+
+ // We'll start with a channel that confirmed, but for which the remote
+ // party never sent channel_ready.
+ noNextPoint := func(params *testChannelParams) {
+ params.channel.RemoteNextRevocation = fn.None[btcec.PublicKey]()
+ }
+ state := createTestChannel(t, cdb, openChannelOption(), noNextPoint)
+
+ fetchState := func() *OpenChannel {
+ t.Helper()
+
+ channels, err := cdb.FetchOpenChannels(state.IdentityPub)
+ require.NoError(t, err)
+ require.Len(t, channels, 1)
+
+ return channels[0]
+ }
+
+ // The revocation state on disk shouldn't carry a next point.
+ require.True(t, fetchState().RemoteNextRevocation.IsNone())
+
+ // Once channel_ready arrives, the point is inserted and should be
+ // read back as is.
+ nextPriv, err := btcec.NewPrivateKey()
+ require.NoError(t, err)
+ require.NoError(t, state.InsertNextRevocation(*nextPriv.PubKey()))
+
+ require.Equal(
+ t, fn.Some(*nextPriv.PubKey()),
+ fetchState().RemoteNextRevocation,
+ )
+
+ // Close summaries also persist the point only if it's present.
+ for _, nextPoint := range []fn.Option[btcec.PublicKey]{
+ fn.None[btcec.PublicKey](), fn.Some(*nextPriv.PubKey()),
+ } {
+ summary := &ChannelCloseSummary{
+ RemotePub: state.IdentityPub,
+ RemoteCurrentRevocation: state.IdentityPub,
+ RemoteNextRevocation: nextPoint,
+ }
+
+ var b bytes.Buffer
+ require.NoError(t, serializeChannelCloseSummary(&b, summary))
+
+ decoded, err := deserializeCloseChannelSummary(&b)
+ require.NoError(t, err)
+ require.Equal(
+ t, nextPoint, decoded.RemoteNextRevocation,
+ )
+ }
+}
+
func TestFetchClosedChannels(t *testing.T) {
t.Parallel()
### channeldb/legacy_serialization.go
@@ -1,7 +1,11 @@
package channeldb
import (
+ "errors"
"io"
+
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/lightningnetwork/lnd/fn/v2"
)
// deserializeCloseChannelSummaryV6 reads the v6 database format for
@@ -43,11 +47,16 @@ func deserializeCloseChannelSummaryV6(r io.Reader) (*ChannelCloseSummary, error)
// channel_ready message, then this can be nil. As a result, we'll use
// the same technique to read the field, only if there's still data
// left in the buffer.
- err = ReadElements(r, &c.RemoteNextRevocation)
- if err != nil && err != io.EOF {
- // If we got a non-eof error, then we know there's an actually
- // issue. Otherwise, it may have been the case that this
- // summary didn't have the set of optional fields.
+ var nextRevocation *btcec.PublicKey
+ err = ReadElements(r, &nextRevocation)
+ switch {
+ case err == nil:
+ c.RemoteNextRevocation = fn.Some(*nextRevocation)
+
+ // If we got a non-eof error, then we know there's an actually issue.
+ // Otherwise, it may have been the case that this summary didn't have
+ // the set of optional fields.
+ case !errors.Is(err, io.EOF):
return nil, err
}
### chanstate/close_summary.go
@@ -5,6 +5,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/lnwire"
)
@@ -114,8 +115,9 @@ type ChannelCloseSummary struct {
// RemoteNextRevocation is the revocation key to be used for the *next*
// commitment transaction we create for the local node. Within the
// specification, this value is referred to as the
- // per-commitment-point.
- RemoteNextRevocation *btcec.PublicKey
+ // per-commitment-point. It's None if the channel was closed before the
+ // remote party sent channel_ready.
+ RemoteNextRevocation fn.Option[btcec.PublicKey]
// LocalChanConfig is the channel configuration for the local node.
LocalChanConfig ChannelConfig
### chanstate/interface.go
@@ -266,7 +266,7 @@ type OpenChannelCommitmentMutationStore interface {
// InsertNextRevocation inserts the next commitment point into the
// persisted channel state.
InsertNextRevocation(channel *OpenChannel,
- revKey *btcec.PublicKey) error
+ revKey btcec.PublicKey) error
// AdvanceCommitChainTail records the new state transition within the
// revocation log and promotes the pending remote commitment to the
### chanstate/kv_close_summary.go
@@ -5,6 +5,8 @@ import (
"errors"
"io"
+ "github.com/btcsuite/btcd/btcec/v2"
+ "github.com/lightningnetwork/lnd/fn/v2"
"github.com/lightningnetwork/lnd/kvdb"
"github.com/lightningnetwork/lnd/lnwire"
)
@@ -67,15 +69,19 @@ func SerializeChannelCloseSummary(w io.Writer,
// channel to be closed before we learn of the next unrevoked
// revocation point for the remote party. Write a boolean indicating
// whether this field is present or not.
- if err := WriteElements(w, cs.RemoteNextRevocation != nil); err != nil {
+ err = WriteElements(w, cs.RemoteNextRevocation.IsSome())
+ if err != nil {
return err
}
// Write the field, if present.
- if cs.RemoteNextRevocation != nil {
- if err = WriteElements(w, cs.RemoteNextRevocation); err != nil {
- return err
- }
+ err = fn.MapOptionZ(
+ cs.RemoteNextRevocation, func(key btcec.PublicKey) error {
+ return WriteElements(w, &key)
+ },
+ )
+ if err != nil {
+ return err
}
// Write whether the channel sync message is present.
@@ -140,10 +146,12 @@ func DeserializeCloseChannelSummary(r io.Reader) (*ChannelCloseSummary, error) {
// If this field was written, read it.
if hasRemoteNextRevocation {
- err = ReadElements(r, &c.RemoteNextRevocation)
+ var nextRevocation *btcec.PublicKey
+ err = ReadElements(r, &nextRevocation)
if err != nil {
return nil, err
}
+ c.RemoteNextRevocation = fn.Some(*nextRevocation)
}
// Check if we have a channel sync message to read.
### chanstate/kv_commitment.go
@@ -298,11 +298,13 @@ func PutChanRevocationState(chanBucket kvdb.RwBucket,
// If the next revocation is present, which is only the case after the
// ChannelReady message has been sent, then we'll write it to disk.
- if channel.RemoteNextRevocation != nil {
- err = WriteElements(&b, channel.RemoteNextRevocation)
- if err != nil {
- return err
- }
+ err = fn.MapOptionZ(
+ channel.RemoteNextRevocation, func(key btcec.PublicKey) error {
+ return WriteElements(&b, &key)
+ },
+ )
+ if err != nil {
+ return err
}
return chanBucket.Put(revocationStateKey, b.Bytes())
@@ -387,7 +389,13 @@ func FetchChanRevocationState(chanBucket kvdb.RBucket,
// Otherwise we'll read the next revocation for the remote party which
// is always the last item within the buffer.
- return ReadElements(r, &channel.RemoteNextRevocation)
+ var nextRevocation *btcec.PublicKey
+ if err := ReadElements(r, &nextRevocation); err != nil {
+ return err
+ }
+ channel.RemoteNextRevocation = fn.Some(*nextRevocation)
+
+ return nil
}
// DeleteOpenChannel deletes the persisted open channel state from the channel
### chanstate/open_channel.go
@@ -154,8 +154,9 @@ type OpenChannel struct {
// RemoteNextRevocation is the revocation key to be used for the *next*
// commitment transaction we create for the local node. Within the
// specification, this value is referred to as the
- // per-commitment-point.
- RemoteNextRevocation *btcec.PublicKey
+ // per-commitment-point. It's only known once the remote party has sent
+ // channel_ready, so it's None until then.
+ RemoteNextRevocation fn.Option[btcec.PublicKey]
// RevocationProducer is used to generate the revocation in such a way
// that remote side might store it efficiently and have the ability to
@@ -947,7 +948,7 @@ func (c *OpenChannel) RemoteUnsignedLocalUpdates() ([]LogUpdate, error) {
//
// NOTE: If this method isn't called, then the target channel won't be able to
// propose new states for the commitment state of the remote party.
-func (c *OpenChannel) InsertNextRevocation(revKey *btcec.PublicKey) error {
+func (c *OpenChannel) InsertNextRevocation(revKey btcec.PublicKey) error {
c.Lock()
defer c.Unlock()
### contractcourt/breach_arbitrator_test.go
@@ -2420,15 +2420,15 @@ func initRevocationWindows(chanA, chanB *lnwallet.LightningChannel) error {
if err != nil {
return err
}
- if err := chanB.InitNextRevocation(aliceNextRevoke); err != nil {
+ if err := chanB.InitNextRevocation(*aliceNextRevoke); err != nil {
return err
}
bobNextRevoke, err := chanB.NextRevocationKey()
if err != nil {
return err
}
- if err := chanA.InitNextRevocation(bobNextRevoke); err != nil {
+ if err := chanA.InitNextRevocation(*bobNextRevoke); err != nil {
return err
}
### contractcourt/chain_watcher.go
@@ -1129,11 +1129,21 @@ func (c *chainWatcher) handleKnownRemoteState(
log.Infof("Remote party broadcast pending set, "+
"commit_num=%v", chainSet.remoteStateNum+1)
+ // We only sign a pending commitment for the remote party once
+ // we know their next revocation point, which is the point for
+ // that commitment.
+ commitPoint, err := c.cfg.chanState.RemoteNextRevocation.
+ UnwrapOrErr(lnwallet.ErrNoNextRevocation)
+ if err != nil {
+ return false, fmt.Errorf("unable to handle remote "+
+ "pending close for chan_point=%v: %w",
+ c.cfg.chanState.FundingOutpoint, err)
+ }
+
chainSet.commitSet.ConfCommitKey = fn.Some(RemotePendingHtlcSet)
- err := c.dispatchRemoteForceClose(
+ err = c.dispatchRemoteForceClose(
commitSpend, *chainSet.remotePendingCommit,
- chainSet.commitSet,
- c.cfg.chanState.RemoteNextRevocation,
+ chainSet.commitSet, &commitPoint,
)
if err != nil {
return false, fmt.Errorf("unable to handle remote "+
### docs/release-notes/release-notes-0.20.6.md
@@ -21,6 +21,11 @@
# Bug Fixes
+* Revocation processing now [orders its state-transition and key checks before
+ their corresponding bookkeeping updates](https://github.com/lightningnetwork/lnd/pull/11330).
+ The remote party's next revocation point now uses `fn.Option`, so callers
+ handle the optional state explicitly.
+
* Taproot commitment signing and verification now [release transient MuSig2
signer sessions](https://github.com/lightningnetwork/lnd/pull/11246) once
the local node no longer needs them. Force-close and cooperative-close
### docs/release-notes/release-notes-0.21.5.md
@@ -21,6 +21,11 @@
# Bug Fixes
+* Revocation processing now [orders its state-transition and key checks before
+ their corresponding bookkeeping updates](https://github.com/lightningnetwork/lnd/pull/11330).
+ The remote party's next revocation point now uses `fn.Option`, so callers
+ handle the optional state explicitly.
+
* Taproot commitment signing and verification now [release transient MuSig2
signer sessions](https://github.com/lightningnetwork/lnd/pull/11246) once
the local node no longer needs them. Force-close and cooperative-close
### funding/manager.go
@@ -3645,7 +3645,7 @@ func (f *Manager) receivedChannelReady(node *btcec.PublicKey,
// If we haven't insert the next revocation point, we haven't finished
// processing the channel ready message.
- if channel.RemoteNextRevocation == nil {
+ if channel.RemoteNextRevocation.IsNone() {
return false, nil
}
@@ -4120,14 +4120,14 @@ func (f *Manager) handleChannelReady(peer lnpeer.Peer,
return
}
- // If the RemoteNextRevocation is non-nil, then the channel has
+ // If the RemoteNextRevocation is set, then the channel has
// already been fully established and we've processed channel_ready
// for it at least once. We short-circuit inline to avoid redoing the
// heavy work in processChannelReady (DB writes, nonce generation,
// AddNewChannel) on every duplicate channel_ready the peer sends.
// Note that the happy path where the channel is actively being
// funded goes through the localDiscoverySignal branch above.
- if channel.RemoteNextRevocation != nil {
+ if channel.RemoteNextRevocation.IsSome() {
// Even though we're ignoring the rest of the message, we
// still need to refresh the peer's alias if they negotiated
// the option_scid_alias feature and sent a (possibly updated)
@@ -4289,7 +4289,7 @@ func (f *Manager) processChannelReady(peer lnpeer.Peer,
}
}
- // If the RemoteNextRevocation is non-nil, it means that we have
+ // If the RemoteNextRevocation is set, it means that we have
// already processed channelReady for this channel, so ignore. This
// check is after the alias logic so we store the peer's most recent
// alias. The spec requires us to validate that subsequent
@@ -4298,7 +4298,7 @@ func (f *Manager) processChannelReady(peer lnpeer.Peer,
// ignoring it. We are, however, required to *send* the same per
// commitment point, since another pedantic implementation might
// verify it.
- if channel.RemoteNextRevocation != nil {
+ if channel.RemoteNextRevocation.IsSome() {
log.Infof("Received duplicate channelReady for "+
"ChannelID(%v), ignoring.", chanID)
return
@@ -4365,7 +4365,7 @@ func (f *Manager) processChannelReady(peer lnpeer.Peer,
// need to create the next commitment state for the remote party. So
// we'll insert that into the channel now before passing it along to
// other sub-systems.
- err = channel.InsertNextRevocation(msg.NextPerCommitmentPoint)
+ err = channel.InsertNextRevocation(*msg.NextPerCommitmentPoint)
if err != nil {
log.Errorf("unable to insert next commitment point: %v", err)
return
### htlcswitch/link.go
@@ -734,7 +734,7 @@ func (l *channelLink) eligibleToForward() bool {
//
// NOTE: MUST be called from the main event loop.
func (l *channelLink) eligibleToUpdate() bool {
- return l.channel.RemoteNextRevocation() != nil &&
+ return l.channel.RemoteNextRevocation().IsSome() &&
l.channel.ShortChanID() != hop.Source &&
l.isReestablished() &&
l.quiescer.CanSendUpdates()
### htlcswitch/link_test.go
@@ -5817,6 +5817,10 @@ func TestChannelLinkFail(t *testing.T) {
// consider the failure permanent in response to the actions
// performed during the linkTest.
permanentFailure bool
+
+ // assertFailure performs case-specific checks on a
+ // received link failure.
+ assertFailure func(*testing.T, LinkFailureError)
}{
{
"don't fail the channel if we receive a warning " +
@@ -5834,6 +5838,7 @@ func TestChannelLinkFail(t *testing.T) {
false,
false,
false,
+ nil,
},
{
"don't force close if syncing states fails at startup",
@@ -5852,6 +5857,7 @@ func TestChannelLinkFail(t *testing.T) {
true,
false,
false,
+ nil,
},
{
"we don't force closes the channel if resolving " +
@@ -5872,6 +5878,7 @@ func TestChannelLinkFail(t *testing.T) {
true,
false,
false,
+ nil,
},
{
"don't force close the channel if we receive an " +
@@ -5892,15 +5899,18 @@ func TestChannelLinkFail(t *testing.T) {
true,
false,
false,
+ nil,
},
{
"force close the channel if we receive an invalid " +
"CommitSig, not containing enough HTLC sigs",
func(c *channelLink) {
},
- func(_ *testing.T, s *Switch, c *channelLink,
+ func(t *testing.T, s *Switch, c *channelLink,
remoteChannel *lnwallet.LightningChannel) {
+ t.Helper()
+
// Generate an HTLC and send to the link.
htlc1 := generateHtlc(t, c, 0)
ctx := linkTestContext{
@@ -5938,6 +5948,7 @@ func TestChannelLinkFail(t *testing.T) {
true,
true,
false,
+ nil,
},
{
"force close the channel if we receive an invalid " +
@@ -5994,6 +6005,55 @@ func TestChannelLinkFail(t *testing.T) {
true,
true,
false,
+ nil,
+ },
+ {
+ "fail the channel if a revocation is invalid for the " +
+ "current state",
+ func(c *channelLink) {
+ // Configure the channel so the
+ // revocation is invalid for its current state.
+ c.channel.State().RemoteNextRevocation =
+ fn.None[btcec.PublicKey]()
+ },
+ func(t *testing.T, _ *Switch, c *channelLink,
+ remoteChannel *lnwallet.LightningChannel) {
+
+ // Construct a well-formed revocation
+ // message that the current channel state must
+ // reject.
+ producer := remoteChannel.State().
+ RevocationProducer
+ secret, err := producer.AtIndex(0)
+ require.NoError(t, err)
+ nextSecret, err := producer.AtIndex(2)
+ require.NoError(t, err)
+
+ revoke := &lnwire.RevokeAndAck{
+ ChanID: c.ChanID(),
+ NextRevocationKey: input.
+ ComputeCommitmentPoint(
+ nextSecret[:],
+ ),
+ }
+ copy(revoke.Revocation[:], secret[:])
+
+ c.HandleChannelUpdate(revoke)
+ },
+ true,
+ false,
+ false,
+ func(t *testing.T, linkErr LinkFailureError) {
+ t.Helper()
+
+ require.Equal(
+ t, LinkFailureDisconnect,
+ linkErr.FailureAction,
+ )
+ require.Equal(
+ t, ErrInvalidRevocation, linkErr.code,
+ )
+ },
},
{
"consider the failure permanent if we receive a link " +
@@ -6011,73 +6071,86 @@ func TestChannelLinkFail(t *testing.T) {
// TODO(halseth) For compatibility with CL we currently
// don't treat Errors as permanent errors.
false,
+ nil,
},
}
const chanAmt = btcutil.SatoshiPerBitcoin * 5
// Execute each test case.
for _, test := range testCases {
- harness, err :=
- newSingleLinkTestHarness(t, chanAmt, 0)
- require.NoError(t, err, test.name)
+ t.Run(test.name, func(t *testing.T) {
+ harness, err :=
+ newSingleLinkTestHarness(t, chanAmt, 0)
+ require.NoError(t, err, test.name)
- //nolint:forcetypeassert
- coreLink := harness.aliceLink.(*channelLink)
+ //nolint:forcetypeassert
+ coreLink := harness.aliceLink.(*channelLink)
- // Set up a channel used to check whether the link error
- // force closed the channel.
- linkErrors := make(chan LinkFailureError, 1)
- coreLink.cfg.OnChannelFailure = func(_ lnwire.ChannelID,
- _ lnwire.ShortChannelID, linkErr LinkFailureError) {
+ // Set up a channel used to check whether the link
+ // error force closed the channel.
+ linkErrors := make(chan LinkFailureError, 1)
+ coreLink.cfg.OnChannelFailure = func(_ lnwire.ChannelID,
+ _ lnwire.ShortChannelID,
+ linkErr LinkFailureError) {
- linkErrors <- linkErr
- }
+ linkErrors <- linkErr
+ }
- // Set up the link before starting it.
- test.options(coreLink)
- err = harness.start()
- require.NoError(t, err, test.name)
+ // Set up the link before starting it.
+ test.options(coreLink)
+ err = harness.start()
+ require.NoError(t, err, test.name)
- // Execute the test case.
- test.linkTest(
- t, harness.aliceSwitch, coreLink, harness.bobChannel,
- )
+ // Execute the test case.
+ test.linkTest(
+ t, harness.aliceSwitch, coreLink,
+ harness.bobChannel,
+ )
- // Currently we expect all test cases to lead to link error.
- var linkErr LinkFailureError
- errReceived := false
- select {
- case linkErr = <-linkErrors:
- errReceived = true
+ // Wait to see whether the test case led to a link
+ // error.
+ var linkErr LinkFailureError
+ errReceived := false
+ select {
+ case linkErr = <-linkErrors:
+ errReceived = true
- case <-time.After(10 * time.Second):
- // If we do not receive a link error in 10s we assume
- // that we won't receive any.
- }
+ case <-time.After(10 * time.Second):
+ // If we do not receive a link error in 10s we
+ // assume that we won't receive any.
+ }
- require.Equal(t, test.shouldFail, errReceived, test.name)
+ require.Equal(
+ t, test.shouldFail, errReceived, test.name,
+ )
- // Check that the link is up and return.
- if !test.shouldFail {
- require.False(t, coreLink.failed)
- return
- }
+ // Check that the link is up and return.
+ if !test.shouldFail {
+ require.False(t, coreLink.failed)
+ return
+ }
- require.True(t, coreLink.failed)
+ require.True(t, coreLink.failed)
- // If we expect the link to force close the channel in this
- // case, check that it happens. If not, make sure it does not
- // happen.
- isForceCloseErr := (linkErr.FailureAction ==
- LinkFailureForceClose)
- require.True(
- t, test.shouldForceClose == isForceCloseErr, test.name,
- )
- require.Equal(
- t, test.permanentFailure, linkErr.PermanentFailure,
- test.name,
- )
+ // If we expect the link to force close the channel in
+ // this case, check that it happens. If not, make sure
+ // it does not happen.
+ isForceCloseErr := (linkErr.FailureAction ==
+ LinkFailureForceClose)
+ require.True(
+ t, test.shouldForceClose == isForceCloseErr,
+ test.name,
+ )
+ require.Equal(
+ t, test.permanentFailure,
+ linkErr.PermanentFailure, test.name,
+ )
+
+ if test.assertFailure != nil {
+ test.assertFailure(t, linkErr)
+ }
+ })
}
}
### htlcswitch/test_utils.go
@@ -385,15 +385,15 @@ func createTestChannel(t *testing.T, alicePrivKey, bobPrivKey []byte,
if err != nil {
return nil, nil, err
}
- if err := channelBob.InitNextRevocation(aliceNextRevoke); err != nil {
+ if err := channelBob.InitNextRevocation(*aliceNextRevoke); err != nil {
return nil, nil, err
}
bobNextRevoke, err := channelBob.NextRevocationKey()
if err != nil {
return nil, nil, err
}
- if err := channelAlice.InitNextRevocation(bobNextRevoke); err != nil {
+ if err := channelAlice.InitNextRevocation(*bobNextRevoke); err != nil {
return nil, nil, err
}
### lnwallet/channel.go
@@ -132,6 +132,16 @@ var (
ErrForceCloseLocalDataLoss = errors.New("cannot force close " +
"channel with local data loss")
+ // ErrUnexpectedRevocation is returned when a revocation cannot be
+ // applied in the current commitment state.
+ ErrUnexpectedRevocation = errors.New("received revocation in " +
+ "invalid commitment state")
+
+ // ErrNoNextRevocation is returned when an operation needs the remote
+ // party's next revocation point, but they haven't sent it to us yet.
+ ErrNoNextRevocation = errors.New("remote next revocation point not " +
+ "known")
+
// errNoNonce is returned when a nonce is required, but none is found.
errNoNonce = errors.New("no nonce found")
@@ -1554,10 +1564,14 @@ func (lc *LightningChannel) restoreCommitState(
// inserting it into the remote party's commitment chain. We
// don't pass our commit point as we don't have the
// corresponding state for the local commitment chain.
- pendingCommitPoint := lc.channelState.RemoteNextRevocation
+ pendingCommitPoint, err := lc.channelState.
+ RemoteNextRevocation.UnwrapOrErr(ErrNoNextRevocation)
+ if err != nil {
+ return err
+ }
pendingRemoteCommit, err = lc.diskCommitToMemCommit(
lntypes.Remote, &pendingRemoteCommitDiff.Commitment,
- nil, pendingCommitPoint,
+ nil, &pendingCommitPoint,
)
if err != nil {
return err
@@ -1570,7 +1584,7 @@ func (lc *LightningChannel) restoreCommitState(
// We'll also re-create the set of commitment keys needed to
// fully re-derive the state.
pendingRemoteKeyChain = DeriveCommitmentKeys(
- pendingCommitPoint, lntypes.Remote,
+ &pendingCommitPoint, lntypes.Remote,
lc.channelState.ChanType,
&lc.channelState.LocalChanCfg,
&lc.channelState.RemoteChanCfg,
@@ -4163,11 +4177,13 @@ func (lc *LightningChannel) SignNextCommitment(
// don't yet have the initial next revocation point of the remote
// party, then we're unable to create new states. Each time we create a
// new state, we consume a prior revocation point.
- commitPoint := lc.channelState.RemoteNextRevocation
unacked := lc.commitChains.Remote.hasUnackedCommitment()
- if unacked || commitPoint == nil {
- lc.log.Tracef("waiting for remote ack=%v, nil "+
- "RemoteNextRevocation: %v", unacked, commitPoint == nil)
+ commitPoint, err := lc.channelState.RemoteNextRevocation.UnwrapOrErr(
+ ErrNoNextRevocation,
+ )
+ if unacked || err != nil {
+ lc.log.Tracef("waiting for remote ack=%v, "+
+ "RemoteNextRevocation known: %v", unacked, err == nil)
return nil, ErrNoWindow
}
@@ -4182,7 +4198,7 @@ func (lc *LightningChannel) SignNextCommitment(
// We do not enforce the FeeBuffer here because when we reach this
// point all updates will have to get locked-in so we enforce the
// minimum requirement.
- err := lc.validateCommitmentSanity(
+ err = lc.validateCommitmentSanity(
remoteACKedIndex, lc.updateLogs.Local.logIndex, lntypes.Remote,
NoBuffer, nil, nil,
)
@@ -4194,7 +4210,7 @@ func (lc *LightningChannel) SignNextCommitment(
// used within fetchCommitmentView to derive all the keys necessary to
// construct the commitment state.
keyRing := DeriveCommitmentKeys(
- commitPoint, lntypes.Remote, lc.channelState.ChanType,
+ &commitPoint, lntypes.Remote, lc.channelState.ChanType,
&lc.channelState.LocalChanCfg, &lc.channelState.RemoteChanCfg,
)
@@ -4790,13 +4806,13 @@ func (lc *LightningChannel) ProcessChanSyncMsg(ctx context.Context,
// in sync, or that we are in a state we can recover from. As a final
// check, we ensure that the commitment point sent to us by the remote
// is valid.
- var commitPoint *btcec.PublicKey
+ var commitPoint fn.Option[btcec.PublicKey]
switch {
// If their height is one beyond what we know their current height to
// be, then we need to compare their current unrevoked commitment point
// as that's what they should send.
case msg.NextLocalCommitHeight == remoteTailHeight+1:
- commitPoint = lc.channelState.RemoteCurrentRevocation
+ commitPoint = fn.Some(*lc.channelState.RemoteCurrentRevocation)
// Alternatively, if their height is two beyond what we know their best
// height to be, then they're holding onto two commitments, and the
@@ -4810,9 +4826,12 @@ func (lc *LightningChannel) ProcessChanSyncMsg(ctx context.Context,
// Only if this is a tweakless channel will we attempt to verify the
// commitment point, as otherwise it has no validity requirements.
tweakless := lc.channelState.ChanType.IsTweakless()
- if !tweakless && commitPoint != nil &&
- !commitPoint.IsEqual(msg.LocalUnrevokedCommitPoint) {
-
+ pointMismatch := fn.MapOptionZ(
+ commitPoint, func(point btcec.PublicKey) bool {
+ return !point.IsEqual(msg.LocalUnrevokedCommitPoint)
+ },
+ )
+ if !tweakless && pointMismatch {
lc.log.Errorf("sync failed: remote sent invalid commit point "+
"for height %v!",
msg.NextLocalCommitHeight)
@@ -5919,10 +5938,8 @@ func extractRevokeAndAckNonce(revMsg *lnwire.RevokeAndAck,
}
// ReceiveRevocation processes a revocation sent by the remote party for the
-// lowest unrevoked commitment within their commitment chain. We receive a
-// revocation either during the initial session negotiation wherein revocation
-// windows are extended, or in response to a state update that we initiate. If
-// successful, then the remote commitment chain is advanced by a single
+// lowest unrevoked commitment within their commitment chain. If validation
+// succeeds, then the remote commitment chain is advanced by a single
// commitment, and a log compaction is attempted.
//
// The returned values correspond to:
@@ -5936,32 +5953,50 @@ func (lc *LightningChannel) ReceiveRevocation(revMsg *lnwire.RevokeAndAck) (
lc.Lock()
defer lc.Unlock()
- // Ensure that the new pre-image can be placed in preimage store.
- store := lc.channelState.RevocationStore
- revocation, err := chainhash.NewHash(revMsg.Revocation[:])
- if err != nil {
- return nil, nil, err
+ // Ensure the remote commitment chain can advance before updating any
+ // revocation state.
+ if !lc.commitChains.Remote.hasUnackedCommitment() {
+ return nil, nil, ErrUnexpectedRevocation
}
- if err := store.AddNextEntry(revocation); err != nil {
+
+ // The next revocation point is required to advance
+ // the remote commitment chain.
+ nextRevocation, err := lc.channelState.RemoteNextRevocation.
+ UnwrapOrErr(ErrNoNextRevocation)
+ if err != nil {
return nil, nil, err
}
// Verify that if we use the commitment point computed based off of the
// revealed secret to derive a revocation key with our revocation base
// point, then it matches the current revocation of the remote party.
+ // We check this before adding the secret to the store, so a revocation
+ // for the wrong point leaves our state untouched.
currentCommitPoint := lc.channelState.RemoteCurrentRevocation
derivedCommitPoint := input.ComputeCommitmentPoint(revMsg.Revocation[:])
if !derivedCommitPoint.IsEqual(currentCommitPoint) {
return nil, nil, fmt.Errorf("revocation key mismatch")
}
+ // Ensure that the new pre-image can be placed in preimage store.
+ store := lc.channelState.RevocationStore
+ revocation, err := chainhash.NewHash(revMsg.Revocation[:])
+ if err != nil {
+ return nil, nil, err
+ }
+ if err := store.AddNextEntry(revocation); err != nil {
+ return nil, nil, err
+ }
+
// Now that we've verified that the prior commitment has been properly
// revoked, we'll advance the revocation state we track for the remote
// party: the new current revocation is what was previously the next
// revocation, and the new next revocation is set to the key included
// in the message.
- lc.channelState.RemoteCurrentRevocation = lc.channelState.RemoteNextRevocation
- lc.channelState.RemoteNextRevocation = revMsg.NextRevocationKey
+ lc.channelState.RemoteCurrentRevocation = &nextRevocation
+ lc.channelState.RemoteNextRevocation = fn.Some(
+ *revMsg.NextRevocationKey,
+ )
lc.log.Tracef("remote party accepted state transition, revoked height "+
"%v, now at %v",
@@ -6207,7 +6242,7 @@ func (lc *LightningChannel) NextRevocationKey() (*btcec.PublicKey, error) {
// revocation to be used when creating a new commitment state for the remote
// party. This function MUST be called before the channel can accept or propose
// any new states.
-func (lc *LightningChannel) InitNextRevocation(revKey *btcec.PublicKey) error {
+func (lc *LightningChannel) InitNextRevocation(revKey btcec.PublicKey) error {
lc.Lock()
defer lc.Unlock()
@@ -9067,8 +9102,13 @@ func (lc *LightningChannel) NewAnchorResolutions() (*AnchorResolutions,
}
if remotePendingCommit != nil {
+ pendingCommitPoint, err := lc.channelState.
+ RemoteNextRevocation.UnwrapOrErr(ErrNoNextRevocation)
+ if err != nil {
+ return nil, err
+ }
pendingRemoteKeyRing := DeriveCommitmentKeys(
- lc.channelState.RemoteNextRevocation, lntypes.Remote,
+ &pendingCommitPoint, lntypes.Remote,
lc.channelState.ChanType, &lc.channelState.LocalChanCfg,
&lc.channelState.RemoteChanCfg,
)
@@ -10067,20 +10107,16 @@ func (lc *LightningChannel) IdealCommitFeeRate(netFeeRate, minRelayFeeRate,
}
// RemoteNextRevocation returns the channelState's RemoteNextRevocation. For
-// musig2 channels, until a nonce pair is processed by the remote party, a nil
-// public key is returned.
+// musig2 channels, until a nonce pair is processed by the remote party, None
+// is returned.
//
// TODO(roasbeef): revisit, maybe just make a more general method instead?
-func (lc *LightningChannel) RemoteNextRevocation() *btcec.PublicKey {
+func (lc *LightningChannel) RemoteNextRevocation() fn.Option[btcec.PublicKey] {
lc.RLock()
defer lc.RUnlock()
- if !lc.channelState.ChanType.IsTaproot() {
- return lc.channelState.RemoteNextRevocation
- }
-
- if lc.musigSessions == nil {
- return nil
+ if lc.channelState.ChanType.IsTaproot() && lc.musigSessions == nil {
+ return fn.None[btcec.PublicKey]()
}
return lc.channelState.RemoteNextRevocation
### lnwallet/channel_test.go
@@ -6096,7 +6096,8 @@ func TestSignCommitmentFailNotLockedIn(t *testing.T) {
// Next, we'll modify Alice's internal state to omit knowledge of Bob's
// next revocation point.
- aliceChannel.channelState.RemoteNextRevocation = nil
+ aliceState := aliceChannel.channelState
+ aliceState.RemoteNextRevocation = fn.None[btcec.PublicKey]()
// If we now try to initiate a state update, then it should fail as
// Alice is unable to actually create a new state.
@@ -6106,6 +6107,183 @@ func TestSignCommitmentFailNotLockedIn(t *testing.T) {
}
}
+// TestReceiveRevocationInvalidState tests that rejected revocations leave the
+// channel state unchanged and don't prevent a later valid transition.
+func TestReceiveRevocationInvalidState(t *testing.T) {
+ t.Parallel()
+
+ noNextPoint := fn.None[btcec.PublicKey]()
+
+ testCases := []struct {
+ name string
+ chanType channeldb.ChannelType
+
+ // dropNextPoint clears Alice's copy of Bob's next revocation
+ // point.
+ dropNextPoint bool
+ }{
+ {
+ name: "tweakless",
+ chanType: channeldb.SingleFunderTweaklessBit,
+ },
+ {
+ name: "tweakless no next point",
+ chanType: channeldb.SingleFunderTweaklessBit,
+ dropNextPoint: true,
+ },
+ {
+ name: "taproot",
+ chanType: channeldb.SimpleTaprootFeatureBit |
+ channeldb.SingleFunderTweaklessBit |
+ channeldb.AnchorOutputsBit,
+ },
+ {
+ name: "taproot no next point",
+ chanType: channeldb.SimpleTaprootFeatureBit |
+ channeldb.SingleFunderTweaklessBit |
+ channeldb.AnchorOutputsBit,
+ dropNextPoint: true,
+ },
+ }
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ aliceChannel, bobChannel, err := CreateTestChannels(
+ t, tc.chanType,
+ )
+ require.NoError(t, err)
+
+ aliceState := aliceChannel.channelState
+ if tc.dropNextPoint {
+ aliceState.RemoteNextRevocation = noNextPoint
+ }
+
+ // Generate a revocation message for the
+ // current commitment state.
+ bobHeight := bobChannel.commitChains.Local.tail().height
+ revMsg, err := bobChannel.generateRevocation(bobHeight)
+ require.NoError(t, err)
+
+ curPoint := aliceState.RemoteCurrentRevocation
+ nextPoint := aliceState.RemoteNextRevocation
+
+ _, _, err = aliceChannel.ReceiveRevocation(revMsg)
+ require.ErrorIs(t, err, ErrUnexpectedRevocation)
+
+ // The rejected transition must leave the
+ // revocation state unchanged.
+ require.Equal(
+ t, curPoint, aliceState.RemoteCurrentRevocation,
+ )
+ require.Equal(
+ t, nextPoint, aliceState.RemoteNextRevocation,
+ )
+ _, err = aliceState.RevocationStore.LookUp(bobHeight)
+ require.Error(t, err)
+
+ if tc.dropNextPoint {
+ return
+ }
+
+ // A normal state transition should still
+ // succeed afterwards.
+ require.NoError(
+ t, ForceStateTransition(
+ aliceChannel, bobChannel,
+ ),
+ )
+ _, err = aliceState.RevocationStore.LookUp(bobHeight)
+ require.NoError(t, err)
+ })
+ }
+}
+
+// TestReceiveRevocationWrongSecret tests that a revocation for the wrong
+// commitment point is rejected before the remote party's revocation state is
+// modified, and that the correct revocation can still be processed afterwards.
+func TestReceiveRevocationWrongSecret(t *testing.T) {
+ t.Parallel()
+
+ testCases := []struct {
+ name string
+ chanType channeldb.ChannelType
+ }{
+ {
+ name: "tweakless",
+ chanType: channeldb.SingleFunderTweaklessBit,
+ },
+ {
+ name: "taproot",
+ chanType: channeldb.SimpleTaprootFeatureBit |
+ channeldb.SingleFunderTweaklessBit |
+ channeldb.AnchorOutputsBit,
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ aliceChannel, bobChannel, err := CreateTestChannels(
+ t, tc.chanType,
+ )
+ require.NoError(t, err)
+
+ // Give Alice an outstanding commitment for Bob so the
+ // revocation reaches the secret validation.
+ commitSigs, err := aliceChannel.SignNextCommitment(ctxb)
+ require.NoError(t, err)
+ err = bobChannel.ReceiveNewCommitment(
+ commitSigs.CommitSigs,
+ )
+ require.NoError(t, err)
+
+ bobHeight := bobChannel.commitChains.Local.tail().height
+ bobRevocation, _, _, err := bobChannel.
+ RevokeCurrentCommitment()
+ require.NoError(t, err)
+
+ aliceState := aliceChannel.channelState
+ currentPoint := aliceState.RemoteCurrentRevocation
+ nextPoint := aliceState.RemoteNextRevocation
+
+ // Corrupt the revealed secret so it no longer
+ // derives the remote party's current revocation
+ // point.
+ wrongRevocation := *bobRevocation
+ wrongRevocation.Revocation[0] ^= 1
+
+ _, _, err = aliceChannel.ReceiveRevocation(
+ &wrongRevocation,
+ )
+ require.EqualError(t, err, "revocation key mismatch")
+
+ // The rejected revocation must not advance
+ // either point or enter the bad secret in the
+ // revocation store.
+ require.Equal(
+ t, currentPoint,
+ aliceState.RemoteCurrentRevocation,
+ )
+ require.Equal(
+ t, nextPoint, aliceState.RemoteNextRevocation,
+ )
+ _, err = aliceState.RevocationStore.LookUp(bobHeight)
+ require.Error(t, err)
+
+ // The real revocation should still be accepted
+ // afterwards.
+ _, _, err = aliceChannel.ReceiveRevocation(
+ bobRevocation,
+ )
+ require.NoError(t, err)
+ _, err = aliceState.RevocationStore.LookUp(bobHeight)
+ require.NoError(t, err)
+ })
+ }
+}
+
// TestLockedInHtlcForwardingSkipAfterRestart ensures that after a restart, a
// state machine doesn't attempt to re-forward any HTLC's that were already
// locked in, but in a prior state.
@@ -6714,11 +6892,13 @@ func TestChannelUnilateralClosePendingCommit(t *testing.T) {
// properly populated.
aliceRemoteChainTip, err := aliceChannel.channelState.RemoteCommitChainTip()
require.NoError(t, err, "unable to fetch remote chain tip")
+ bobNextPoint := aliceChannel.channelState.RemoteNextRevocation.
+ UnwrapOrFail(t)
aliceCloseSummary, err := NewUnilateralCloseSummary(
aliceChannel.channelState, aliceChannel.Signer,
spendDetail,
aliceRemoteChainTip.Commitment,
- aliceChannel.channelState.RemoteNextRevocation,
+ &bobNextPoint,
fn.Some[AuxLeafStore](&MockAuxLeafStore{}),
fn.Some[AuxContractResolver](&MockAuxContractResolver{}),
)
### lnwallet/test_utils.go
@@ -474,15 +474,15 @@ func initRevocationWindows(chanA, chanB *LightningChannel) error {
if err != nil {
return err
}
- if err := chanB.InitNextRevocation(aliceNextRevoke); err != nil {
+ if err := chanB.InitNextRevocation(*aliceNextRevoke); err != nil {
return err
}
bobNextRevoke, err := chanB.NextRevocationKey()
if err != nil {
return err
}
- if err := chanA.InitNextRevocation(bobNextRevoke); err != nil {
+ if err := chanA.InitNextRevocation(*bobNextRevoke); err != nil {
return err
}
### peer/brontide.go
@@ -3272,7 +3272,7 @@ func (p *Brontide) ChannelSnapshots() []*channeldb.ChannelSnapshot {
// We'll only return a snapshot for channels that are
// *immediately* available for routing payments over.
- if activeChan.RemoteNextRevocation() == nil {
+ if activeChan.RemoteNextRevocation().IsNone() {
return nil
}
@@ -5731,16 +5731,22 @@ func (p *Brontide) updateNextRevocation(c *chanstate.OpenChannel) error {
// If we're being sent a new channel, and our existing channel doesn't
// have the next revocation, then we need to update the current
// existing channel.
- if currentChan.RemoteNextRevocation() != nil {
+ if currentChan.RemoteNextRevocation().IsSome() {
return nil
}
p.log.Infof("Processing retransmitted ChannelReady for "+
"ChannelPoint(%v)", chanPoint)
- nextRevoke := c.RemoteNextRevocation
+ nextRevoke, err := c.RemoteNextRevocation.UnwrapOrErr(
+ lnwallet.ErrNoNextRevocation,
+ )
+ if err != nil {
+ return fmt.Errorf("retransmitted channel has no next "+
+ "revocation: %w", err)
+ }
- err := currentChan.InitNextRevocation(nextRevoke)
+ err = currentChan.InitNextRevocation(nextRevoke)
if err != nil {
return fmt.Errorf("unable to init next revocation: %w", err)
}
### peer/brontide_test.go
@@ -2380,12 +2380,28 @@ func TestUpdateNextRevocation(t *testing.T) {
// testChannel is used to test the updateNextRevocation function.
testChannel := bobChan.State()
+ chanID := lnwire.NewChanIDFromOutPoint(testChannel.FundingOutpoint)
+
+ // The test channels start out without a next revocation point, so
+ // there's nothing to insert yet.
+ err = alicePeer.updateNextRevocation(testChannel)
+ require.ErrorIs(err, lnwallet.ErrNoNextRevocation)
+
+ // Once the channel carries the point, updating a known channel should
+ // give us no error, and insert the point into our copy of it.
+ nextPriv, err := btcec.NewPrivateKey()
+ require.NoError(err)
+ testChannel.RemoteNextRevocation = fn.Some(*nextPriv.PubKey())
- // Update the next revocation for a known channel should give us no
- // error.
err = alicePeer.updateNextRevocation(testChannel)
require.NoError(err, "expected no error")
+ aliceChan, ok := alicePeer.activeChannels.Load(chanID)
+ require.True(ok)
+ require.Equal(
+ fn.Some(*nextPriv.PubKey()), aliceChan.RemoteNextRevocation(),
+ )
+
// Test an error is returned when the chanID cannot be found in
// `activeChannels` map.
testChannel.FundingOutpoint = wire.OutPoint{Index: 0}
@@ -2395,7 +2411,7 @@ func TestUpdateNextRevocation(t *testing.T) {
// Test an error is returned when the chanID's corresponding channel is
// nil.
testChannel.FundingOutpoint = wire.OutPoint{Index: 1}
- chanID := lnwire.NewChanIDFromOutPoint(testChannel.FundingOutpoint)
+ chanID = lnwire.NewChanIDFromOutPoint(testChannel.FundingOutpoint)
alicePeer.activeChannels.Store(chanID, nil)
err = alicePeer.updateNextRevocation(testChannel)Why this scored 61/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.