Repository navigation
Conversation
a031b8a to
2eae968
Compare
…peer keeps refusing forwards for lack of outbound
2eae968 to
35889c1
Compare
There was a problem hiding this comment.
🔒 Automated security review — no issues found
Adds a demand-driven auto channel-open pipeline: a Quartz job scores peers from forwarding evidence, writes recommendations, and in per-node Auto mode promotes them into ChannelOperationRequests on the existing approval/signing path, with immediate dispatch only for hot wallets. I found no way in: Promote/Dismiss have no RPC/UI caller (job only, serialized via DisallowConcurrentExecution), all queries are parameterized EF, budget is tracked across plans and capped per run, multisig still requires human signatures, and a peer manufacturing the qualifying evidence is the feature's stated design behind three operator flags and a per-node budget.
Reviewed 17 files at 35889c1. Nothing to report.
Not a guarantee — one diff, no knowledge of your threat model.
🤖 Automated security review. It never pushes, approves or blocks; a suggestion applies only when you click Commit suggestion.
There was a problem hiding this comment.
🟡 Changes recommended
Critical funding-selection and promotion failure-handling issues can create unfundable or stranded pending requests while allowing the same coins or budget to be committed repeatedly.
5 open issues
1 file not reviewed
src/Migrations/20261117110255_AddSparkSignerIdentities.Designer.cs: Generated file
What changed in this PR
Adds demand-driven channel opening to NodeGuard’s routing automation, recommending fixed-size channels for earning peers with persistent outbound shortages.
Changes:
- Adds peer-level planning, automatic promotion, and funding-fee headroom checks, including the wallet-clamp work from #621.
- Expands Spark wallet management and signer identity pinning, and corrects changeless withdrawal accounting.
- Adds regression coverage, cumulative routing-profit reporting, and repository, image, and workflow updates.
| File | Description |
|---|---|
| THIRD-PARTY-NOTICES.md | Updates the NSpark fork attribution. |
| test/NodeGuard.Tests/TestHelpers/TestUtxos.cs | Adds reusable spendable-UTXO fixtures. |
| test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs | Tests changeless replacement amounts. |
| test/NodeGuard.Tests/Services/Spark/SparkWalletServiceTests.cs | Tests remote wallet identity validation. |
| test/NodeGuard.Tests/Services/Spark/SparkWalletManagementTests.cs | Updates wallet-management and remote-mode coverage. |
| test/NodeGuard.Tests/Services/Spark/SparkSignerProviderTests.cs | Tests handshake identity persistence. |
| test/NodeGuard.Tests/Services/Spark/SparkSignerIdentityPinTests.cs | Covers identity pinning and conflicts. |
| test/NodeGuard.Tests/Services/Spark/SparkSignerHandshakeTests.cs | Updates handshake validation coverage. |
| test/NodeGuard.Tests/Services/Spark/SparkSettingsTests.cs | Tests optional configured identity. |
| test/NodeGuard.Tests/Services/Spark/SparkGuardrailsTests.cs | Covers first-handshake balance attribution. |
| test/NodeGuard.Tests/Services/Spark/InMemorySparkSignerIdentities.cs | Adds an identity repository test double. |
| test/NodeGuard.Tests/Services/ChannelOpenInitiatorServiceTests.cs | Tests fixed-size planning gates and ranking. |
| test/NodeGuard.Tests/Services/BitcoinServiceTests.cs | Tests changeless amount consistency. |
| test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs | Covers withdrawal validation and Spark responses. |
| test/NodeGuard.Tests/Jobs/SparkSwapExitJobTests.cs | Tests exit serialization. |
| test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs | Covers orchestration, budgets, and operating modes. |
| test/NodeGuard.Tests/Helpers/LightningHelperTests.cs | Tests funding-fee and change headroom. |
| test/NodeGuard.Tests/E2E/WalletEventsE2ETests.cs | Verifies changeless interceptor amounts. |
| test/NodeGuard.Tests/E2E/SparkSwapOutE2ETests.cs | Exercises withdrawal with a pending Spark swap. |
| test/NodeGuard.Tests/Data/Repositories/WalletRepositoryTests.cs | Tests wallet-kind filtering. |
| test/NodeGuard.Tests/Data/Repositories/SparkSignerIdentityRepositoryTests.cs | Tests insert-once identity storage. |
| src/Shared/SparkWallets.razor | Adds the Spark wallet listing. |
| src/Shared/SparkWalletModals.razor | Expands details and swap-aware withdrawals. |
| src/Services/WithdrawalRequestService.cs | Normalizes changeless replacement amounts. |
| src/Services/Spark/SparkWalletService.cs | Supports remote wallet management and identity checks. |
| src/Services/Spark/SparkSignerProvider.cs | Integrates persistent identity verification. |
| src/Services/Spark/SparkSignerIdentityPin.cs | Implements first-use identity pinning. |
| src/Services/Spark/SparkSignerHandshake.cs | Separates policy checks from identity pinning. |
| src/Services/Spark/SparkSettings.cs | Makes identity optional and raises default balance capacity. |
| src/Services/Spark/SparkGuardrails.cs | Uses the connected identity for balance attribution. |
| src/Services/NBXplorerService.cs | Updates a repository reference in a comment only. |
| src/Services/LightningService.cs | Exposes paired outbound fees and fixes log arguments. |
| src/Services/ChannelOpenPromotionService.cs | Creates and dispatches recommended channel requests. |
| src/Services/ChannelOpenInitiatorService.cs | Adds the fixed-size peer planner. |
| src/Services/BitcoinService.cs | Rejects inconsistent changeless request amounts. |
| src/Rpc/NodeGuardService.cs | Normalizes withdrawals and returns Spark exit details. |
| src/Proto/nodeguard.proto | Documents changeless amounts and extends Spark responses. |
| src/Program.cs | Registers services and schedules automatic channel opening. |
| src/Pages/Wallets.razor | Separates treasury and Spark tabs. |
| src/NodeGuard.csproj | Updates the telemetry exporter and fork comment. |
| src/Migrations/ApplicationDbContextModelSnapshot.cs | Records the signer identity schema. |
| src/Migrations/20261117110255_AddSparkSignerIdentities.cs | Creates the signer identity table. |
| src/Jobs/SparkSwapExitJob.cs | Serializes scheduled and manual exits. |
| src/Jobs/AutoChannelOpenJob.cs | Aggregates peer evidence and orchestrates recommendations. |
| src/Helpers/LightningHelper.cs | Estimates channel funding headroom. |
| src/Data/Repositories/WalletRepository.cs | Adds optional wallet-kind filtering. |
| src/Data/Repositories/SparkSignerIdentityRepository.cs | Persists identities without overwriting existing pins. |
| src/Data/Repositories/Interfaces/IWalletRepository.cs | Exposes wallet-kind filtering. |
| src/Data/Repositories/Interfaces/ISparkSignerIdentityRepository.cs | Defines identity persistence operations. |
| src/Data/Models/SparkSignerIdentity.cs | Models a seed/account identity pin. |
| src/Data/ApplicationDbContext.cs | Maps signer identities and their unique key. |
| README.md | Updates repository and project links. |
| go.mod | Updates the Go module path. |
| docs/spark-swaps.md | Documents pinning, withdrawals, and signer transitions. |
| docker/spark/README.md | Updates development image references. |
| docker/spark/docker-compose.yml | Uses Lunar-Rails development images. |
| docker/grafana/provisioning/dashboards/routing.json | Adds cumulative routing profit. |
| docker/docker-compose.dev.yml | Updates an NBXplorer reference in a comment only. |
| CONTRIBUTING.md | Updates issue-reporting links. |
| .justfile | Updates the remote signer URL. |
| .gitmodules | Updates signer and NSpark submodule URLs. |
| .github/workflows/spark-dev-images.yml | Updates image destinations and action versions. |
| .github/workflows/dotnet.yml | Updates actions and selects one image for scanning. |
| .github/workflows/cleanup.yaml | Updates the container-pruning action. |
| .github/workflows/actions.lock | Synchronizes workflow action pins. |
Review effort: Balanced
| if (await RecordAndMaybePromote(node, plan)) | ||
| { | ||
| remainingBudget -= plan.SuggestedCapacitySats; |
|
|
||
| var utxos = await _coinSelectionService.GetAvailableUTXOsAsync(derivationStrategy); | ||
|
|
||
| return LightningHelper.MaxFundableChannelSats(derivationStrategy, utxos, feeRate); |
| if (!updated) | ||
| { | ||
| _logger.LogError("Channel operation request {RequestId} was created but recommendation {Id} could not be marked promoted: {Error}", | ||
| request.Id, recommendationId, updateError); | ||
| return (false, updateError); |
| catch (Exception e) | ||
| { | ||
| _logger.LogError(e, "Error promoting channel open recommendation {Id}", recommendationId); | ||
| return (false, e.Message); |
| // cheapest route to a peer the drain evidence proves is expensive. It opens at the price we | ||
| // already charge that peer, captured with the evidence and gated on — asking LND again here | ||
| // would reprice off gossip and could contradict the number the operator approved. | ||
| if (recommendation.InheritedFeeRatePpm is not > 0) |
There was a problem hiding this comment.
🔒 Automated security review
This PR adds AutoChannelOpenJob plus a planner (ChannelOpenInitiatorService), a promoter (ChannelOpenPromotionService) and a recommendation repository that automatically open fixed-size channels, funded from a per-node wallet, to peers whose forwarding evidence crosses thresholds. All new data access is parameterized EF Core (no SQL injection surface), the job is serialized via [DisallowConcurrentExecution], the (NodeId, PeerPubKey) upsert is backed by a unique index, and budget/size/cooldown/per-run-cap safeguards are present. The one weakness found: a peer that farms the evidence thresholds and then cancels each funding flow (RemoteCanceledFunding → request Failed) is released from the per-peer cooldown and never consumes budget, so the job re-promotes it every run indefinitely — the two safeguards meant to bound automated hot-wallet spending are both bypassed when the failure is caused by the peer itself.
Reviewed Lunar-Rails/NodeGuard #660 at 15c531d — 1 inline finding(s), 0 not anchorable, 0 below the posting threshold.
🤖 Automated security review. It never pushes, approves or blocks; a suggestion applies only when you click Commit suggestion.
| // Ahead of the cooldown this run derives: a promotion whose channel never opened committed | ||
| // nothing to the peer, so leaving it Promoted would suppress the peer for a channel it never got. | ||
| var unrealized = await _recommendationRepository.FailUnrealizedPromotions(node.Id); |
There was a problem hiding this comment.
MEDIUM · concurrency — Peer-caused open failures bypass both the cooldown and the budget, enabling an infinite auto-open retry loop
The attacker farms the evidence thresholds (50k sats of fees over 7d, 5 INSUFFICIENT_BALANCE refusals per 6h — failed HTLCs are free to generate) so the job promotes them. Each time ChannelOpenJob runs, they abort the funding flow: LND returns 'remote canceled funding' → RemoteCanceledFundingException → the request is marked Failed with no retry (ChannelOpenJob.cs:97-101). On the next run, FailUnrealizedPromotions flips the recommendation Promoted→Failed, explicitly 'releasing their peers from the cooldown', and GetOpenSatsCommittedSince excludes Failed requests, so the attempt consumes no budget either. The peer still qualifies on unchanged evidence, is re-planned and re-promoted in the same run. The loop repeats every job interval forever: the per-peer cooldown and the sats budget — the only two bounds on how often this automation engages the hot wallet — never apply to failures the peer itself causes.
Threat: An external Lightning peer of a managed node that has AutoChannelOpenMode.Auto with a hot funding wallet, starting from An open channel to the victim node and the ability to route/fail HTLCs through it; no NodeGuard credentials → The victim's node automatically re-attempts a fixed-size channel open to the attacker every run indefinitely — repeated template-PSBT generation, internal-wallet signing, LND funding-shim registrations, and ChannelOperationRequest/audit row growth — despite the operator-configured cooldown and budg…
Checks
Ruled out: Verified DisallowConcurrentExecution serializes the job; checked GetLastDecisionByPeer (only Promoted/Dismissed rows feed the cooldown) and GetOpenSatsCommittedSince (excludes Failed/Cancelled/Rejected), so neither guard bounds peer-induced failures. No lifetime attempt cap exists — MAX_PLANS_PER_RUN is per run. The code comments assume a failed promotion 'committed nothing to the peer', i.e. no-fault failure; the RemoteCanceledFunding path (ChannelOpenJob.cs:97) is exactly the opposite case and is not distinguished.
Verified: Confirmed every link: ChannelOpenJob.cs:97-101 marks RemoteCanceledFunding requests Failed with no retry; FailUnrealizedPromotions (ChannelOpenRecommendationRepository.cs:160) flips Promoted→Failed and GetLastDecisionByPeer (line 190) counts only Promoted/Dismissed, so the cooldown never engages; GetOpenSatsCommittedSince (ChannelOperationRequestRepository.cs:224-236) excludes Failed, so no budget is consumed; Upsert recycles the Failed row to Open and ChannelOpenInitiatorService.Reject has no failure-history guard, so the peer is re-planned and re-promoted the same run, repeating every job interval. Only in-repo comments claim the no-fault design, which cannot refute; the subsystem is new in this PR. Attacker cost (sustained 50k sats/wk fees, no fund loss since the funding tx never broadcasts) fits the claimed MEDIUM.
🤖 automated review — reply not-an-issue to dismiss
15c531d to
35889c1
Compare


AutoChannelOpenJob runs every 30 minutes (1 in dev) behind ROUTING_ENGINE_ENABLED and AUTO_CHANNEL_OPEN_ENABLED. Per node it sums the evidence over each peer's open channels, since LND forwards non-strictly, and recommends a channel when the peer earned at least the minimum fees over the lookback, refused enough forwards with INSUFFICIENT_BALANCE in the shortage window, and is still below the low-outbound threshold now. The size is the node's fixed size: a peer it doesn't fit (wallet or budget) is skipped, never shrunk.
ChannelOpenInitiatorService is the pure planner. ChannelOpenPromotionService turns a recommendation into a pending ChannelOperationRequest at the highest fee rate we already charge the peer; a hot wallet goes straight to ChannelOpenJob. In Auto mode the job promotes on its own unless the node is in dry run.
Also carries the #621 fix: MaxFundableChannelSats leaves room for the funding fee and a change output, from coin selection's spendable coins.
The defaults (7 days / 50,000 sats, 6 h / 5 refusals, 20%) still need checking against prod forwarding data.