← Back to Pull requests

htlcswitch: align forwarding response and circuit lifetimes #11258

Merged
ziggie1984 merged 19 files (1607 lines) on Sep 25, 2026 03:16 UTC
View on GitHub
ziggie1984 ziggie1984 commented on Sep 24, 2026 14:07 UTC
Author

Summary

Forwarding responses participate in switch recovery through per-channel
package state, while resolution messages and payment circuits have separately
managed lifecycles.

This PR adds circuit-indexed persistence for forwarding responses and
integrates it with the switch's existing startup and cleanup flows.

Changes

  • add a circuit-keyed store for settle and fail responses

  • integrate response persistence with both channel cleanup strategies

  • include persisted response state in circuit cleanup decisions

  • process persisted responses during switch startup

  • classify known-preimage commitment differences through the existing

  • resolution path
  • keep overlapping response sources idempotent
  • Persistence

    Response persistence and synchronous package cleanup share a transaction.
    Startup propagates unreadable state and removes records that no longer refer to
    an open circuit.

    Testing

  • response serialization, lookup and filtering

  • both channel cleanup implementations

  • circuit retention and storage-error handling

  • startup replay and orphan cleanup

  • local payment results and duplicate response handling

  • known-preimage commitment differences
  • Diff: 1607 lines (+1551 / -56) across 19 files Reviewer: gijswijs Review duration: 788m
    All Vouch review confidence checks passed
    Residual risk 0.14 = Change Risk (0.72) × (1 − Review Confidence (0.81)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 1607 lines diff across 19 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.77 · 5 substantive comment(s)
    0.77
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    80%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    14 items
    gijswijs gijswijs approved these changes on Sep 24, 2026 14:26 UTC
    Approved Reviewer

    LGTM.

    Roasbeef Roasbeef commented on code on Sep 25, 2026 00:04 UTC
    Code Review
    channeldb/fwd_response_store.go:1
    @@ -0,0 +1,224 @@
    +package channeldb
    +
    +import (
    +	"bytes"
    +	"errors"
    +	"fmt"
    +	"io"
    +
    +	"github.com/lightningnetwork/lnd/graph/db/models"
    +	"github.com/lightningnetwork/lnd/kvdb"
    +	"github.com/lightningnetwork/lnd/lnwire"
    +)
    +
    +var (
    +	// fwdResponseBucketKey is the root level bucket that stores the
    +	// outgoing CircuitKey -> settle/fail message mapping independently
    +	// of per-channel forwarding packages.
    +	fwdResponseBucketKey = []byte("fwd-response-store-bucket-key")
    +
    +	// ErrFwdResponseNotFound identifies a clean forwarding response store
    +	// miss. Callers must not treat other storage errors as proof that no
    +	// response exists.
    +	ErrFwdResponseNotFound = errors.New("forwarding response not found")
    +
    +	// ErrUnknownFwdResponse signals that a stored response deserialized
    +	// into a message that is neither a settle nor a fail.
    +	ErrUnknownFwdResponse = errors.New("unknown forwarding response type")
    +)
    +
    +// FwdResponse is an off-chain settle or fail retained under its outgoing
    +// circuit key. This gives forwarding responses the same circuit-oriented
    +// lookup model used by contractcourt resolution messages.
    +type FwdResponse struct {

    👍

    github-actions[bot] github-actions[bot] commented on Sep 25, 2026 00:04 UTC
    Bot

    🔴 PR Severity: CRITICAL

    gh pr view | 17 files | 1389 lines changed

    <details>
    <summary>🔴 <strong>Critical</strong> (9 files)</summary>

  • channeldb/channel.go - channel state persistence logic

  • channeldb/db.go - core channel database wiring

  • channeldb/fwd_response_store.go - new persisted store for forwarding responses

  • contractcourt/channel_arbitrator.go - on-chain dispute/breach handling state machine

  • htlcswitch/circuit_map.go - HTLC circuit tracking used by the forwarding switch

  • htlcswitch/mock.go - htlcswitch test scaffolding touched alongside switch changes

  • htlcswitch/resolution_store.go - HTLC resolution persistence

  • htlcswitch/switch.go - core HTLC forwarding/routing state machine

  • server.go - core server coordination/wiring
  • </details>

    <details>
    <summary>🟢 <strong>Low</strong> (8 files)</summary>

  • docs/release-notes/release-notes-0.20.5.md - release notes

  • docs/release-notes/release-notes-0.21.4.md - release notes

  • channeldb/fwd_response_store_test.go - test only

  • contractcourt/channel_arbitrator_test.go - test only

  • htlcswitch/circuit_map_test.go - test only

  • htlcswitch/circuit_test.go - test only

  • htlcswitch/resolution_store_test.go - test only

  • htlcswitch/switch_fwd_response_test.go - test only
  • </details>

    Analysis

    This PR adds a new forward-response store (channeldb/fwd_response_store.go) and wires it through htlcswitch/switch.go and htlcswitch/circuit_map.go, plus modifies contractcourt/channel_arbitrator.go and server.go. It touches multiple distinct CRITICAL packages (channeldb, contractcourt, htlcswitch) that make up the core HTLC forwarding and on-chain dispute resolution path, and non-test/non-generated changes exceed 500 lines. This is squarely core payment-routing and channel-state logic and warrants expert review.

    ---
    <sub>To override, add a severity-override-{critical,high,medium,low} label.</sub>
    <!-- pr-severity-bot -->

    Roasbeef Roasbeef commented on code on Sep 25, 2026 00:04 UTC
    Code Review
    htlcswitch/switch.go:1
    @@ -167,6 +167,16 @@ type Config struct {
     	// forwarding packages, and ack settles and fails contained within them.
     	SwitchPackager channeldb.FwdOperator
     
    +	// FetchFwdResponses returns every off-chain response rescued from a
    +	// closed channel that has not been reaped yet.
    +	FetchFwdResponses func() ([]*channeldb.FwdResponse, error)

    Can be wrapped up into a new interface to collocate the new responsibility.

    Roasbeef Roasbeef commented on code on Sep 25, 2026 00:10 UTC
    Code Review
    contractcourt/channel_arbitrator.go:1
    @@ -2061,14 +2075,16 @@ func (c *ChannelArbitrator) isPreimageAvailable(hash lntypes.Hash) (bool,
     	case errors.Is(err, invoices.ErrInvoiceNotFound) ||
     		errors.Is(err, invoices.ErrNoInvoicesCreated):
     
    -		return false, nil
    +		return lntypes.Preimage{}, false, nil
     	default:
    -		return false, err
    +		return lntypes.Preimage{}, false, err
     	}
     
    -	preimageAvailable = invoice.Terms.PaymentPreimage != nil
    +	if invoice.Terms.PaymentPreimage == nil {
    +		return lntypes.Preimage{}, false, nil
    +	}
     
    -	return preimageAvailable, nil
    +	return *invoice.Terms.PaymentPreimage, true, nil

    When the pre-image is found, true is always returned, so might as well return fn.Option[lntypes.Preimage]. Then can go further to wrap then in fn.Result, then it's a bit clearer as you can collapse the redundant return type (non-blank preimage is never seen with false as a return value).

    starius starius approved these changes on Sep 25, 2026 00:10 UTC
    Approved Reviewer

    LGTM! 🎉

    Great PR! Thanks!

    Roasbeef Roasbeef commented on code on Sep 25, 2026 00:13 UTC
    Code Review
    htlcswitch/switch.go:1
    @@ -359,6 +373,19 @@ type Switch struct {
     
     // New creates the new instance of htlc switch.
     func New(cfg Config, currentHeight uint32) (*Switch, error) {
    +	// These are dereferenced unconditionally during startup, so a missing
    +	// one must fail here rather than panic mid-recovery.
    +	switch {
    +	case cfg.CheckFwdResponse == nil:

    If these are rolled into an interface, only need a single nil check there.

    ziggie1984 ziggie1984 commented on code on Sep 25, 2026 02:11 UTC
    Code Review
    htlcswitch/switch.go:1
    @@ -167,6 +167,16 @@ type Config struct {
     	// forwarding packages, and ack settles and fails contained within them.
     	SwitchPackager channeldb.FwdOperator
     
    +	// FetchFwdResponses returns every off-chain response rescued from a
    +	// closed channel that has not been reaped yet.
    +	FetchFwdResponses func() ([]*channeldb.FwdResponse, error)

    will be done in a followup, kept it as is for easier backporting

    ziggie1984 ziggie1984 commented on code on Sep 25, 2026 02:11 UTC
    Code Review
    contractcourt/channel_arbitrator.go:1
    @@ -2061,14 +2075,16 @@ func (c *ChannelArbitrator) isPreimageAvailable(hash lntypes.Hash) (bool,
     	case errors.Is(err, invoices.ErrInvoiceNotFound) ||
     		errors.Is(err, invoices.ErrNoInvoicesCreated):
     
    -		return false, nil
    +		return lntypes.Preimage{}, false, nil
     	default:
    -		return false, err
    +		return lntypes.Preimage{}, false, err
     	}
     
    -	preimageAvailable = invoice.Terms.PaymentPreimage != nil
    +	if invoice.Terms.PaymentPreimage == nil {
    +		return lntypes.Preimage{}, false, nil
    +	}
     
    -	return preimageAvailable, nil
    +	return *invoice.Terms.PaymentPreimage, true, nil

    Accepted took the fn.Option approach

    ziggie1984 ziggie1984 commented on code on Sep 25, 2026 02:12 UTC
    Code Review
    htlcswitch/switch.go:1
    @@ -359,6 +373,19 @@ type Switch struct {
     
     // New creates the new instance of htlc switch.
     func New(cfg Config, currentHeight uint32) (*Switch, error) {
    +	// These are dereferenced unconditionally during startup, so a missing
    +	// one must fail here rather than panic mid-recovery.
    +	switch {
    +	case cfg.CheckFwdResponse == nil:

    see comment above regarding the interface

    Roasbeef Roasbeef approved these changes on Sep 25, 2026 02:13 UTC
    Approved Reviewer

    LGTM

    github-actions[bot] github-actions[bot] commented on Sep 25, 2026 03:19 UTC
    Bot

    Created backport PR for v0.20.x-branch:

  • #11260 with remaining conflicts!
  • Please cherry-pick the changes locally and resolve any conflicts.

    git fetch origin backport-11258-to-v0.20.x-branch
    git worktree add --checkout .worktree/backport-11258-to-v0.20.x-branch backport-11258-to-v0.20.x-branch
    cd .worktree/backport-11258-to-v0.20.x-branch
    git reset --hard HEAD^
    git cherry-pick -x 94c598a01ebc2ee21f7827b31eb1a9754d761768 b17f70d797e32ef4dc933156a330238b254747c1 dd0c09d8f58d01a946897007c0511044b035d8d8 413b02cd53f7cf7afd0febe43ef86f113471df25
    git push --force-with-lease
    

    github-actions[bot] github-actions[bot] commented on Sep 25, 2026 03:19 UTC
    Bot

    Created backport PR for v0.21.x-branch:

  • #11261 with remaining conflicts!
  • Please cherry-pick the changes locally and resolve any conflicts.

    git fetch origin backport-11258-to-v0.21.x-branch
    git worktree add --checkout .worktree/backport-11258-to-v0.21.x-branch backport-11258-to-v0.21.x-branch
    cd .worktree/backport-11258-to-v0.21.x-branch
    git reset --hard HEAD^
    git cherry-pick -x 94c598a01ebc2ee21f7827b31eb1a9754d761768 b17f70d797e32ef4dc933156a330238b254747c1 dd0c09d8f58d01a946897007c0511044b035d8d8 413b02cd53f7cf7afd0febe43ef86f113471df25
    git push --force-with-lease
    

    Reviewers
    Assignees
    ziggie1984 ziggie1984
    Labels
    risk: low confidence: 80.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 80.7% · Lower = rushed or shallow review
    80.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 13.8% · Safe to merge
    13.8%