Update server callback wiring to use chanstate.OpenChannel at the
funding manager boundary.
This follows the funding package change and removes another
consumer-facing dependency on the channeldb OpenChannel alias.
Release the preimage beacon lock before invoking the on-chain
interceptor. The interceptor path can block on the htlcswitch event
loop, while resolution of another held on-chain HTLC can call back
into the beacon to add a preimage.
If interceptor delivery fails after the subscriber was registered,
cancel the subscription before returning the error.
On-chain held entries are replay handles for the interceptor while
contractcourt waits for a preimage or on-chain expiry. Once the resolver
tears down, keeping the handle until the refund timeout can replay a stale
HTLC to a reconnecting interceptor.
Thread a dedicated cleanup signal from the witness subscription cancel path
back through the interceptable switch event loop. The held set only removes
on-chain entries for that signal, leaving off-chain entries under the link
flow lifecycle.
Mirror the link's final-hop HTLC checks in the incoming contest resolver so
the off-chain link path and on-chain resolver use the same final-hop handling.
Use MaxFinalCltvDelta directly in contractcourt to match invoice creation and
link processing.
Preserve the link's custom HTLC behavior by leaving amount checks to auxiliary
traffic shapers when custom HTLC handling applies.
Migrate all btcd dependencies to the new per-package v2 modules (wire/v2,
txscript/v2, chaincfg/v2, chainhash/v2, btcutil/v2, psbt/v2, btcec/v2)
introduced by btcd v0.26.0, and pin the tagged ecosystem versions:
btcwallet v0.17.0, neutrino v0.18.0 and lightning-onion v1.4.0.
The bulk of the import rewrite was produced by the scripted diff from
https://github.com/btcsuite/btcd/pull/2547 (followed by 'make rpc'). The
address symbols that moved out of btcutil into the new address package
are imported as btcaddr where a local "address" variable would otherwise
shadow them. The go.mod/go.sum updates and the remaining manual
compilation fixes are folded into this single commit so it builds on its
own (the migration was previously split into a reproducible scripted-diff
plus follow-ups, intended to be squashed on merge).
Channels are loaded into the channel fitness store on startup regardless
of whether their peer is connected. When a peer monitor was first
created we unconditionally recorded an online event, which caused
offline peers to report 100% uptime in ListChannels.
Seed the initial event with the peer's actual connection state via a new
IsPeerOnline config callback so that uptime reflects real connectivity.
Tor stopped serving v2 onion services in October 2021; lnd should not
produce v2 addresses anymore, but it must still verify signatures on
and re-broadcast peer NodeAnnouncement messages that carry v2 entries.
Stop accepting v2 as configuration input (lncfg), strip the legacy
`--tor.v2` flag from the sample config, and remove the
`tor.OnionHostToFakeIP` helper. Operator entry points (`--externalip`,
`--listen`, `lncli connect`, `lncli wtclient towers add`) fail fast on
a v2 `.onion` string, so upgrading nodes must remove any v2 entry from
`lnd.conf` before lnd will start.
Filter persisted v2 state before use without rewriting on-disk records:
the self-announcement builder strips any v2 entry inherited from the
stored self-node; the watchtower client drops v2 entries from each
persisted tower's address list (skipping the tower entirely if no
non-v2 address remains); the autopilot connector, graph bootstrapper,
and static-channel backup restore paths skip v2 entries before
attempting outbound dials. Restrict the Tor controller's ADD_ONION
path to v3 keys, including the encrypted on-disk legacy-key fallback.
For inbound announcements, keep the wire codec wire-faithful:
`lnwire.WriteOnionAddr`, `graph/db.encodeOnionAddr`, and the matching
decoders round-trip v2 bytes so `DataToSign` reproduces the bytes the
remote peer signed, signature validation succeeds, and the announcement
is persisted to the graph DB and re-broadcast across restarts byte-for-
byte. RPC surfaces continue to expose the full address set so external
tools can independently reproduce and verify the signed bytes.
Add a netann regression test that signs a [v3, v2, ipv4] announcement,
round-trips it through Encode/Decode, verifies the signature, and
confirms the resulting models.Node preserves the v2 entry. Add a
graph bootstrapper test asserting v2 entries are skipped while v3 and
plain TCP entries on the same node still surface as bootstrap
candidates.
PR #10331 introduced a multi-confirmation reorg-aware dispatch in the
chain watcher. In production builds CloseConfsForCapacity is at least
3, so the chain watcher waits for three confirmations of a close tx
before running dispatchCooperativeClose, MarkChannelClosed, and
NotifyClosedChannel. Subscribers of the SubscribeChannelEvents stream
that used to receive a CLOSED_CHANNEL event after a single
confirmation in v0.20.1 stopped seeing the event entirely on shorter
test cycles and were delayed by two extra blocks on longer ones. This
is the regression alexbosworth reported on zero-conf channels.
The intent behind the original change was to wait three confirmations
under the hood for reorg safety while still dispatching a
CLOSED_CHANNEL event to RPC subscribers immediately, matching the
v0.20.1 surface. That insta-dispatch was wired into
peer.WaitForChanToClose for the local CloseChannel response stream
but was never extended to the channel-notifier path that drives
SubscribeChannelEvents.
In this commit, we wire a new optional notifyEarlyCoopClose callback
into the chain watcher's processDetectedSpend. The first time a coop
close spend is detected on chain, the chain watcher synthesizes a
ChannelCloseSummary with IsPending=true and dispatches a
CLOSED_CHANNEL event over the channel notifier, no DB round-trip
required. The callback is plumbed through ChainArbitratorConfig
.NotifyEarlyClosedChannel to the new
ChannelNotifier.NotifyEarlyClosedChannelEvent. The summary builder
shared with dispatchCooperativeClose is extracted into
buildCoopCloseSummary so the early and post-N-conf paths produce
equivalent payloads.
A coopCloseEarlyDispatched flag on the chain watcher keeps the
dispatch idempotent across blockbeat replays of the same spend, and
the closeObserver clears it on negativeConfChan so a re-mined or
replacement close after a deep reorg re-fires the preliminary event
with its own summary. The early-dispatch call sits before the
fast-path check so numConfs==1 also fires the early event through the
same code path.
Suppressing the duplicate notify at MarkChannelClosed time happens
inline in the chain_arbitrator MarkChannelClosed callback: after
CloseChannel succeeds, NotifyClosedChannel is fired only when the
close type is not CooperativeClose. Force, breach, and abandon paths
intentionally remain on the existing N-confirmation dispatch contract.
Store channel-state access on server as chanstate.Store instead of
*channeldb.ChannelStateDB. Keep link-node access as a separate concrete
*channeldb.LinkNodeDB field so LinkNodeDB does not leak into the
channel-state store contract.
All four call sites pass nil for tx today (server.go, two in
channeldb/db_test.go, funding/manager_test.go). The internal
channelScanner(nil, selector) call inside FetchChannelByID is preserved
verbatim, so runtime behavior is unchanged.
This is a prerequisite for the upcoming chanstate.ChannelStore
interface: keeping the parameter would leak kvdb into a domain
interface.
In this commit, we now register the rbfCloseActor when we create the rbf
chan closer state machine. Now the RPC server no longer neesd to
traverse a series of maps and pointers (rpcServer -> server -> peer ->
activeCloseMap -> rbf chan closer) to trigger a new fee bump.
Instead, it just creates the service key that it knows that the closer
can be reached at, and sends a message to it using the returned
actorRef/router. We also hide additional details re the various methods
in play, as we only care about the type of message we expect to send and
receive.
An earlier commit added an auto-enable that forces RbfCoopClose=true
whenever either taproot channel flag is set. This breaks
taproot-overlay channels, because the RBF coop close state machine in
lnwallet/chancloser/rbf_coop_*.go does not integrate the AuxCloser
(or any other aux) hook that overlay channels depend on to build
aux-aware close transactions. A node that enables
--protocol.simple-taproot-overlay-chans ends up with RBF force-on and
its overlay channel closes silently fail, leaving the aux closer
unable to finalize on-chain.
Narrow the auto-enable so it only fires for TaprootChans (staging /
final taproot) and explicitly skips it when TaprootOverlayChans is set.
Operators that positively want RBF can still opt in via
--protocol.rbf-coop-close; this change only removes the forced path
that silently breaks overlay closes.
Add a new protocol option, protocol.onion-msg-relay-all, that controls
whether incoming onion messages are required to come from peers with a
fully open channel. The default is false, which preserves the existing
behavior: the channel-presence gate drops messages from peers with no
channel before the rate limiters are consulted, so a new no-cost
identity cannot burn any per-peer byte budget and saturate the global
bucket. Setting the flag to true skips the gate so that onion messages
from any peer are admitted into the per-peer + global IngressLimiter
pipeline.
The flag is plumbed through ProtocolOptions in both the default and
integration build variants of lncfg/protocol*.go, threaded into the
peer subsystem as peer.Config.OnionRelayAll, and wired by the server
from s.cfg.ProtocolOptions.OnionMsgRelayAll alongside the existing
OnionLimiter field. allowOnionMessage gains a relayAll bool parameter;
the gate check becomes "if \!relayAll && \!hasChannel { drop }" so the
semantics of hasChannel stay pure — it still means "this peer has a
channel" — and the policy toggle lives entirely in the caller's
configuration rather than being spread across gate-state and flag
state.
sample-lnd.conf gains a commented-out entry for the new option with
the default value and an operator-facing note that enabling it trades
the Sybil-resistance property of the gate for reachability to peers
with whom we have no channel.
A new TestAllowOnionMessageRelayAll unit test exercises the four
(hasChannel, relayAll) combinations at the helper level, including
the key new behavior — a peer with hasChannel=false being rejected
under relayAll=false and admitted into the limiter under
relayAll=true — and the nil-limiter path under relayAll=true, which
must still accept. The existing allowOnionMessage tests were
extended with the new parameter set to false so they continue to
assert the gate semantics unchanged.
With the limiter primitives, config options, and peer-side enforcement
in place, this commit constructs the per-peer and global onion message
rate limiters inside the server's onion messaging setup block,
composes them with NewIngressLimiter, and threads the resulting
IngressLimiter into peer.Config alongside the existing SpawnOnionActor
factory as a single OnionLimiter field. The limiters are only built
when onion messaging is actually enabled so that the disabled path
allocates nothing.
sample-lnd.conf gains commented-out entries for the four new options
with the default values and a short explanation of the ~5 Mbps
worst-case target. The user-facing release note for this feature is
added in a single consolidated commit at the end of the series rather
than split across the commits that introduce it.
Wire channel type through BreachRetribution and the watchtower blob
system to support production taproot channels with final scripts.
The key changes are:
1. Add ChanType field to BreachRetribution so downstream consumers
(including the watchtower) can determine the script variant.
2. Add FlagTaprootFinalChannel blob type flag and
TypeAltruistTaprootFinalCommit blob type to distinguish production
from staging taproot channels in watchtower backups.
3. Add TaprootFinalCommitment to the watchtower's CommitmentType enum
with appropriate witness type and size mappings.
4. Update taprootJusticeKit to use WithProdScripts() when constructing
script trees for production taproot channels. The isFinal flag is
set during construction from BreachRetribution.ChanType and during
deserialization from the blob's commitment type.
Without this change, the watchtower would construct justice transactions
using staging scripts for production taproot channels, resulting in
invalid witnesses that fail to sweep breached outputs.
This commit completes the production taproot integration by updating the
UTXO nursery to properly handle production taproot channels. The nursery
is responsible for incubating time-locked outputs from commitment transactions
and must use the correct witness types for successful sweeping operations.
The witness type selection logic has been updated in three key areas within
the IncubateOutputs function: incoming HTLC resolution handling, outgoing
HTLC resolution handling, and baby output creation through makeBabyOutput.
Each location now uses a consistent three-way selection pattern that chooses
production taproot witness types for final channels, staging types for
development channels, and legacy types for traditional channels.
A new helper method isProdTaprootResolution has been added to determine
production taproot channels by examining the presence of a ResolutionBlob,
which indicates auxiliary channel information used by production taproot
implementations. The makeBabyOutput function has been converted to a method
to access this helper function.
The NurseryReport function has been updated to include all new Final witness
types in its switch statements, ensuring that production taproot outputs are
properly categorized and reported. This maintains consistency in the nursery's
reporting system while supporting the new witness types.
In this commit, we eliminate the three buffered chan error patterns in
the discovery package and replace them with actor.Promise[error]/
actor.Future[error]. The old pattern is error-prone: if a channel is
completed more than once (e.g. when a deferred message copy is
re-enqueued and processed again), the second write to a capacity-1
channel blocks forever. actor.Promise.Complete() is idempotent via
sync.Once, so the second call is always a safe no-op regardless of
whether anyone holds a reference to the Future.
Additionally, PropagateChanPolicyUpdate previously blocked on <-errChan
after enqueuing a policy update with no quit-channel check, creating a
latent deadlock if the gossiper shut down between enqueue and send. It
now uses AwaitGossipResult with a ContextFromQuit-derived context, so
shutdown is always respected.
This is an atomic migration that updates all callers in the same
commit so each commit builds standalone. The three main pieces are:
discovery
networkMsg.err chan error becomes errPromise actor.Promise[error].
chanPolicyUpdateRequest.errChan chan error becomes errPromise.
syncTransitionReq.errChan chan error becomes errPromise. All ~65 sites
that previously wrote to the error channel now call
completeGossipResult(nMsg.errPromise, err) instead.
ProcessRemoteAnnouncement and ProcessLocalAnnouncement now return
actor.Future[error] instead of chan error. The capacity-2 buffer
comment on ProcessRemoteAnnouncement, which was itself a workaround
for the old pattern, is removed along with the TODO referencing the
actor model redesign. ProcessSyncTransition in syncer.go follows the
same pattern: the errChan select is replaced with AwaitGossipResult
using a ContextFromQuit-derived context.
funding
The SendAnnouncement function type in funding.Config changes from
returning chan error to returning actor.Future[error]. The call sites
in addToGraph and announceChannel are updated to await the future with
AwaitGossipResult, passing a context derived from f.quit via
ContextFromQuit. Shutdown signals (context.Canceled and
discovery.ErrGossiperShuttingDown) are both mapped to
ErrFundingManagerShuttingDown via the new mapGossipError helper, which
also factors out the duplicated graph-rejected / unknown-error
handling. The three mock SendAnnouncement implementations in
manager_test.go are updated accordingly.
peer+server
In peer/brontide.go, the ProcessRemoteAnnouncement call in the gossip
stream handler intentionally discards the result since remote gossip
messages are fire-and-forget from the peer's perspective. The old
comment explaining why the chan error was unsafe to use is replaced
with a note that an unawaited Future[error] carries no overhead.
In server.go (applyChannelUpdate), the previous select on errChan and
the quit channel is replaced with ContextFromQuit + AwaitGossipResult.
This commit adds per-peer backpressure control to the onion message
actor system by introducing a BackpressureMailbox that uses Random
Early Detection (RED) to probabilistically drop messages when the
per-peer queue depth exceeds a configurable threshold.
The OnionActorFactory type now accepts variadic ActorOptions, allowing
the spawn call site (brontide) to provide per-peer mailbox configuration.
A DefaultOnionActorOpts helper provides the standard RED thresholds so
callers don't need to wire up the BackpressureMailbox manually.
Key changes:
- OnionActorFactory signature extended with ...ActorOption[*Request,
*Response] so backpressure policy is no longer baked into the factory.
- NewOnionActorFactory drops its shouldDrop parameter; it forwards opts
through to serviceKey.Spawn.
- DefaultOnionActorOpts(shouldDrop) returns the default backpressure
options (BackpressureMailbox + DefaultOnionMailboxSize).
- peer.Config gains OnionActorOpts callback for per-peer customization.
- server.go creates default opts once and returns them for every peer.
Add a gossip version parameter to ForEachNode, ForEachNodeCached, and
NumZombies in the Store interface and propagate it through the KV and
SQL implementations and the ChannelGraph wrapper.
The KVStore gates each method against GossipVersion1, returning
ErrVersionNotSupportedForKVDB for any other version. The SQLStore uses
the version to filter the underlying queries.
All call sites—routing graph, autopilot, RPC server, and the graph
migration integration test—are updated to pass the appropriate version
explicitly.
Add version-free shadow methods to VersionedGraph so it satisfies the
routing.Graph, graphdb.NodeTraverser, and related interfaces used by the
channel router and RPC layer.
FetchNodeFeatures and ForEachNodeDirectedChannel delegate to the graph
cache when available, falling back to the store with the baked-in
version. ForEachNode, ForEachNodeCached, ChannelView, and
NodeUpdatesInHorizon all forward to the embedded ChannelGraph with the
version pre-applied.
Update server.go and rpcserver.go to pass s.v1Graph (a *VersionedGraph
wrapping the main graphDB with GossipVersion1) wherever the routing and
session interfaces are needed, replacing direct *ChannelGraph references
that no longer satisfy those interfaces after the version parameters were
added.
Add an LRU cache to GraphNodeResolver to avoid repeated database lookups
when resolving SCIDs to node public keys. The cache stores up to 1000
compressed pubkey entries, which is sufficient for typical onion message
forwarding scenarios.
This change also introduces a NewGraphNodeResolver constructor to
properly initialize the cache, replacing direct struct literal usage.
This commit adds a configuration flag to disable onion messaging support.
When set, lnd will:
- Not advertise the onion messages feature bit (39) in init and node
announcements
- Skip creating the OnionEndpoint at server startup
- Not register an onion message handler with peers, so incoming onion
messages are not processed
Add onion message forwarding capability using the OnionPeerActor for
communication. Messages are routed through a receptionist pattern where
each peer has a dedicated OnionPeerActor for handling message sends.
The OnionEndpoint uses the sphinx router for decoding and decrypting the
onion message packet and the encrypted recipient data in the payload of
the onion messages.
Initialize a sphinx router without persistent replay protection logging
for onion message processing. Onion messages don't require replay
protection since they don't involve payment routing.
Previously we had db and application logic mixed on the db level.
We now move the config option KeepFailedPaymentAttempts to the
ChannelRouter level and move it out of the db level.
Add a gossip version parameter to HighestChanID in the Store interface
and both KV/SQL implementations. Update callers in the discovery
ChanSeries and server bootstrap code.
Add gossip version parameters to ForEachNodeCacheable and
ForEachChannelCacheable in the Store interface and both implementations.
Thread the version through SQL helpers and update call sites/tests
accordingly.
Add a gossip version parameter to ForEachSourceNodeChannel in the Store
interface and both KV/SQL implementations. The VersionedGraph wrapper
delegates with its baked-in version. Convert the
testAddChannelEdgeShellNodes and testForEachSourceNodeChannel tests to
run against both v1 and v2 gossip versions.
Update ForEachNodeChannel to accept a gossip version parameter,
allowing callers to specify which gossip version's channels should be
iterated. This change mirrors the approach taken in ForEachChannel and
prepares the graph database for supporting multiple gossip versions
while maintaining backward compatibility.
The Store interface is updated to include the version parameter, and
both KVStore and SQLStore implementations are updated accordingly:
- KVStore validates that only GossipVersion1 is requested, returning
ErrVersionNotSupportedForKVDB for other versions.
- SQLStore passes the version through to the underlying node query,
enabling version-specific channel iteration.
The ChannelGraph wrapper is updated to accept and pass through the
version parameter. VersionedGraph gains a ForEachNodeChannel method
that automatically uses its configured gossip version, providing a
clean interface for version-specific operations.
Update all call sites to explicitly pass lnwire.GossipVersion1, except
for the local channel manager in server.go which now uses the v1Graph
directly (matching the pattern used in other parts of the codebase).
Add version-aware DeleteChannelEdges method to VersionedGraph and
update call sites in graph builder, rpcserver, and server to use
versioned graphs. This ensures channel deletion operations are
properly scoped to the correct gossip version.
In this commit, we add a new param that'll allow us to scale up the
number of confirmations before we act on a new close. We'll use this
later to improve the current on chain handling logic.
In the previous iteration with endorsement
signaling, the recommendation was for the sender to
set it to 1 and that could have had privacy concerns
when first deploying given that the default was to
downgrade the signal to 0. In the latest proposal
the recommended default for both sending and
forwarding nodes is to set `accountable` to 0.
As a result, the dates have been removed given
that there are no privacy risks associated
with relaying the signal with zero values.
Fix bug where setSelfNode compared only the seconds component of
timestamps instead of the full timestamp. This caused the node to
attempt persisting an older timestamp than what existed in the
database during restart, resulting in "sql: no rows in result set"
errors.
Modifiers of the node announcement may add duplicate addresses, which we
remove here after the modifications were applied. This also ensures that
any previously added duplicate addresses are removed as well.
Introduced a new config value `upfront-shutdown-address`
in the `lnd.conf` file. This ensures that channel close
funds are transferred to the specified shutdown address.
The value applies to both the funder and the fundee but
can be overridden by the value specified during
`openchannel` or by the `channel acceptor`.
NOTE: If this field is set when opening a channel with a
peer that does not advertise support for upfront shutdown
feature, the channel open will fail.
Signed-off-by: Nishant Bansal <nishant.bansal.282003@gmail.com>
The only way to unblock SendCustomMessage is if the peer activates,
disconnects or the server shuts down. This means that if the context is
cancelled, we will still wait until one of those other events happen.
With this commit we thread the context through to SendCustomMessage, so
that if the context is cancelled, we can return early. This improves the
cancellation semantics.
This commit creates the necessary endpoints for onion messages.
Specifically, it adds the following:
- `SendOnionMessage` endpoint to send onion messages.
- `SubscribeOnionMessages` endpoint to subscribe to incoming onion
messages.
It uses the `msgmux` package to handle the onion messages.