From 766e73e0a11837a56386bfdf55ba60814805fa05 Mon Sep 17 00:00:00 2001 From: Marcos Date: Tue, 1 Dec 2026 17:31:23 +0100 Subject: [PATCH] feat: keep auto channel open from recommending swap providers the node swaps out through --- docker/e2e/nodeguard-entrypoint.sh | 3 + docs/auto-channel-open.md | 26 ++++- src/Helpers/Constants.cs | 24 +++++ src/Jobs/AutoChannelOpenJob.cs | 4 +- src/Pages/Nodes.razor | 3 +- src/Services/ChannelOpenInitiatorService.cs | 11 ++- src/Services/SwapProviderLimits.cs | 26 +++++ .../E2E/AutoChannelOpenE2ETests.cs | 94 +++++++++++++++---- .../Jobs/AutoChannelOpenJobTests.cs | 63 +++++++++++++ .../ChannelOpenInitiatorServiceTests.cs | 18 +++- .../Services/SwapOutWarningServiceTests.cs | 9 +- 11 files changed, 254 insertions(+), 27 deletions(-) diff --git a/docker/e2e/nodeguard-entrypoint.sh b/docker/e2e/nodeguard-entrypoint.sh index 5e5a8c0ae..85e05a66c 100755 --- a/docker/e2e/nodeguard-entrypoint.sh +++ b/docker/e2e/nodeguard-entrypoint.sh @@ -12,6 +12,9 @@ until [ -s "$ENV_FILE" ] || [ $i -ge 60 ]; do i=$((i+1)); sleep 2; done if [ -s "$ENV_FILE" ]; then set -a; . "$ENV_FILE"; set +a echo "Loaded LND connection env for ALICE/BOB/CAROL." + # AutoChannelOpenE2ETests: carol stands in for a 40swap node. It only counts for a node that gives + # 40swap a weight, which the seeded nodes don't. + export FORTYSWAP_NODE_PUBKEYS="${FORTYSWAP_NODE_PUBKEYS:-$CAROL_PUBKEY}" else echo "WARNING: $ENV_FILE missing/empty; NodeGuard may fail to reach LND." >&2 fi diff --git a/docs/auto-channel-open.md b/docs/auto-channel-open.md index cb3f7fc26..078f3996b 100644 --- a/docs/auto-channel-open.md +++ b/docs/auto-channel-open.md @@ -1,6 +1,6 @@ # Auto channel open -Auto channel open proposes a new channel to a peer when two things are true: the route to that peer has been earning us fees, and we have recently been turning payments to it away for lack of outbound liquidity. The channel always has the same size, set per node. Peers we want channels with regardless, such as a swap service, can be [reserved](#reserved-peers) a share of the budget. +Auto channel open proposes a new channel to a peer when two things are true: the route to that peer has been earning us fees, and we have recently been turning payments to it away for lack of outbound liquidity. The channel always has the same size, set per node. Peers we want channels with regardless can be [reserved](#reserved-peers) a share of the budget. A swap provider the node swaps out through [never gets one](#swap-providers). [`AutoChannelOpenJob`](../src/Jobs/AutoChannelOpenJob.cs) runs every 30 minutes (every minute in a dev environment) as part of the routing engine (see [routing-engine.md](routing-engine.md)). It writes recommendations, which an operator promotes from the Routing Management page. In **Auto** mode the job promotes them itself. Either way a promotion only creates a channel open request: funding still goes through the usual approval and signing flow. @@ -27,6 +27,24 @@ The size is never adjusted: a peer whose channel doesn't fit the wallet or the b - Outbound and capacity come from LND's `ListChannels` at the time of the run. Check 3 matters because the refusals are history: a rebalance or a payment the other way may have refilled the peer since. - What the wallet can fund is computed from the wallet's spendable coins (locked and frozen ones excluded) at mempool's hour fee rate, leaving room for the funding fee and a change output. +## Swap providers + +A node gets no recommendation to a swap provider it swaps out through. The swap-outs are our own payments to the provider, so they would drain the new channel as soon as it opened. + +A node swaps out through every provider it gives a weight above 0 (Loop alone when none has one), however small the weight. The provider's Lightning nodes are listed by pubkey (see below). A peer on the list of such a provider is rejected before any other check, [reserved](#reserved-peers) or not, and logged with the reason. An open recommendation to it expires on the next run. A provider the node gives no weight is treated like any other peer. + +The check is only on recommendations: a channel open request created by hand is not stopped. + +Each provider's list has a default, the provider's mainnet nodes: + +| Variable | Default | +|---|---| +| `LOOP_NODE_PUBKEYS` | `021c97a90a411ff2b10dc2a8e32de2f29d2fa49d41bfbb52bd416e460db0747d0d` | +| `FORTYSWAP_NODE_PUBKEYS` | empty: 40swap is not blocked until its nodes are listed | +| `SPARK_NODE_PUBKEYS` | `039174f846626c6053ba80f5443d0db33da384f1dde135bf7080ba1eec465019c3`, `02a98e8c590a1b5602049d6b21d8f4c8861970aa310762f42eae1b2be88372e924` | + +Setting a variable replaces its default, it does not add to it: list every pubkey, comma-separated. An empty value clears the list, so that provider is no longer blocked. + ## Modes and promotion Each node runs in one of two modes: @@ -43,11 +61,12 @@ Promoting creates a `ChannelOperationRequest` to open a public channel to the pe ## Reserved peers -Some peers need channels whether or not they earn us anything. A swap service such as Loop is the usual case: our swap-outs are our own payments to it, not forwards, so the route to it never earns fees and never passes check 1. Each node can list such peers on the Nodes page (Automatic Channel Opening ▸ Reserved Peers). Each one is a node registered in NodeGuard, picked from a list, with a share of the budget in percent, a fee rate and a base fee. The shares of a node add up to at most 100%. Both fees are required. +Some peers need channels whether or not they earn us anything: a peer we mostly pay ourselves rather than forward to never earns fees on the route, so it never passes check 1. Each node can list such peers on the Nodes page (Automatic Channel Opening ▸ Reserved Peers). Each one is a node registered in NodeGuard, picked from a list, with a share of the budget in percent, a fee rate and a base fee. The shares of a node add up to at most 100%. Both fees are required. A reserved peer skips the evidence (checks 1, 2 and 5). It qualifies when: - the usable outbound to it is below `AUTO_CHANNEL_OPEN_LOW_OUTBOUND_PCT` of the capacity we have with it, or we have no channel with it at all; - it is not on cooldown; +- it is not a [swap provider](#swap-providers) the node swaps out through; - the node's channel size fits the funding wallet and the budget left for it (see below). Reserved peers are evaluated ahead of the others in each run, so the per-run cap can't crowd them out. Their recommendations show a **reserved** badge on the Routing Management page, and the panel shows what each share has committed this period. @@ -81,7 +100,7 @@ What counts as committed is the capacity of every channel open request from the - A reserved peer uses its own share first, then the unreserved part. - Committed sats count against the peer the request opens to, so an open made by hand to a reserved peer uses up its share too. Whatever a reserved peer commits beyond its share comes out of the unreserved part. -For example, with a 10 BTC budget and Loop reserved at 30%, other peers can commit at most 7 BTC, and Loop up to 3 BTC on its own share plus whatever the others leave of the 7. +For example, with a 10 BTC budget and a peer reserved at 30%, other peers can commit at most 7 BTC, and the reserved peer up to 3 BTC on its own share plus whatever the others leave of the 7. ## Settings @@ -99,6 +118,7 @@ For example, with a 10 BTC budget and Loop reserved at 30%, other peers can comm | `AUTO_CHANNEL_OPEN_MAX_PLANS_PER_RUN` | 5 | Most recommendations per node per run. | | `AUTO_CHANNEL_OPEN_DEFAULT_BUDGET_REFRESH_HOURS` | 720 | Budget period when the node sets none. | | `AUTO_CHANNEL_OPEN_JOB_INTERVAL_MINUTES` | 30 | Job interval; 1 in a dev environment. | +| `LOOP_NODE_PUBKEYS`, `FORTYSWAP_NODE_PUBKEYS`, `SPARK_NODE_PUBKEYS` | see [Swap providers](#swap-providers) | Pubkeys of each swap provider's Lightning nodes, comma-separated. | **Per node**, on the Nodes page (liquidity management ▸ Automatic Channel Opening): - **Enable automatic channel opening** and the **mode**. diff --git a/src/Helpers/Constants.cs b/src/Helpers/Constants.cs index 83879495e..0019cabb9 100644 --- a/src/Helpers/Constants.cs +++ b/src/Helpers/Constants.cs @@ -433,6 +433,21 @@ public class Constants // In dev this is 1 minute. public static int AUTO_CHANNEL_OPEN_JOB_INTERVAL_MINUTES = 30; + // Lightning pubkeys of each swap provider's nodes, comma-separated in the environment. A node gets no + // channel open recommendation to a provider it swaps out through. + public static IReadOnlySet LOOP_NODE_PUBKEYS = new HashSet() + { + "021c97a90a411ff2b10dc2a8e32de2f29d2fa49d41bfbb52bd416e460db0747d0d", + }; + + public static IReadOnlySet FORTYSWAP_NODE_PUBKEYS = new HashSet(); + + public static IReadOnlySet SPARK_NODE_PUBKEYS = new HashSet() + { + "039174f846626c6053ba80f5443d0db33da384f1dde135bf7080ba1eec465019c3", + "02a98e8c590a1b5602049d6b21d8f4c8861970aa310762f42eae1b2be88372e924", + }; + #endregion Auto Channel Open @@ -450,6 +465,11 @@ public class Constants return envVariable; } + // Null when the variable is unset, so the default stays. + private static IReadOnlySet? ParsePubKeys(string? commaSeparated) => + commaSeparated?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + static Constants() { IS_DEV_ENVIRONMENT = StringHelper.IsTrue(Environment.GetEnvironmentVariable("IS_DEV_ENVIRONMENT")); @@ -814,6 +834,10 @@ static Constants() var acoInterval = Environment.GetEnvironmentVariable("AUTO_CHANNEL_OPEN_JOB_INTERVAL_MINUTES"); if (acoInterval != null) AUTO_CHANNEL_OPEN_JOB_INTERVAL_MINUTES = int.Parse(acoInterval); if (IS_DEV_ENVIRONMENT) AUTO_CHANNEL_OPEN_JOB_INTERVAL_MINUTES = 1; + + LOOP_NODE_PUBKEYS = ParsePubKeys(Environment.GetEnvironmentVariable("LOOP_NODE_PUBKEYS")) ?? LOOP_NODE_PUBKEYS; + FORTYSWAP_NODE_PUBKEYS = ParsePubKeys(Environment.GetEnvironmentVariable("FORTYSWAP_NODE_PUBKEYS")) ?? FORTYSWAP_NODE_PUBKEYS; + SPARK_NODE_PUBKEYS = ParsePubKeys(Environment.GetEnvironmentVariable("SPARK_NODE_PUBKEYS")) ?? SPARK_NODE_PUBKEYS; } } diff --git a/src/Jobs/AutoChannelOpenJob.cs b/src/Jobs/AutoChannelOpenJob.cs index 797172c03..744ba1f3c 100644 --- a/src/Jobs/AutoChannelOpenJob.cs +++ b/src/Jobs/AutoChannelOpenJob.cs @@ -255,6 +255,7 @@ private async Task> BuildPeerSnapshots(Node node, DateTimeOff var policyByChanId = policyTask.Result; var lastDecisionByPeer = lastDecisionTask.Result; var cooldownCutoff = now.AddHours(-Constants.AUTO_CHANNEL_OPEN_PEER_COOLDOWN_HOURS); + var swapProviderByPeer = SwapProviderLimits.NodesSwappedThrough(node); // Fees and refusals on channels that have since closed are dropped with them: only the peer's // current channels map back to a pubkey. @@ -287,7 +288,8 @@ private async Task> BuildPeerSnapshots(Node node, DateTimeOff .Where(p => p != null) .MaxBy(p => p!.FeeRatePpm) ?? reserved.GetValueOrDefault(x.Peer), OnCooldown: lastDecisionByPeer.TryGetValue(x.Peer, out var last) && last > cooldownCutoff, - IsReserved: reserved.ContainsKey(x.Peer))) + IsReserved: reserved.ContainsKey(x.Peer), + SwapProvider: swapProviderByPeer.TryGetValue(x.Peer, out var provider) ? provider : null)) .ToList(); } diff --git a/src/Pages/Nodes.razor b/src/Pages/Nodes.razor index 15a3f07db..ad7ea79c0 100644 --- a/src/Pages/Nodes.razor +++ b/src/Pages/Nodes.razor @@ -902,10 +902,11 @@ Reserved Peers - Registered nodes with their own share of the budget, such as a swap service. They skip the earning evidence: a reserved peer gets a channel + Registered nodes with their own share of the budget. They skip the earning evidence: a reserved peer gets a channel whenever its usable outbound is below @Constants.AUTO_CHANNEL_OPEN_LOW_OUTBOUND_PCT%, or we have no channel with it yet. Other peers can't spend a reserved share. A reserved peer spends its own share first, then the rest of the budget. The fee rate and base fee are what its channel opens at when we have no channel with it to copy a fee from. + A swap provider this node swaps out through gets no channel, reserved or not. @foreach (var peer in _reservedPeers) { diff --git a/src/Services/ChannelOpenInitiatorService.cs b/src/Services/ChannelOpenInitiatorService.cs index d1a2d34a6..830524fb6 100644 --- a/src/Services/ChannelOpenInitiatorService.cs +++ b/src/Services/ChannelOpenInitiatorService.cs @@ -26,6 +26,7 @@ namespace NodeGuard.Services; /// Everything the planner knows about one peer, aggregated over all our open channels to it. LND /// forwards non-strictly and reports whichever channel it tried last, so the peer is the identity. /// A reserved peer we have no channel with has a zero capacity and the policy set on its reservation. +/// is set when the peer is a node of a provider we swap out through. /// public record PeerSnapshot( string PeerPubKey, @@ -36,7 +37,8 @@ public record PeerSnapshot( long CapacitySats, LocalOutboundPolicy? OutboundPolicy, bool OnCooldown, - bool IsReserved = false); + bool IsReserved = false, + SwapProvider? SwapProvider = null); public record ChannelOpenInitiatorTunables( long MinEarnedFeeSats, @@ -70,6 +72,7 @@ public record ChannelOpenClassification( /// Channel-open planner. Pure, no I/O. A peer gets a fixed-size channel when the route to it has /// earned us fees, it refused forwards recently for lack of outbound, and it is still short now. /// A reserved peer skips the evidence: being short now, or having no channel at all, is enough. +/// A swap provider the node swaps out through never gets one. /// public static class ChannelOpenInitiatorService { @@ -120,6 +123,12 @@ public static ChannelOpenClassification Evaluate( private static string? Reject(PeerSnapshot peer, ChannelOpenInitiatorTunables t) { + // Reserved or not: the swap-outs we pay through it would drain the new channel. + if (peer.SwapProvider != null) + { + return $"it is a {peer.SwapProvider} node, a swap provider the node swaps out through"; + } + if (peer.OnCooldown) { return "on cooldown after a recent promotion or dismissal"; diff --git a/src/Services/SwapProviderLimits.cs b/src/Services/SwapProviderLimits.cs index 41c652f31..53d1c5058 100644 --- a/src/Services/SwapProviderLimits.cs +++ b/src/Services/SwapProviderLimits.cs @@ -59,6 +59,32 @@ public readonly record struct SwapProviderLimits(long MinSats, long MaxSats, int return weighted.Count > 0 ? weighted : [(SwapProvider.Loop, 1)]; } + /// + /// The Lightning nodes of the providers swaps out through (see ), + /// by pubkey, from LOOP_NODE_PUBKEYS, FORTYSWAP_NODE_PUBKEYS and SPARK_NODE_PUBKEYS. + /// + public static IReadOnlyDictionary NodesSwappedThrough(Node node) + { + var providerByPubKey = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var (provider, _) in Weighted(node)) + { + foreach (var pubKey in NodePubKeysOf(provider)) + { + providerByPubKey.TryAdd(pubKey, provider); + } + } + + return providerByPubKey; + } + + private static IReadOnlySet NodePubKeysOf(SwapProvider provider) => provider switch + { + SwapProvider.Loop => Constants.LOOP_NODE_PUBKEYS, + SwapProvider.FortySwap => Constants.FORTYSWAP_NODE_PUBKEYS, + SwapProvider.Spark => Constants.SPARK_NODE_PUBKEYS, + _ => throw new ArgumentOutOfRangeException(nameof(provider), provider, "Unknown swap provider") + }; + /// 's max routing fee ratio for 's swaps. public static decimal MaxRoutingFeeRatioFor(Node node, SwapProvider provider) => provider switch { diff --git a/test/NodeGuard.Tests/E2E/AutoChannelOpenE2ETests.cs b/test/NodeGuard.Tests/E2E/AutoChannelOpenE2ETests.cs index 22dd1cf53..98a845adc 100644 --- a/test/NodeGuard.Tests/E2E/AutoChannelOpenE2ETests.cs +++ b/test/NodeGuard.Tests/E2E/AutoChannelOpenE2ETests.cs @@ -34,6 +34,7 @@ namespace NodeGuard.Tests.E2E; /// then in Auto mode (request created, channel opened at the price bob already charges carol). /// Two more scenarios cover reserved peers: one with no channel and no evidence opens at the fee set for it, /// and one still opens when its share is all the budget has left, while the earning peer is skipped. +/// A last scenario makes carol a swap provider bob swaps out through, which takes the recommendation away. /// Order-agnostic and self-resetting; serial with the other e2e classes via [Collection("E2E")]. /// [Trait("Category", "E2E")] @@ -75,30 +76,17 @@ public async Task AutoChannelOpen_EarningRouteRunsOutOfOutbound_RecommendsThenOp { var scenario = await LoadScenarioAsync(); var (client, headers, rpc) = (scenario.Client, scenario.Headers, scenario.Rpc); - var (alice, bob, carol) = (scenario.Alice, scenario.Bob, scenario.Carol); + var (bob, carol) = (scenario.Bob, scenario.Carol); var walletId = int.Parse(Env("E2E_HOT_WALLET_ID", "3")); try { - await ResetAutoChannelOpenAsync(scenario.BobNodeId, dynamicFees: false); - // Before any payment, so this scenario's forwards are the only ones the job can see - await ResetRoutingEngineStateAsync(); - - var aliceToBobScid = await ResolveAliceToBobAsync(client, headers, rpc, alice, bob.PubKey); - _output.WriteLine($"[setup] alice→bob first hop scid {aliceToBobScid}"); - - var earnedFeeSats = await EarnOnBobToCarolAsync(alice, bob, carol, aliceToBobScid); - await DrainUsableLocalAsync(bob, carol); - await SendRefusedPaymentsAsync(alice, bob, carol, aliceToBobScid); + var earnedFeeSats = await ArrangeShortEarningRouteAsync(scenario); var carolChannels = await bob.ChannelsToAsync(carol.PubKey); var carolScids = carolChannels.Select(c => c.ChanId).ToHashSet(); var dearest = await DearestPolicyAsync(bob, carolScids); - // Earlier scenarios leave unconfirmed change in the hot wallet; the wallet check only counts - // confirmed coins - await MineAsync(rpc, 6); - // ── Recommendation mode: recorded, nothing opened ──────────────────────────────────── await EnableAsync(scenario.BobNodeId, walletId, AutoChannelOpenMode.Recommendation); var recommendation = await PollRecommendationAsync(scenario.BobNodeId, carol.PubKey, r => r.Status == ChannelOpenRecommendationStatus.Open, @@ -332,6 +320,43 @@ public async Task AutoChannelOpen_OnlyTheReservedShareLeft_SkipsTheEarningPeerAn } } + /// + /// The e2e NodeGuard lists carol as a 40swap node (FORTYSWAP_NODE_PUBKEYS, set by its entrypoint), which + /// only counts for a node that gives 40swap a weight. Carol qualifies and is recommended; bob then + /// gives 40swap the smallest weight and the next run expires the recommendation; with the weight back + /// at 0 carol is recommended again, so nothing but the weight took it away. + /// + [E2EFact, Trait("Speed", "Slow")] + public async Task AutoChannelOpen_PeerIsASwapProviderTheNodeSwapsOutThrough_GetsNoRecommendation() + { + var scenario = await LoadScenarioAsync(); + var walletId = int.Parse(Env("E2E_HOT_WALLET_ID", "3")); + + try + { + await ArrangeShortEarningRouteAsync(scenario); + + await EnableAsync(scenario.BobNodeId, walletId, AutoChannelOpenMode.Recommendation); + var recommended = await PollRecommendationAsync(scenario.BobNodeId, scenario.Carol.PubKey, r => r.Status == ChannelOpenRecommendationStatus.Open, + "AutoChannelOpenJob recommended carol while bob gives 40swap no weight"); + + await SetFortySwapWeightAsync(scenario.BobNodeId, 1); + var expired = await PollRecommendationAsync(scenario.BobNodeId, scenario.Carol.PubKey, r => r.Status == ChannelOpenRecommendationStatus.Expired, + "AutoChannelOpenJob expired carol's recommendation once bob swaps out through 40swap"); + expired.Id.Should().Be(recommended.Id, "the run that rejects carol writes no new row for her"); + expired.ChannelOperationRequestId.Should().BeNull("nothing was promoted"); + + await SetFortySwapWeightAsync(scenario.BobNodeId, 0); + var again = await PollRecommendationAsync(scenario.BobNodeId, scenario.Carol.PubKey, r => r.Status == ChannelOpenRecommendationStatus.Open, + "AutoChannelOpenJob recommended carol again with 40swap back at no weight"); + again.Id.Should().NotBe(expired.Id, "an expired recommendation is history, never reused"); + } + finally + { + await ResetAutoChannelOpenAsync(scenario.BobNodeId, dynamicFees: scenario.BobDynamicFees); + } + } + private sealed record Scenario( Nodeguard.NodeGuardService.NodeGuardServiceClient Client, Grpc.Core.Metadata Headers, @@ -369,6 +394,32 @@ private async Task LoadScenarioAsync() aliceRow.Id, bobRow.Id, carolNodeId, aliceRow.DynamicFeeManagementEnabled, bobRow.DynamicFeeManagementEnabled); } + /// + /// Leaves bob, with his channel opener off, everything the rule asks for toward carol: a route that + /// earned, no outbound left on it and fresh refusals. Returns the fee earned, in sats. + /// + private async Task ArrangeShortEarningRouteAsync(Scenario scenario) + { + var (alice, bob, carol) = (scenario.Alice, scenario.Bob, scenario.Carol); + + await ResetAutoChannelOpenAsync(scenario.BobNodeId, dynamicFees: false); + // Before any payment, so this scenario's forwards are the only ones the job can see + await ResetRoutingEngineStateAsync(); + + var aliceToBobScid = await ResolveAliceToBobAsync(scenario.Client, scenario.Headers, scenario.Rpc, alice, bob.PubKey); + _output.WriteLine($"[setup] alice→bob first hop scid {aliceToBobScid}"); + + var earnedFeeSats = await EarnOnBobToCarolAsync(alice, bob, carol, aliceToBobScid); + await DrainUsableLocalAsync(bob, carol); + await SendRefusedPaymentsAsync(alice, bob, carol, aliceToBobScid); + + // Earlier scenarios leave unconfirmed change in the hot wallet; the wallet check only counts + // confirmed coins + await MineAsync(scenario.Rpc, 6); + + return earnedFeeSats; + } + /// /// One settled alice→bob→carol forward, so the route has earned bob a fee. Refills bob's side from /// carol first if an earlier scenario left it too dry to carry the payment. Returns the fee in sats @@ -585,8 +636,11 @@ private async Task PollRecommendationAsync( async () => { await using var db = CreateDbContext(); + // The latest: every earlier row to the peer is history var row = await db.ChannelOpenRecommendations.AsNoTracking() - .FirstOrDefaultAsync(r => r.NodeId == nodeId && r.PeerPubKey == peerPubKey); + .Where(r => r.NodeId == nodeId && r.PeerPubKey == peerPubKey) + .OrderByDescending(r => r.Id) + .FirstOrDefaultAsync(); if (row != null) _output.WriteLine($"[recommendation] #{row.Id} status={row.Status} earned={row.EarnedFeeSats} refusals={row.Refusals} usable={row.UsableLocalSats}/{row.PeerCapacitySats} request={row.ChannelOperationRequestId}"); return row; @@ -598,6 +652,12 @@ private async Task PollRecommendationAsync( return recommendation!; } + private static async Task SetFortySwapWeightAsync(int nodeId, int weight) + { + await using var db = CreateDbContext(); + await db.Nodes.Where(n => n.Id == nodeId).ExecuteUpdateAsync(s => s.SetProperty(n => n.FortySwapWeight, weight)); + } + /// /// Switches a node's channel opener off and clears its recommendations and reserved peers — on the way in /// so an earlier run's Promoted row can't put a peer on cooldown, and on the way out so nothing opens under @@ -611,6 +671,8 @@ await db.Nodes .ExecuteUpdateAsync(s => s .SetProperty(n => n.AutoChannelOpenEnabled, false) .SetProperty(n => n.AutoChannelOpenMode, AutoChannelOpenMode.Recommendation) + // Carol is listed as a 40swap node: any weight would keep her from being recommended + .SetProperty(n => n.FortySwapWeight, 0) .SetProperty(n => n.DynamicFeeManagementEnabled, dynamicFees)); await db.ChannelOpenRecommendations.Where(r => r.NodeId == nodeId).ExecuteDeleteAsync(); await db.ReservedChannelOpenPeers.Where(r => r.NodeId == nodeId).ExecuteDeleteAsync(); diff --git a/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs b/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs index 9957f3062..ed999b1cc 100644 --- a/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs +++ b/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs @@ -564,6 +564,69 @@ public async Task Execute_AutoModeWithoutAutomaticSwapOut_PromotesWithoutReading _swapOutWarningService.Verify(x => x.LocalBalanceSatsAsync(It.IsAny()), Times.Never); } + // ── Swap providers ───────────────────────────────────────────────────────────────── + + /// Process-wide statics, like the switches in : set and restored around the run. + private async Task RunWithSwapProviderNodes(string[]? loop = null, string[]? fortySwap = null) + { + var (previousLoop, previousFortySwap) = (Constants.LOOP_NODE_PUBKEYS, Constants.FORTYSWAP_NODE_PUBKEYS); + Constants.LOOP_NODE_PUBKEYS = new HashSet(loop ?? []); + Constants.FORTYSWAP_NODE_PUBKEYS = new HashSet(fortySwap ?? []); + try + { + await Run(); + } + finally + { + (Constants.LOOP_NODE_PUBKEYS, Constants.FORTYSWAP_NODE_PUBKEYS) = (previousLoop, previousFortySwap); + } + } + + [Fact] + public async Task Execute_PeerIsAProviderTheNodeSwapsOutThrough_IsNotRecommended() + { + // The node's weights are the defaults: every swap goes through Loop. + ArrangeQualifyingPeer(secondPeer: true); + + await RunWithSwapProviderNodes(loop: [Peer]); + + VerifyRecorded(Times.Once()); + _recommendationRepository.Verify(x => x.Upsert(It.Is(r => r.PeerPubKey == SecondPeer)), Times.Once); + } + + [Fact] + public async Task Execute_PeerIsAProviderTheNodeDoesNotSwapOutThrough_IsRecommended() + { + ArrangeQualifyingPeer(); + + await RunWithSwapProviderNodes(fortySwap: [Peer]); + + _recommendationRepository.Verify(x => x.Upsert(It.Is(r => r.PeerPubKey == Peer)), Times.Once); + } + + [Fact] + public async Task Execute_PeerIsAProviderWithAnyWeight_IsNotRecommended() + { + var node = ArrangeQualifyingPeer(); + node.LoopSwapWeight = 99; + node.FortySwapWeight = 1; + + await RunWithSwapProviderNodes(fortySwap: [Peer]); + + VerifyRecorded(Times.Never()); + } + + [Fact] + public async Task Execute_ReservedPeerIsAProviderTheNodeSwapsOutThrough_IsNotRecommended() + { + ArrangeQualifyingPeer(reservedPct: 20); + + await RunWithSwapProviderNodes(loop: [ReservedPeer]); + + VerifyRecorded(Times.Once()); + _recommendationRepository.Verify(x => x.Upsert(It.Is(r => r.PeerPubKey == Peer)), Times.Once); + } + // ── Reserved peers ───────────────────────────────────────────────────────────────── [Fact] diff --git a/test/NodeGuard.Tests/Services/ChannelOpenInitiatorServiceTests.cs b/test/NodeGuard.Tests/Services/ChannelOpenInitiatorServiceTests.cs index 013dcbd02..cad40a502 100644 --- a/test/NodeGuard.Tests/Services/ChannelOpenInitiatorServiceTests.cs +++ b/test/NodeGuard.Tests/Services/ChannelOpenInitiatorServiceTests.cs @@ -48,9 +48,10 @@ private static PeerSnapshot Peer( LocalOutboundPolicy? policy = null, bool noPolicy = false, bool onCooldown = false, - bool reserved = false) + bool reserved = false, + SwapProvider? swapProvider = null) => new(pubKey, earnedFeeSats, 4_000_000, refusals, usableLocalSats, capacitySats, - noPolicy ? null : policy ?? new LocalOutboundPolicy(1_200, 1_000), onCooldown, reserved); + noPolicy ? null : policy ?? new LocalOutboundPolicy(1_200, 1_000), onCooldown, reserved, swapProvider); /// A reserved peer with none of the earning evidence, short of outbound. private static PeerSnapshot ReservedPeer( @@ -105,6 +106,19 @@ public void Evaluate_OutboundAtTheThreshold_IsRejected() public void Evaluate_OnCooldown_IsRejected() => Evaluate(Peer(onCooldown: true)).Plans.Should().BeEmpty(); + [Fact] + public void Evaluate_SwapProviderTheNodeSwapsOutThrough_IsRejected() + { + var result = Evaluate(Peer(swapProvider: SwapProvider.Loop)); + + result.Plans.Should().BeEmpty(); + result.Rejected.Should().ContainSingle().Which.Reason.Should().Contain("swap provider"); + } + + [Fact] + public void Evaluate_ReservedSwapProviderTheNodeSwapsOutThrough_IsRejected() + => Evaluate(ReservedPeer() with { SwapProvider = SwapProvider.Spark }).Plans.Should().BeEmpty(); + [Fact] public void Evaluate_NoOutboundPolicy_IsRejected() => Evaluate(Peer(noPolicy: true)).Plans.Should().BeEmpty(); diff --git a/test/NodeGuard.Tests/Services/SwapOutWarningServiceTests.cs b/test/NodeGuard.Tests/Services/SwapOutWarningServiceTests.cs index f7dcc569d..d69e41382 100644 --- a/test/NodeGuard.Tests/Services/SwapOutWarningServiceTests.cs +++ b/test/NodeGuard.Tests/Services/SwapOutWarningServiceTests.cs @@ -64,6 +64,9 @@ private void ArrangeNode(Node node, ulong localSats, ulong pendingOpenSats = 0) }); } + // In the culture the warning is written in, so the decimal separator matches on any machine. + private static string Btc(decimal btc) => $"{btc:f8} BTC"; + [Fact] public async Task AnOpenThatTakesTheBalanceOverTheThreshold_WarnsWithTheAmounts() { @@ -72,7 +75,7 @@ public async Task AnOpenThatTakesTheBalanceOverTheThreshold_WarnsWithTheAmounts( var warning = await BuildService().ForChannelOpenAsync(NodeId, 500_000); - warning.Should().Contain("alice").And.Contain("0.01450000 BTC").And.Contain("0.01000000 BTC").And.Contain("0.00450000 BTC"); + warning.Should().Contain("alice").And.Contain(Btc(0.0145m)).And.Contain(Btc(0.01m)).And.Contain(Btc(0.0045m)); } [Fact] @@ -83,7 +86,7 @@ public async Task AWarning_SaysTheThresholdThatWouldKeepTheOutboundEarning() var warning = await BuildService().ForChannelOpenAsync(NodeId, 500_000); - warning.Should().Contain("could earn routing fees").And.Contain("Balance Threshold to 0.01450000 BTC or more"); + warning.Should().Contain("could earn routing fees").And.Contain($"Balance Threshold to {Btc(0.0145m)} or more"); } [Fact] @@ -94,7 +97,7 @@ public async Task ChannelsStillOpening_CountTowardsTheBalance() var warning = await BuildService().ForChannelOpenAsync(NodeId, 500_000); - warning.Should().Contain("0.01450000 BTC"); + warning.Should().Contain(Btc(0.0145m)); } [Fact]