multi: make RemoteNextRevocation an fn.Option
What changed, and why it matters
This commit is a defensive code-quality change in LND that makes the 'remote next revocation point' an explicit optional value instead of a bare pointer that could be nil. It forces every piece of code that needs the point to check whether it is actually present before using it, and returns a clear error (ErrNoNextRevocation) when it is missing. The on-disk database format is unchanged, and new tests are added for channels and close summaries that lack the point. The change reduces the risk of accidental nil-pointer use or logic bugs around channels that have not yet received channel_ready, but it is not a fix for a known active exploit.
Review as normal defensive hardening. No urgent patch or incident response is indicated by the commit itself. Operators and downstream integrators should ensure they are on a version that includes this refactor if they want the additional safety around pre-channel_ready state handling. Monitor release notes for any related follow-up fixes.
Security signals we found
Refactor from nullable pointer to explicit Option type to prevent accidental use of absent revocation point
New sentinel error ErrNoNextRevocation returned when the point is required but missing
Multiple call sites now require explicit unwrapping before using the revocation point
On-disk serialization format kept backward-compatible
New and updated tests cover absent next revocation point paths
Evidence from the diff
The commit refactors OpenChannel.RemoteNextRevocation, ChannelCloseSummary.RemoteNextRevocation, and LightningChannel.RemoteNextRevocation from *btcec.PublicKey to fn.Option[btcec.PublicKey]. It also changes InsertNextRevocation and InitNextRevocation to take the key by value. Call sites in channeldb, chanstate, contractcourt, funding, htlcswitch, lnwallet, and peer now unwrap the option explicitly, returning ErrNoNextRevocation when absent. Serialization/deserialization preserves the existing on-disk format (presence flag for close summaries, omitted field for revocation state). Tests are updated and added to verify round-tripping of channels and close summaries with no next revocation point, and to assert that retransmitted channel_ready messages without a point are rejected.
Changed components
channeldbchanstatecontractcourt/chain_watcher.gofunding/manager.gohtlcswitch/link.golnwallet/channel.gopeer/brontide.goInspect captured patch +250 / −89
### 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 "+
### 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/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
@@ -137,6 +137,11 @@ var (
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")
@@ -1559,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
@@ -1575,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,
@@ -4168,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
}
@@ -4187,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,
)
@@ -4199,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,
)
@@ -4795,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
@@ -4815,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)
@@ -5945,6 +5959,14 @@ func (lc *LightningChannel) ReceiveRevocation(revMsg *lnwire.RevokeAndAck) (
return nil, nil, ErrUnexpectedRevocation
}
+ // 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.
@@ -5971,8 +5993,10 @@ func (lc *LightningChannel) ReceiveRevocation(revMsg *lnwire.RevokeAndAck) (
// 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",
@@ -6218,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()
@@ -9078,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,
)
@@ -10078,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.
@@ -6111,6 +6112,8 @@ func TestSignCommitmentFailNotLockedIn(t *testing.T) {
func TestReceiveRevocationInvalidState(t *testing.T) {
t.Parallel()
+ noNextPoint := fn.None[btcec.PublicKey]()
+
testCases := []struct {
name string
chanType channeldb.ChannelType
@@ -6153,7 +6156,7 @@ func TestReceiveRevocationInvalidState(t *testing.T) {
aliceState := aliceChannel.channelState
if tc.dropNextPoint {
- aliceState.RemoteNextRevocation = nil
+ aliceState.RemoteNextRevocation = noNextPoint
}
// Generate a revocation message for the
@@ -6889,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 32/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.