diff --git a/src/Helpers/LightningHelper.cs b/src/Helpers/LightningHelper.cs index 9ff273740..1867804c5 100644 --- a/src/Helpers/LightningHelper.cs +++ b/src/Helpers/LightningHelper.cs @@ -22,6 +22,7 @@ using Google.Protobuf; using NBitcoin; using NBXplorer; +using NBXplorer.DerivationStrategy; using NBXplorer.Models; namespace NodeGuard.Helpers @@ -220,6 +221,30 @@ public static async Task> SelectCoins(Wallet wallet, List sele .ToList(); } + /// + /// Biggest channel the coins can fund through a normal open: every coin in, the funding output + /// and a change output out, with the change kept at dust so the tx still relays. + /// + public static long MaxFundableChannelSats(DerivationStrategyBase derivationStrategy, List utxos, decimal feeRateSatPerVb) + { + if (utxos.Count == 0) + { + return 0; + } + + // Output values don't change the size, so the amounts here are placeholders + var builder = CurrentNetworkHelper.GetCurrentNetwork().CreateTransactionBuilder(); + var tx = builder.AddCoins(utxos.Select(u => u.AsCoin(derivationStrategy))) + .SendAll(new WitScriptId(uint256.Zero).ScriptPubKey) + .BuildTransaction(false); + tx.Outputs.Add(Money.Zero, utxos[0].ScriptPubKey); + + var totalSats = utxos.Sum(u => ((Money)u.Value).Satoshi); + var feeSats = builder.EstimateFees(tx, new FeeRate(feeRateSatPerVb)).Satoshi; + + return Math.Max(0, totalSats - feeSats - Constants.MINIMUM_UTXO_VALUE_SATS); + } + /// /// Returns the fee rate (sat/vb) for a tx, 4 is the value in regtest /// diff --git a/src/Jobs/AutoChannelOpenJob.cs b/src/Jobs/AutoChannelOpenJob.cs new file mode 100644 index 000000000..12e5d35eb --- /dev/null +++ b/src/Jobs/AutoChannelOpenJob.cs @@ -0,0 +1,367 @@ +/* + * NodeGuard + * Copyright (C) 2023 Elenpay + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see http://www.gnu.org/licenses/. + * + */ + +using NodeGuard.Data.Models; +using NodeGuard.Data.Repositories.Interfaces; +using NodeGuard.Helpers; +using NodeGuard.Services; +using Quartz; + +namespace NodeGuard.Jobs; + +/// +/// Opens a fixed-size channel to a peer whose route earned us fees but keeps running out of outbound. +/// Writes rows, and in +/// promotes them. Promotion removes the human *decision*, not the *signature*: a multisig wallet still +/// collects signatures through the normal approval flow. +/// +[DisallowConcurrentExecution] +public class AutoChannelOpenJob : IJob +{ + private readonly ILogger _logger; + private readonly INodeRepository _nodeRepository; + private readonly IForwardingHtlcEventRepository _forwardingHtlcEventRepository; + private readonly IChannelOpenRecommendationRepository _recommendationRepository; + private readonly IChannelOpenPromotionService _promotionService; + private readonly ILightningService _lightningService; + private readonly INBXplorerService _nbXplorerService; + private readonly IChannelOperationRequestRepository _channelOperationRequestRepository; + private readonly IAuditService _auditService; + private readonly ICoinSelectionService _coinSelectionService; + + public AutoChannelOpenJob( + ILogger logger, + INodeRepository nodeRepository, + IForwardingHtlcEventRepository forwardingHtlcEventRepository, + IChannelOpenRecommendationRepository recommendationRepository, + IChannelOpenPromotionService promotionService, + ILightningService lightningService, + INBXplorerService nbXplorerService, + IChannelOperationRequestRepository channelOperationRequestRepository, + IAuditService auditService, + ICoinSelectionService coinSelectionService) + { + _logger = logger; + _nodeRepository = nodeRepository; + _forwardingHtlcEventRepository = forwardingHtlcEventRepository; + _recommendationRepository = recommendationRepository; + _promotionService = promotionService; + _lightningService = lightningService; + _nbXplorerService = nbXplorerService; + _channelOperationRequestRepository = channelOperationRequestRepository; + _auditService = auditService; + _coinSelectionService = coinSelectionService; + } + + public async Task Execute(IJobExecutionContext context) + { + // Killing the routing engine must stop every actuator, most of all the one that spends on-chain. + if (!Constants.ROUTING_ENGINE_ENABLED || !Constants.AUTO_CHANNEL_OPEN_ENABLED) + { + return; + } + + _logger.LogInformation("Starting {JobName}...", nameof(AutoChannelOpenJob)); + + try + { + // HourFee is at or above the EconomyFee the funding tx is built at, so the wallet check errs safe. + var feeRate = await _nbXplorerService.GetFeesByType(MempoolRecommendedFeesType.HourFee); + if (feeRate == null) + { + _logger.LogWarning("{JobName}: no feerate available, skipping run", nameof(AutoChannelOpenJob)); + return; + } + + var nodes = await _nodeRepository.GetAllWithAutoChannelOpenEnabled(); + _logger.LogInformation("Found {Count} node(s) with automatic channel opening enabled", nodes.Count); + + foreach (var node in nodes) + { + try + { + await ProcessNode(node, feeRate.Value); + } + catch (Exception e) + { + _logger.LogError(e, "Error processing automatic channel opening for node {NodeName} ({NodePubKey})", + node.Name, node.PubKey); + } + } + } + catch (Exception e) + { + _logger.LogError(e, "Error in {JobName}", nameof(AutoChannelOpenJob)); + } + + _logger.LogInformation("{JobName} ended", nameof(AutoChannelOpenJob)); + } + + private async Task ProcessNode(Node node, decimal feeRate) + { + var now = DateTimeOffset.UtcNow; + + // Every run starts clean: the upsert below re-opens whatever still qualifies, so the panel is + // always this run's output and nothing lingers from an earlier one. + var expired = await _recommendationRepository.ExpireOpen(node.Id); + if (expired > 0) + { + _logger.LogInformation("Node {NodeName}: expired {Count} open recommendation(s) ahead of this run", + node.Name, expired); + } + + // 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); + if (unrealized > 0) + { + _logger.LogInformation("Node {NodeName}: {Count} promoted recommendation(s) whose channel never opened marked failed, releasing their peers from the cooldown", + node.Name, unrealized); + } + + if (node.AutoChannelOpenWalletId == null) + { + _logger.LogInformation("Node {NodeName}: no wallet set for automatic channel opening", node.Name); + return; + } + + if (node.AutoChannelOpenSizeSats is not > 0) + { + _logger.LogInformation("Node {NodeName}: no channel size set for automatic channel opening", node.Name); + return; + } + + var remainingBudget = await GetRemainingBudget(node, now); + if (remainingBudget <= 0) + { + _logger.LogInformation("Node {NodeName}: channel open budget exhausted", node.Name); + return; + } + + var peers = await BuildPeerSnapshots(node, now); + if (peers.Count == 0) + { + _logger.LogDebug("Node {NodeName}: no peer refused forwards in the shortage window", node.Name); + return; + } + + var walletSpendableSats = await GetWalletSpendableSats(node, feeRate); + var tunables = ChannelOpenInitiatorTunables.FromConstants(node, walletSpendableSats, remainingBudget); + var classification = ChannelOpenInitiatorService.Evaluate(peers, tunables); + + foreach (var rejection in classification.Rejected) + { + _logger.LogInformation("Node {NodeName}: no channel open to {Peer} — {Reason}", + node.Name, rejection.PeerPubKey, rejection.Reason); + } + + // Each plan was checked against the full remaining budget, so spend has to be tracked across the + // run — otherwise a per-run cap above 1 would commit the budget once per plan. + foreach (var plan in classification.Plans) + { + if (plan.SuggestedCapacitySats > remainingBudget) + { + _logger.LogInformation("Node {NodeName}: skipping a {Capacity} sats plan, only {Remaining} sats of budget left", + node.Name, plan.SuggestedCapacitySats, remainingBudget); + continue; + } + + if (await RecordAndMaybePromote(node, plan)) + { + remainingBudget -= plan.SuggestedCapacitySats; + } + } + } + + /// + /// One snapshot per peer that refused forwards in the shortage window. Every input is fetched once + /// for the whole node, never per channel. + /// + private async Task> BuildPeerSnapshots(Node node, DateTimeOffset now) + { + var lookbackSince = now.AddDays(-Constants.AUTO_CHANNEL_OPEN_LOOKBACK_DAYS); + var shortageSince = now.AddHours(-Constants.AUTO_CHANNEL_OPEN_SHORTAGE_HOURS); + + var refusalsTask = _forwardingHtlcEventRepository.GetInsufficientBalanceCountsByChannel(node.PubKey, shortageSince); + var feesTask = _forwardingHtlcEventRepository.GetEarnedFeesMsatByChannel(node.PubKey, lookbackSince); + var outTask = _forwardingHtlcEventRepository.GetOutgoingAmountsMsatByChannel(node.PubKey, lookbackSince); + var listChannelsTask = _lightningService.ListChannels(node); + var policyTask = _lightningService.GetLocalOutboundPoliciesAsync(node); + var lastDecisionTask = _recommendationRepository.GetLastDecisionByPeer(node.Id); + await Task.WhenAll(refusalsTask, feesTask, outTask, listChannelsTask, policyTask, lastDecisionTask); + + var refusalsByChanId = refusalsTask.Result; + if (refusalsByChanId.Count == 0) + { + return []; + } + + var listChannels = listChannelsTask.Result; + if (listChannels == null) + { + _logger.LogWarning("Node {NodeName}: could not list channels", node.Name); + return []; + } + + var feesByChanId = feesTask.Result; + var outByChanId = outTask.Result; + var policyByChanId = policyTask.Result; + var lastDecisionByPeer = lastDecisionTask.Result; + var cooldownCutoff = now.AddHours(-Constants.AUTO_CHANNEL_OPEN_PEER_COOLDOWN_HOURS); + + // Fees and refusals on channels that have since closed are dropped with them: only the peer's + // current channels map back to a pubkey. + return listChannels.Channels + .GroupBy(x => x.RemotePubkey) + .Select(peerChannels => (Peer: peerChannels.Key, Channels: peerChannels.ToList())) + .Where(x => x.Channels.Sum(c => refusalsByChanId.GetValueOrDefault(c.ChanId)) > 0) + .Select(x => new PeerSnapshot( + PeerPubKey: x.Peer, + EarnedFeeSats: x.Channels.Sum(c => feesByChanId.GetValueOrDefault(c.ChanId)) / 1000, + SettledOutSats: x.Channels.Sum(c => outByChanId.GetValueOrDefault(c.ChanId)) / 1000, + Refusals: x.Channels.Sum(c => refusalsByChanId.GetValueOrDefault(c.ChanId)), + // Usable, not raw: the reserve can never be forwarded, and on a drained channel it is + // most of what local_balance reports. + UsableLocalSats: x.Channels.Sum(c => Math.Max(0, c.LocalBalance - c.LocalChanReserveSat)), + CapacitySats: x.Channels.Sum(c => c.Capacity), + // The highest rate, with the base fee from that same channel rather than a mix. + OutboundPolicy: x.Channels + .Select(c => policyByChanId != null && policyByChanId.TryGetValue(c.ChanId, out var p) ? p : null) + .Where(p => p != null) + .MaxBy(p => p!.FeeRatePpm), + OnCooldown: lastDecisionByPeer.TryGetValue(x.Peer, out var last) && last > cooldownCutoff)) + .ToList(); + } + + /// + /// The biggest channel the wallet can fund from the coins coin selection would hand it, with the + /// funding fee already taken out. + /// + private async Task GetWalletSpendableSats(Node node, decimal feeRate) + { + var derivationStrategy = node.AutoChannelOpenWallet?.GetDerivationStrategy(); + if (derivationStrategy == null) + { + return 0; + } + + var utxos = await _coinSelectionService.GetAvailableUTXOsAsync(derivationStrategy); + + return LightningHelper.MaxFundableChannelSats(derivationStrategy, utxos, feeRate); + } + + /// + /// Rolls the budget period over and persists it when elapsed — a Get that writes. + /// + private async Task GetRemainingBudget(Node node, DateTimeOffset now) + { + var budgetSats = node.AutoChannelOpenBudgetSats ?? 0; + if (budgetSats <= 0) + { + _logger.LogInformation("Node {NodeName}: no channel open budget configured; skipping", node.Name); + return 0; + } + + var refreshInterval = node.AutoChannelOpenBudgetRefreshInterval + ?? TimeSpan.FromHours(Constants.AUTO_CHANNEL_OPEN_DEFAULT_BUDGET_REFRESH_HOURS); + if (!node.AutoChannelOpenBudgetStartDatetime.HasValue || + now - node.AutoChannelOpenBudgetStartDatetime.Value >= refreshInterval) + { + _logger.LogInformation("Refreshing channel open budget for node {NodeName}", node.Name); + node.AutoChannelOpenBudgetStartDatetime = now; + _nodeRepository.Update(node); + } + + var periodStart = node.AutoChannelOpenBudgetStartDatetime ?? now; + var committed = await _channelOperationRequestRepository.GetOpenSatsCommittedSince(node.Id, periodStart); + + return budgetSats - committed; + } + + /// + /// Returns true only when the run has committed capital, so the caller can decrement its budget. + /// + private async Task RecordAndMaybePromote(Node node, ChannelOpenRecommendation plan) + { + plan.NodeId = node.Id; + + var (recommendation, error) = await _recommendationRepository.Upsert(plan); + if (recommendation == null) + { + _logger.LogError("Node {NodeName}: could not record channel open recommendation — {Error}", node.Name, error); + return false; + } + + // Checked before the log and the audit entry: an untouched row means nothing was recorded, and + // claiming a creation that did not happen would repeat every run until the open resolves. + if (recommendation.Status != ChannelOpenRecommendationStatus.Open) + { + _logger.LogDebug("Node {NodeName}: skipping {Peer}, a channel open to it is still in progress", + node.Name, plan.PeerPubKey); + + return false; + } + + _logger.LogInformation( + "Node {NodeName}: recommending a {Capacity} sats channel to {Peer} — earned {EarnedFee} sats in {LookbackDays}d, {Refusals} refused forward(s) in {ShortageHours}h, {UsableLocal}/{PeerCapacity} sats usable outbound", + node.Name, plan.SuggestedCapacitySats, plan.PeerPubKey, + plan.EarnedFeeSats, Constants.AUTO_CHANNEL_OPEN_LOOKBACK_DAYS, + plan.Refusals, Constants.AUTO_CHANNEL_OPEN_SHORTAGE_HOURS, + plan.UsableLocalSats, plan.PeerCapacitySats); + + await _auditService.LogAsync( + AuditActionType.Create, + AuditEventType.Success, + AuditObjectType.ChannelOpenRecommendation, + recommendation.Id.ToString(), + new + { + NodeId = node.Id, + plan.PeerPubKey, + plan.SuggestedCapacitySats, + plan.EarnedFeeSats, + plan.Refusals, + plan.UsableLocalSats, + plan.PeerCapacitySats, + Description = $"Channel open recommended to {plan.PeerPubKey} for {plan.SuggestedCapacitySats} sats" + }); + + if (node.AutoChannelOpenMode != AutoChannelOpenMode.Auto) + { + return false; + } + + if (node.RoutingEngineDryRun) + { + _logger.LogInformation("Node {NodeName}: dry run, not promoting the recommendation", node.Name); + return false; + } + + var (promoted, promotionError) = await _promotionService.Promote( + recommendation.Id, recommendation.SuggestedCapacitySats, userId: null); + + if (!promoted) + { + _logger.LogError("Node {NodeName}: could not promote recommendation {Id} — {Error}", + node.Name, recommendation.Id, promotionError); + } + + return promoted; + } +} diff --git a/src/Program.cs b/src/Program.cs index 75891a71c..18c0bdeb4 100644 --- a/src/Program.cs +++ b/src/Program.cs @@ -130,6 +130,7 @@ public static async Task Main(string[] args) builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); + builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); @@ -148,6 +149,7 @@ public static async Task Main(string[] args) builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); + builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); @@ -376,6 +378,23 @@ void ScheduleRoutingJob(SimpleScheduleBuilder sb, int minutes) opts.StartAt(DateBuilder.FutureDate(Constants.ROUTING_ENGINE_ACTUATOR_OFFSET_MINUTES, IntervalUnit.Minute)); }); + //Auto Channel Open Job (demand-driven capacity, own cadence) + q.AddJob(opts => + { + opts.DisallowConcurrentExecution(); + opts.WithIdentity(nameof(AutoChannelOpenJob)); + }); + + q.AddTrigger(opts => + { + // No offset: unlike the fee and rebalance actuators this job reads HTLC events and + // live LND state, never the routing state TargetRatioReevaluationJob writes. + opts.ForJob(nameof(AutoChannelOpenJob)) + .WithIdentity($"{nameof(AutoChannelOpenJob)}Trigger") + .StartNow() + .WithSimpleSchedule(sb => ScheduleRoutingJob(sb, Constants.AUTO_CHANNEL_OPEN_JOB_INTERVAL_MINUTES)); + }); + //Monitor Withdrawals Job q.AddJob(opts => { diff --git a/src/Services/ChannelOpenInitiatorService.cs b/src/Services/ChannelOpenInitiatorService.cs new file mode 100644 index 000000000..94860241b --- /dev/null +++ b/src/Services/ChannelOpenInitiatorService.cs @@ -0,0 +1,163 @@ +/* + * NodeGuard + * Copyright (C) 2023 Elenpay + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see http://www.gnu.org/licenses/. + * + */ + +using NodeGuard.Data.Models; +using NodeGuard.Helpers; + +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. +/// +public record PeerSnapshot( + string PeerPubKey, + long EarnedFeeSats, + long SettledOutSats, + int Refusals, + long UsableLocalSats, + long CapacitySats, + LocalOutboundPolicy? OutboundPolicy, + bool OnCooldown); + +public record ChannelOpenInitiatorTunables( + long MinEarnedFeeSats, + int MinRefusals, + int LowOutboundPct, + long SizeSats, + long WalletSpendableSats, + long RemainingBudgetSats, + int MaxPlansPerRun) +{ + public static ChannelOpenInitiatorTunables FromConstants( + Node node, + long walletSpendableSats, + long remainingBudgetSats) => new( + MinEarnedFeeSats: Constants.AUTO_CHANNEL_OPEN_MIN_EARNED_FEE_SATS, + MinRefusals: Constants.AUTO_CHANNEL_OPEN_MIN_REFUSALS, + LowOutboundPct: Constants.AUTO_CHANNEL_OPEN_LOW_OUTBOUND_PCT, + SizeSats: node.AutoChannelOpenSizeSats ?? 0, + WalletSpendableSats: walletSpendableSats, + RemainingBudgetSats: remainingBudgetSats, + MaxPlansPerRun: Constants.AUTO_CHANNEL_OPEN_MAX_PLANS_PER_RUN); +} + +public record ChannelOpenRejection(string PeerPubKey, string Reason); + +public record ChannelOpenClassification( + IReadOnlyList Plans, + IReadOnlyList Rejected); + +/// +/// 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. +/// +public static class ChannelOpenInitiatorService +{ + public static ChannelOpenClassification Evaluate( + IReadOnlyList peers, + ChannelOpenInitiatorTunables t) + { + var plans = new List(); + var rejected = new List(); + var now = DateTimeOffset.UtcNow; + + foreach (var peer in peers.OrderByDescending(x => x.EarnedFeeSats)) + { + var reason = Reject(peer, t); + if (reason != null) + { + rejected.Add(new ChannelOpenRejection(peer.PeerPubKey, reason)); + continue; + } + + if (plans.Count >= t.MaxPlansPerRun) + { + rejected.Add(new ChannelOpenRejection(peer.PeerPubKey, + $"qualifies, but the run already has {t.MaxPlansPerRun} plan(s)")); + continue; + } + + plans.Add(new ChannelOpenRecommendation + { + PeerPubKey = peer.PeerPubKey, + EarnedFeeSats = peer.EarnedFeeSats, + SettledOutSats = peer.SettledOutSats, + Refusals = peer.Refusals, + UsableLocalSats = peer.UsableLocalSats, + PeerCapacitySats = peer.CapacitySats, + SuggestedCapacitySats = t.SizeSats, + InheritedFeeRatePpm = peer.OutboundPolicy!.FeeRatePpm, + InheritedBaseFeeMsat = peer.OutboundPolicy.BaseFeeMsat, + Status = ChannelOpenRecommendationStatus.Open, + LastEvidenceAt = now + }); + } + + return new ChannelOpenClassification(plans, rejected); + } + + private static string? Reject(PeerSnapshot peer, ChannelOpenInitiatorTunables t) + { + if (peer.OnCooldown) + { + return "on cooldown after a recent promotion or dismissal"; + } + + // Without it the channel can't be priced: at the global default it would undercut what we + // already charge this peer. + if (peer.OutboundPolicy == null) + { + return "no outbound fee policy reported for any channel to the peer"; + } + + if (peer.EarnedFeeSats < t.MinEarnedFeeSats) + { + return $"earned {peer.EarnedFeeSats} sats, below the {t.MinEarnedFeeSats} sats minimum"; + } + + if (peer.Refusals < t.MinRefusals) + { + return $"{peer.Refusals} refused forward(s), below the {t.MinRefusals} minimum"; + } + + // The refusals are history; a rebalance or a settled HTLC may have refilled the peer since. + if (peer.UsableLocalSats * 100 >= peer.CapacitySats * t.LowOutboundPct) + { + return $"{peer.UsableLocalSats} of {peer.CapacitySats} sats usable outbound, not below {t.LowOutboundPct}%"; + } + + if (t.SizeSats <= 0) + { + return "the node has no channel size configured"; + } + + if (t.SizeSats > t.WalletSpendableSats) + { + return $"the funding wallet can fund at most {t.WalletSpendableSats} sats, below the {t.SizeSats} sats size"; + } + + if (t.SizeSats > t.RemainingBudgetSats) + { + return $"{t.RemainingBudgetSats} sats of budget left, below the {t.SizeSats} sats size"; + } + + return null; + } +} diff --git a/src/Services/ChannelOpenPromotionService.cs b/src/Services/ChannelOpenPromotionService.cs new file mode 100644 index 000000000..67e6e66cc --- /dev/null +++ b/src/Services/ChannelOpenPromotionService.cs @@ -0,0 +1,315 @@ +/* + * NodeGuard + * Copyright (C) 2023 Elenpay + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see http://www.gnu.org/licenses/. + * + */ + +using NBitcoin; +using NodeGuard.Data.Models; +using NodeGuard.Data.Repositories.Interfaces; +using NodeGuard.Helpers; +using NodeGuard.Jobs; +using Quartz; + +namespace NodeGuard.Services; + +public interface IChannelOpenPromotionService +{ + /// + /// Capacity may differ from what was suggested. The request still follows the normal approval and + /// signing path — promotion removes the decision, never a signature. + /// + Task<(bool, string?)> Promote(int recommendationId, long capacitySats, string? userId); + + Task<(bool, string?)> Dismiss(int recommendationId, string reason, string? userId); +} + +public class ChannelOpenPromotionService : IChannelOpenPromotionService +{ + private readonly ILogger _logger; + private readonly IChannelOpenRecommendationRepository _recommendationRepository; + private readonly IChannelOperationRequestRepository _channelOperationRequestRepository; + private readonly INodeRepository _nodeRepository; + private readonly IWalletRepository _walletRepository; + private readonly ILightningService _lightningService; + private readonly ISchedulerFactory _schedulerFactory; + private readonly IAuditService _auditService; + + public ChannelOpenPromotionService( + ILogger logger, + IChannelOpenRecommendationRepository recommendationRepository, + IChannelOperationRequestRepository channelOperationRequestRepository, + INodeRepository nodeRepository, + IWalletRepository walletRepository, + ILightningService lightningService, + ISchedulerFactory schedulerFactory, + IAuditService auditService) + { + _logger = logger; + _recommendationRepository = recommendationRepository; + _channelOperationRequestRepository = channelOperationRequestRepository; + _nodeRepository = nodeRepository; + _walletRepository = walletRepository; + _lightningService = lightningService; + _schedulerFactory = schedulerFactory; + _auditService = auditService; + } + + public async Task<(bool, string?)> Promote(int recommendationId, long capacitySats, string? userId) + { + var (recommendation, loadError) = await LoadOpen(recommendationId, "promoted"); + if (recommendation == null) + { + return (false, loadError); + } + + // GetById includes the Node, and the FK is required, so it is always populated. + var node = recommendation.Node; + if (node == null) + { + return (false, "Source node not found"); + } + + if (!node.AutoChannelOpenWalletId.HasValue) + { + return (false, "The node has no funding wallet configured for channel opens"); + } + + if (capacitySats < Constants.MINIMUM_CHANNEL_CAPACITY_SATS) + { + return (false, $"Capacity must be greater than {Constants.MINIMUM_CHANNEL_CAPACITY_SATS} sats"); + } + + ChannelOperationRequest? promotedRequest = null; + + try + { + // The peer is not a managed node, so it may not have a row yet. + var destNode = await _nodeRepository.GetOrCreateByPubKey(recommendation.PeerPubKey, _lightningService); + + // A second channel to this peer arrives full, so at the global default it would be the + // 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 null or < 0) + { + return (false, $"Recommendation {recommendationId} carries no inherited fee policy, so there is no price to open at — it predates fee capture and will be replaced on the next run"); + } + + var request = new ChannelOperationRequest + { + SatsAmount = capacitySats, + AmountCryptoUnit = MoneyUnit.Satoshi, + Description = BuildDescription(recommendation), + Status = ChannelOperationRequestStatus.Pending, + RequestType = OperationRequestType.Open, + WalletId = node.AutoChannelOpenWalletId, + SourceNodeId = node.Id, + DestNodeId = destNode.Id, + UserId = userId, + IsChannelPrivate = false, + MempoolRecommendedFeesType = MempoolRecommendedFeesType.EconomyFee, + InitialChannelBaseFeeMsat = recommendation.InheritedBaseFeeMsat, + InitialChannelFeeRatePpm = recommendation.InheritedFeeRatePpm + }; + + var (added, addError) = await _channelOperationRequestRepository.AddAsync(request); + if (!added) + { + _logger.LogError("Could not create the channel operation request for recommendation {Id}: {Error}", + recommendationId, addError); + return (false, addError); + } + + recommendation.Status = ChannelOpenRecommendationStatus.Promoted; + recommendation.ChannelOperationRequestId = request.Id; + + var (updated, updateError) = await _recommendationRepository.UpdateIfStatus(recommendation, ChannelOpenRecommendationStatus.Open); + if (!updated) + { + _logger.LogError("Channel operation request {RequestId} was created but recommendation {Id} could not be marked promoted: {Error}", + request.Id, recommendationId, updateError); + + // Nothing points at it now, so left Pending it could still be signed or sit on the budget. + CloseRequest(request, ChannelOperationRequestStatus.Cancelled, + ChannelStatusLog.Info("Cancelled: the recommendation was no longer open when this request was created")); + + return (false, updateError); + } + + promotedRequest = request; + + await _auditService.LogAsync( + AuditActionType.Create, + AuditEventType.Success, + AuditObjectType.ChannelOperationRequest, + request.Id.ToString(), + new + { + RequestId = request.Id, + RecommendationId = recommendationId, + SuggestedCapacitySats = recommendation.SuggestedCapacitySats, + ApprovedCapacitySats = capacitySats, + PeerPubKey = recommendation.PeerPubKey, + InitialChannelBaseFeeMsat = recommendation.InheritedBaseFeeMsat, + InitialChannelFeeRatePpm = recommendation.InheritedFeeRatePpm, + Description = $"Channel open request created from recommendation {recommendationId} " + + $"({capacitySats} sats, suggested {recommendation.SuggestedCapacitySats} sats, " + + $"opening at {recommendation.InheritedFeeRatePpm} ppm / {recommendation.InheritedBaseFeeMsat} msat, " + + $"the most we already charge this peer)" + }); + + _logger.LogInformation( + "Promoted channel open recommendation {Id} to request {RequestId}: {Capacity} sats to {Peer} (suggested {Suggested})", + recommendationId, request.Id, capacitySats, recommendation.PeerPubKey, recommendation.SuggestedCapacitySats); + + return await DispatchIfNoSignaturesNeeded(request, node.AutoChannelOpenWalletId.Value); + } + catch (Exception e) + { + _logger.LogError(e, "Error promoting channel open recommendation {Id}", recommendationId); + + // Left Pending it would never be dispatched, and would hold the peer, the budget and its coins. + if (promotedRequest != null) + { + CloseRequest(promotedRequest, ChannelOperationRequestStatus.Failed, + ChannelStatusLog.Error("Could not dispatch the channel open")); + } + + return (false, e.Message); + } + } + + private void CloseRequest(ChannelOperationRequest request, ChannelOperationRequestStatus status, ChannelStatusLog statusLog) + { + try + { + request.Status = status; + request.StatusLogs.Add(statusLog); + var (updated, error) = _channelOperationRequestRepository.Update(request); + if (!updated) + { + _logger.LogError("Could not mark channel open request {RequestId} as {Status}: {Error}", request.Id, status, error); + } + } + catch (Exception e) + { + _logger.LogError(e, "Could not mark channel open request {RequestId} as {Status}", request.Id, status); + } + } + + /// + /// Without this a promoted hot-wallet request dead-ends: Pending with no template, and its only UI + /// action opens an external-signer modal a hot wallet has no signer for. + /// + private async Task<(bool, string?)> DispatchIfNoSignaturesNeeded(ChannelOperationRequest request, int walletId) + { + var wallet = await _walletRepository.GetById(walletId); + if (wallet is not { IsHotWallet: true }) + { + // Multisig / watch-only: leave it Pending for the signers, which is the intended flow. + return (true, null); + } + + var (templatePsbt, noUtxosAvailable) = await _lightningService.GenerateTemplatePSBT(request); + if (templatePsbt == null) + { + var reason = noUtxosAvailable + ? "No UTXOs available in the funding wallet" + : "Could not generate the template PSBT"; + + request.Status = ChannelOperationRequestStatus.Failed; + request.StatusLogs.Add(ChannelStatusLog.Error(reason)); + _channelOperationRequestRepository.Update(request); + _logger.LogError("Channel open request {RequestId} failed before dispatch: {Reason}", request.Id, reason); + + return (false, reason); + } + + var persisted = await _channelOperationRequestRepository.GetById(request.Id); + if (persisted is not { AreAllRequiredHumanSignaturesCollected: true }) + { + // Nothing broken — the wallet simply still needs signatures. Leave it for them. + return (true, null); + } + + var map = new JobDataMap(); + map.Put("openRequestId", request.Id); + var retryList = RetriableJob.ParseRetryListFromString(Constants.JOB_RETRY_INTERVAL_LIST_IN_MINUTES); + var job = RetriableJob.Create(map, request.Id.ToString(), retryList); + + var scheduler = await _schedulerFactory.GetScheduler(); + await scheduler.ScheduleJob(job.Job, job.Trigger); + + _logger.LogInformation("Scheduled ChannelOpenJob for hot-wallet request {RequestId}", request.Id); + + return (true, null); + } + + public async Task<(bool, string?)> Dismiss(int recommendationId, string reason, string? userId) + { + var (recommendation, loadError) = await LoadOpen(recommendationId, "dismissed"); + if (recommendation == null) + { + return (false, loadError); + } + + recommendation.Status = ChannelOpenRecommendationStatus.Dismissed; + recommendation.DismissReason = reason; + + var (updated, error) = await _recommendationRepository.UpdateIfStatus(recommendation, ChannelOpenRecommendationStatus.Open); + if (!updated) + { + return (false, error); + } + + await _auditService.LogAsync( + AuditActionType.Reject, + AuditEventType.Success, + AuditObjectType.ChannelOpenRecommendation, + recommendationId.ToString(), + new + { + RecommendationId = recommendationId, + PeerPubKey = recommendation.PeerPubKey, + Reason = reason, + Description = $"Channel open recommendation {recommendationId} dismissed: {reason}" + }); + + return (true, null); + } + + private async Task<(ChannelOpenRecommendation?, string?)> LoadOpen(int recommendationId, string verb) + { + var recommendation = await _recommendationRepository.GetById(recommendationId); + if (recommendation == null) + { + return (null, "Recommendation not found"); + } + + return recommendation.Status == ChannelOpenRecommendationStatus.Open + ? (recommendation, null) + : (null, $"Recommendation is {recommendation.Status}, only Open ones can be {verb}"); + } + + /// + /// Summarised onto the request so an approver sees why it exists without leaving that page. + /// + private static string BuildDescription(ChannelOpenRecommendation r) => + $"Auto channel open: earned {r.EarnedFeeSats} sats in fees over {r.SettledOutSats} sats routed " + + $"in {Constants.AUTO_CHANNEL_OPEN_LOOKBACK_DAYS}d, {r.Refusals} forward(s) refused for lack of outbound " + + $"in {Constants.AUTO_CHANNEL_OPEN_SHORTAGE_HOURS}h, {r.UsableLocalSats} of {r.PeerCapacitySats} sats usable outbound."; +} diff --git a/src/Services/LightningService.cs b/src/Services/LightningService.cs index ed9ebed19..3ae2c286f 100644 --- a/src/Services/LightningService.cs +++ b/src/Services/LightningService.cs @@ -58,6 +58,12 @@ public enum MaxHtlcSyncResult Skipped = 2, } + /// + /// Our own side's advertised policy on one channel, as LND's FeeReport states it. A rate without + /// its base fee cannot reproduce a policy, so the two travel together. + /// + public record LocalOutboundPolicy(long FeeRatePpm, long BaseFeeMsat); + /// /// Service to interact with LND /// @@ -232,6 +238,14 @@ Task SendPaymentV2Async(Node node, string paymentRequest, long amountSa /// Task?> GetLocalOutboundFeeRatesPpmAsync(Node node); + /// + /// Local-outbound policy — base fee and rate together — for every channel on the node, keyed + /// by LND chan_id. Same call and same null contract as + /// ; callers wanting to reproduce a policy need + /// the pair, because a rate without its base fee is not one. + /// + Task?> GetLocalOutboundPoliciesAsync(Node node); + /// /// Sets the channel fee policy for a given channel identified by its chanPoint /// @@ -1277,8 +1291,8 @@ await _coinSelectionService.GetTxInputCoins(availableUTXOs, channelOperationRequ { _logger.LogError( "Cannot generate base template PSBT for {Visibility} channel operation request: {RequestId}, no UTXOs found for the wallet: {WalletId}", - channelOperationRequest.Id, channelOperationRequest.IsChannelPrivate ? "private" : "public", + channelOperationRequest.Id, channelOperationRequest.WalletId); return (null, true); //true means no UTXOS @@ -1915,6 +1929,21 @@ public async Task SendPaymentV2Async(Node node, string paymentRequest, return byChanId; } + public async Task?> GetLocalOutboundPoliciesAsync(Node node) + { + var report = await _lightningClientService.FeeReport(node); + if (report == null) return null; + + // Same last-wins indexer rationale as GetLocalOutboundFeeRatesPpmAsync. + var byChanId = new Dictionary(report.ChannelFees.Count); + foreach (var fee in report.ChannelFees) + { + byChanId[fee.ChanId] = new LocalOutboundPolicy(fee.FeePerMil, fee.BaseFeeMsat); + } + + return byChanId; + } + public async Task GetLocalOutboundFeeRatePpmByPeerAsync(Node node, string peerPubkey) { if (string.IsNullOrEmpty(peerPubkey)) return null; diff --git a/test/NodeGuard.Tests/Helpers/LightningHelperTests.cs b/test/NodeGuard.Tests/Helpers/LightningHelperTests.cs index 3d704e60b..c530dc485 100644 --- a/test/NodeGuard.Tests/Helpers/LightningHelperTests.cs +++ b/test/NodeGuard.Tests/Helpers/LightningHelperTests.cs @@ -166,5 +166,64 @@ public void AddDerivationData_SinglesigSucceeds() var psbt = PSBT.Parse( "cHNidP8BAIkBAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////wD/////AhAnAAAAAAAAIgAgPHfzrZk7L68p0NnijKzJFlfQcBGipD0uqora6TGiimLwvAtUAgAAACIAID2j1mgUIE8RzjFXzH6V9tW5a6FHvCgHesNoC0XpRbogAAAAAE8BBDWHzwN9uUaNAAAAAYPR/OiA1LbTzxbLPvbXvtAwckIG3g+0T1zblR/ZodaiA5zBFsigPpL8htN/KJ/Ph8SPvQA/K+mSNXTSA0hgvPNuEO0CEMgwAACAAQAAgAEAAAAAAQEfAOQLVAIAAAAWABTpOvUBMqNMfl7P81etji6x4fXrMyIGA3uD9HVjgF5E+eQhHp+Na6femVYpc4bCA4DmimehAdWcGO0CEMgwAACAAQAAgAEAAAAAAAAAAAAAAAAAAA==", network); result.Should().BeEquivalentTo(psbt); } + + // ── MaxFundableChannelSats ──────────────────────────────────────────────────── + + private static long MaxChannel(Wallet wallet, params long[] coinSats) => + LightningHelper.MaxFundableChannelSats( + wallet.GetDerivationStrategy()!, + coinSats.Select((sats, i) => TestUtxos.Spendable(wallet, (uint)i, sats)).ToList(), + 10m); + + [Fact] + public void MaxFundableChannelSats_SingleSig_LeavesTheFeeAndADustChange() + { + // (11 vB header + 2 × 68 vB P2WPKH in + 43 vB funding + 31 vB P2WPKH change) × 10 sat/vB = 2,210 + MaxChannel(CreateWallet.SingleSig(CreateWallet.CreateInternalWallet()), 6_000_000, 4_000_000) + .Should().Be(10_000_000 - 2_210 - 546); + } + + [Fact] + public void MaxFundableChannelSats_Multisig_LeavesTheFeeAndADustChange() + { + // (11 vB header + 2 × 105 vB 2-of-3 P2WSH in + 43 vB funding + 43 vB P2WSH change) × 10 sat/vB = 3,070 + MaxChannel(CreateWallet.MultiSig(CreateWallet.CreateInternalWallet()), 6_000_000, 4_000_000) + .Should().Be(10_000_000 - 3_070 - 546); + } + + [Theory] + // Same rate as the clamp, and the usual case of the open's EconomyFee coming in under HourFee + [InlineData(10, 546)] + [InlineData(4, 546 + 221 * 6)] + public void MaxFundableChannelSats_OpenedAtTheLimit_LeavesChangeAboveDust(int openFeeRate, long expectedChange) + { + var wallet = CreateWallet.SingleSig(CreateWallet.CreateInternalWallet()); + var derivationStrategy = wallet.GetDerivationStrategy()!; + var utxos = new List { TestUtxos.Spendable(wallet, 0, 6_000_000), TestUtxos.Spendable(wallet, 1, 4_000_000) }; + var capacity = LightningHelper.MaxFundableChannelSats(derivationStrategy, utxos, 10m); + + // The funded PSBT ChannelOpenJob gets back from LND: every coin in, the funding output and change out + var psbt = Network.RegTest.CreateTransactionBuilder() + .AddCoins(utxos.Select(u => u.AsCoin(derivationStrategy))) + .Send(new WitScriptId(uint256.Zero).ScriptPubKey, Money.Satoshis(capacity)) + .SetChange(utxos[0].ScriptPubKey) + .SendFees(Money.Zero) + .BuildPSBT(false); + + // LightningService.OpenChannel's change fix: totalIn − amount − vsize × feeRate, throwing below zero + psbt.TryGetVirtualSize(out var vsize).Should().BeTrue(); + var change = 10_000_000 - capacity - vsize * openFeeRate; + + psbt.Inputs.Should().HaveCount(2, "every coin funds the channel"); + change.Should().Be(expectedChange); + change.Should().BeGreaterThanOrEqualTo(Constants.MINIMUM_UTXO_VALUE_SATS, "a dust change output would not relay"); + } + + [Fact] + public void MaxFundableChannelSats_CoinsCannotCoverFeeAndChange_IsZero() + { + // 153 vB × 10 sat/vB + 546 sats of change = 2,076 against a 2,000 sat coin + MaxChannel(CreateWallet.SingleSig(CreateWallet.CreateInternalWallet()), 2_000).Should().Be(0); + } } } \ No newline at end of file diff --git a/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs b/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs new file mode 100644 index 000000000..09c662a92 --- /dev/null +++ b/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs @@ -0,0 +1,455 @@ +/* + * NodeGuard + * Copyright (C) 2023 Elenpay + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see http://www.gnu.org/licenses/. + * + */ + +using FluentAssertions; +using Microsoft.Extensions.Logging; +using NBXplorer.DerivationStrategy; +using NodeGuard.Data.Models; +using NodeGuard.Data.Repositories.Interfaces; +using NodeGuard.Helpers; +using NodeGuard.Services; +using NodeGuard.TestHelpers; +using NodeGuard.Tests.Jobs; +using Quartz; + +namespace NodeGuard.Jobs; + +/// +/// Covers the orchestration the pure planner cannot: the kill switches, how per-channel inputs roll up +/// to a peer, the expire-then-reopen lifecycle, and which of record / audit / promote runs per mode. +/// +[Collection("RoutingEngine")] +public class AutoChannelOpenJobTests +{ + private const string NodePubKey = "managedPubKey"; + private const string Peer = "03peer"; + private const int NodeId = 7; + private const ulong ChanId = 1001; + private const ulong SecondChanToPeer = 1003; + private const string SecondPeer = "03peer2"; + private const ulong SecondPeerChanId = 1002; + private const long SizeSats = 5_000_000; + + private readonly Mock> _logger = new(); + private readonly Mock _nodeRepository = new(); + private readonly Mock _forwardingHtlcEventRepository = new(); + private readonly Mock _recommendationRepository = new(); + private readonly Mock _promotionService = new(); + private readonly Mock _lightningService = new(); + private readonly Mock _nbXplorerService = new(); + private readonly Mock _channelOperationRequestRepository = new(); + private readonly Mock _auditService = new(); + private readonly Mock _coinSelectionService = new(); + + private AutoChannelOpenJob BuildJob() => + new( + _logger.Object, + _nodeRepository.Object, + _forwardingHtlcEventRepository.Object, + _recommendationRepository.Object, + _promotionService.Object, + _lightningService.Object, + _nbXplorerService.Object, + _channelOperationRequestRepository.Object, + _auditService.Object, + _coinSelectionService.Object); + + /// + /// Both switches are process-wide statics, so they are set and restored around every run to keep + /// one test from leaking into the next. + /// + private async Task Run(bool engine = true, bool feature = true) + { + await RoutingEngineSwitch.WithEngine(engine, async () => + { + var previous = Constants.AUTO_CHANNEL_OPEN_ENABLED; + Constants.AUTO_CHANNEL_OPEN_ENABLED = feature; + try + { + await BuildJob().Execute(Mock.Of()); + } + finally + { + Constants.AUTO_CHANNEL_OPEN_ENABLED = previous; + } + }); + } + + /// + /// A peer with two channels that together clear every gate: the earned fees and the refusals are + /// split across them, and both are nearly empty. Optionally a second peer that qualifies the same way. + /// + private Node ArrangeQualifyingPeer( + AutoChannelOpenMode mode = AutoChannelOpenMode.Recommendation, + long? sizeSats = SizeSats, + long budgetSats = 1_000_000_000, + long committedSats = 0, + bool dryRun = false, + long[]? walletUtxoSats = null, + bool secondPeer = false) + { + var node = new Node + { + Id = NodeId, + PubKey = NodePubKey, + Name = "alice", + AutoChannelOpenEnabled = true, + AutoChannelOpenMode = mode, + AutoChannelOpenWalletId = 3, + AutoChannelOpenWallet = FundingWallet(), + AutoChannelOpenSizeSats = sizeSats, + AutoChannelOpenBudgetSats = budgetSats, + AutoChannelOpenBudgetStartDatetime = DateTimeOffset.UtcNow.AddHours(-1), + RoutingEngineDryRun = dryRun, + }; + + _nodeRepository.Setup(x => x.GetAllWithAutoChannelOpenEnabled()).ReturnsAsync(new List { node }); + _nbXplorerService.Setup(x => x.GetFeesByType(MempoolRecommendedFeesType.HourFee, default)).ReturnsAsync(10m); + _recommendationRepository.Setup(x => x.ExpireOpen(NodeId)).ReturnsAsync(0); + _recommendationRepository.Setup(x => x.FailUnrealizedPromotions(NodeId)).ReturnsAsync(0); + _recommendationRepository.Setup(x => x.GetLastDecisionByPeer(NodeId)) + .ReturnsAsync(new Dictionary()); + _channelOperationRequestRepository + .Setup(x => x.GetOpenSatsCommittedSince(NodeId, It.IsAny())) + .ReturnsAsync(committedSats); + + // Each channel alone falls short of both gates; only the peer-level sums clear them. + var minFeeMsat = Constants.AUTO_CHANNEL_OPEN_MIN_EARNED_FEE_SATS * 1000; + var minRefusals = Constants.AUTO_CHANNEL_OPEN_MIN_REFUSALS; + var fees = new Dictionary { [ChanId] = minFeeMsat / 2, [SecondChanToPeer] = minFeeMsat / 2 }; + var refusals = new Dictionary { [ChanId] = minRefusals - minRefusals / 2, [SecondChanToPeer] = minRefusals / 2 }; + var outgoing = new Dictionary { [ChanId] = 3_000_000_000, [SecondChanToPeer] = 1_000_000_000 }; + + var channels = new Lnrpc.ListChannelsResponse + { + Channels = + { + DryChannel(ChanId, Peer), + DryChannel(SecondChanToPeer, Peer), + }, + }; + var policies = new Dictionary + { + [ChanId] = new(900, 1_000), + [SecondChanToPeer] = new(1_200, 0), + }; + + if (secondPeer) + { + channels.Channels.Add(DryChannel(SecondPeerChanId, SecondPeer)); + policies[SecondPeerChanId] = new LocalOutboundPolicy(900, 1_000); + fees[SecondPeerChanId] = minFeeMsat * 2; + refusals[SecondPeerChanId] = minRefusals; + } + + _forwardingHtlcEventRepository + .Setup(x => x.GetEarnedFeesMsatByChannel(NodePubKey, It.IsAny())) + .ReturnsAsync(fees); + _forwardingHtlcEventRepository + .Setup(x => x.GetInsufficientBalanceCountsByChannel(NodePubKey, It.IsAny())) + .ReturnsAsync(refusals); + _forwardingHtlcEventRepository + .Setup(x => x.GetOutgoingAmountsMsatByChannel(NodePubKey, It.IsAny())) + .ReturnsAsync(outgoing); + _lightningService.Setup(x => x.ListChannels(It.IsAny())).ReturnsAsync(channels); + _lightningService.Setup(x => x.GetLocalOutboundPoliciesAsync(It.IsAny())).ReturnsAsync(policies); + + var utxos = (walletUtxoSats ?? [1_000_000_000]) + .Select((sats, i) => TestUtxos.Spendable(node.AutoChannelOpenWallet, (uint)i, sats)) + .ToList(); + _coinSelectionService.Setup(x => x.GetAvailableUTXOsAsync(It.IsAny())) + .ReturnsAsync(utxos); + + SetupUpsertReturning(ChannelOpenRecommendationStatus.Open); + + _promotionService + .Setup(x => x.Promote(It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync((true, (string?)null)); + + return node; + } + + // 100k usable on 10M: 1%, well under the low-outbound threshold. + private static Lnrpc.Channel DryChannel(ulong chanId, string peer) => new() + { + ChanId = chanId, + RemotePubkey = peer, + Active = true, + Initiator = true, + Capacity = 10_000_000, + LocalBalance = 200_000, + LocalChanReserveSat = 100_000, + }; + + private static Wallet FundingWallet() + { + var wallet = CreateWallet.SingleSig(CreateWallet.CreateInternalWallet()); + wallet.Id = 3; + return wallet; + } + + private void SetupUpsertReturning(ChannelOpenRecommendationStatus status) => + _recommendationRepository + .Setup(x => x.Upsert(It.IsAny())) + .ReturnsAsync((ChannelOpenRecommendation plan) => + { + plan.Id = 42; + plan.Status = status; + return (plan, (string?)null); + }); + + private void VerifyRecorded(Times times) => + _recommendationRepository.Verify(x => x.Upsert(It.IsAny()), times); + + private void VerifyPromoted(Times times) => + _promotionService.Verify(x => x.Promote(It.IsAny(), It.IsAny(), It.IsAny()), times); + + private void VerifyAudited(Times times) => + _auditService.Verify(x => x.LogAsync( + AuditActionType.Create, + AuditEventType.Success, + AuditObjectType.ChannelOpenRecommendation, + It.IsAny(), + It.IsAny()), times); + + // ── Kill switches ────────────────────────────────────────────────────────────────── + + [Fact] + public async Task Execute_RoutingEngineOff_DoesNotEvenLookForNodes() + { + ArrangeQualifyingPeer(); + + await Run(engine: false); + + _nodeRepository.Verify(x => x.GetAllWithAutoChannelOpenEnabled(), Times.Never); + } + + [Fact] + public async Task Execute_FeatureOff_DoesNotEvenLookForNodes() + { + ArrangeQualifyingPeer(); + + await Run(feature: false); + + _nodeRepository.Verify(x => x.GetAllWithAutoChannelOpenEnabled(), Times.Never); + } + + [Fact] + public async Task Execute_NoFeerate_SkipsBeforeTouchingAnyNode() + { + ArrangeQualifyingPeer(); + _nbXplorerService.Setup(x => x.GetFeesByType(MempoolRecommendedFeesType.HourFee, default)) + .ReturnsAsync((decimal?)null); + + await Run(); + + // The feerate prices the funding fee, so without it the wallet check can't run. + _nodeRepository.Verify(x => x.GetAllWithAutoChannelOpenEnabled(), Times.Never); + VerifyRecorded(Times.Never()); + } + + // ── Peer roll-up ─────────────────────────────────────────────────────────────────── + + [Fact] + public async Task Execute_PeerWithTwoChannels_RecordsOneRowWithTheSummedEvidence() + { + ArrangeQualifyingPeer(); + + await Run(); + + _recommendationRepository.Verify(x => x.Upsert(It.Is(r => + r.NodeId == NodeId + && r.PeerPubKey == Peer + && r.EarnedFeeSats == Constants.AUTO_CHANNEL_OPEN_MIN_EARNED_FEE_SATS + && r.Refusals == Constants.AUTO_CHANNEL_OPEN_MIN_REFUSALS + && r.SettledOutSats == 4_000_000 + && r.UsableLocalSats == 200_000 + && r.PeerCapacitySats == 20_000_000 + && r.SuggestedCapacitySats == SizeSats + // The dearest channel's policy, base fee from that same channel + && r.InheritedFeeRatePpm == 1_200 + && r.InheritedBaseFeeMsat == 0)), Times.Once); + } + + [Fact] + public async Task Execute_RefusalsOnAClosedChannel_AreDropped() + { + ArrangeQualifyingPeer(); + _forwardingHtlcEventRepository + .Setup(x => x.GetInsufficientBalanceCountsByChannel(NodePubKey, It.IsAny())) + .ReturnsAsync(new Dictionary { [999_999] = 100 }); + + await Run(); + + // No listed channel maps the scid back to a peer, and a closed channel is not a route. + VerifyRecorded(Times.Never()); + } + + // ── The expire-first lifecycle ───────────────────────────────────────────────────── + + [Fact] + public async Task Execute_PeerClearsEveryGate_ExpiresFirstThenRecords() + { + ArrangeQualifyingPeer(); + + await Run(); + + // Expiry runs before anything is planned, so the panel is always this run's output. + _recommendationRepository.Verify(x => x.ExpireOpen(NodeId), Times.Once); + VerifyRecorded(Times.Once()); + } + + [Fact] + public async Task Execute_UnrealizedPromotions_AreReleasedBeforeTheCooldownIsRead() + { + ArrangeQualifyingPeer(); + var released = false; + var cooldownSawTheRelease = false; + _recommendationRepository.Setup(x => x.FailUnrealizedPromotions(NodeId)) + .ReturnsAsync(1) + .Callback(() => released = true); + _recommendationRepository.Setup(x => x.GetLastDecisionByPeer(NodeId)) + .ReturnsAsync(new Dictionary()) + .Callback(() => cooldownSawTheRelease = released); + + await Run(); + + // A promotion that came to nothing has to be cleared first, or its peer stays suppressed. + released.Should().BeTrue(); + cooldownSawTheRelease.Should().BeTrue(); + } + + [Fact] + public async Task Execute_NoSizeConfigured_RecordsNothing() + { + ArrangeQualifyingPeer(sizeSats: null); + + await Run(); + + VerifyRecorded(Times.Never()); + } + + [Fact] + public async Task Execute_BudgetExhausted_StillExpiresAndRecordsNothing() + { + ArrangeQualifyingPeer(budgetSats: 1_000, committedSats: 1_000); + + await Run(); + + _recommendationRepository.Verify(x => x.ExpireOpen(NodeId), Times.Once); + VerifyRecorded(Times.Never()); + } + + [Fact] + public async Task Execute_FundingWalletEmpty_RecordsNothing() + { + ArrangeQualifyingPeer(walletUtxoSats: []); + + await Run(); + + VerifyRecorded(Times.Never()); + } + + [Fact] + public async Task Execute_WalletJustUnderTheSizeOnceFeeAndChangeAreKept_RecordsNothing() + { + // One coin of exactly the size: the funding fee and a dust-safe change output don't fit on top. + ArrangeQualifyingPeer(walletUtxoSats: [SizeSats]); + + await Run(); + + VerifyRecorded(Times.Never()); + } + + // ── Record, audit, promote ───────────────────────────────────────────────────────── + + [Fact] + public async Task Execute_RecommendationMode_RecordsAndAuditsButNeverPromotes() + { + ArrangeQualifyingPeer(mode: AutoChannelOpenMode.Recommendation); + + await Run(); + + VerifyRecorded(Times.Once()); + VerifyAudited(Times.Once()); + VerifyPromoted(Times.Never()); + } + + [Fact] + public async Task Execute_AutoMode_PromotesAtTheFixedSize() + { + ArrangeQualifyingPeer(mode: AutoChannelOpenMode.Auto); + + await Run(); + + VerifyRecorded(Times.Once()); + _promotionService.Verify(x => x.Promote(42, SizeSats, null), Times.Once); + } + + [Fact] + public async Task Execute_AutoModeButDryRun_RecordsWithoutPromoting() + { + ArrangeQualifyingPeer(mode: AutoChannelOpenMode.Auto, dryRun: true); + + await Run(); + + VerifyRecorded(Times.Once()); + VerifyPromoted(Times.Never()); + } + + [Fact] + public async Task Execute_UpsertReturnsARowItDidNotOpen_WritesNoAuditEntryAndDoesNotPromote() + { + ArrangeQualifyingPeer(mode: AutoChannelOpenMode.Auto); + + // What the upsert returns when the peer's previous open is still unresolved. + SetupUpsertReturning(ChannelOpenRecommendationStatus.Promoted); + + await Run(); + + VerifyAudited(Times.Never()); + VerifyPromoted(Times.Never()); + } + + [Fact] + public async Task Execute_PeerWithinTheCooldown_IsNotRecommended() + { + ArrangeQualifyingPeer(); + _recommendationRepository.Setup(x => x.GetLastDecisionByPeer(NodeId)) + .ReturnsAsync(new Dictionary { [Peer] = DateTimeOffset.UtcNow }); + + await Run(); + + VerifyRecorded(Times.Never()); + } + + [Fact] + public async Task Execute_TwoQualifyingPeersButBudgetForOne_PromotesOnlyTheHigherEarner() + { + // Each plan is checked against the whole remaining budget, so the job has to decrement as it + // promotes or both would commit the period's budget. + ArrangeQualifyingPeer(mode: AutoChannelOpenMode.Auto, budgetSats: SizeSats, secondPeer: true); + + await Run(); + + VerifyRecorded(Times.Once()); + _recommendationRepository.Verify(x => x.Upsert(It.Is(r => r.PeerPubKey == SecondPeer)), Times.Once); + VerifyPromoted(Times.Once()); + } +} diff --git a/test/NodeGuard.Tests/Services/ChannelOpenInitiatorServiceTests.cs b/test/NodeGuard.Tests/Services/ChannelOpenInitiatorServiceTests.cs new file mode 100644 index 000000000..4f0a6a3bf --- /dev/null +++ b/test/NodeGuard.Tests/Services/ChannelOpenInitiatorServiceTests.cs @@ -0,0 +1,135 @@ +/* + * NodeGuard + * Copyright (C) 2023 Elenpay + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see http://www.gnu.org/licenses/. + * + */ + +using FluentAssertions; +using NodeGuard.Data.Models; + +namespace NodeGuard.Services; + +public class ChannelOpenInitiatorServiceTests +{ + private const long Size = 5_000_000; + + private static readonly ChannelOpenInitiatorTunables Tunables = new( + MinEarnedFeeSats: 10_000, + MinRefusals: 5, + LowOutboundPct: 20, + SizeSats: Size, + WalletSpendableSats: 100_000_000, + RemainingBudgetSats: 100_000_000, + MaxPlansPerRun: 5); + + /// Clears every gate by default; each test breaks exactly one. + private static PeerSnapshot Peer( + string pubKey = "03peer", + long earnedFeeSats = 10_000, + int refusals = 5, + long usableLocalSats = 1_999_999, + long capacitySats = 10_000_000, + LocalOutboundPolicy? policy = null, + bool noPolicy = false, + bool onCooldown = false) + => new(pubKey, earnedFeeSats, 4_000_000, refusals, usableLocalSats, capacitySats, + noPolicy ? null : policy ?? new LocalOutboundPolicy(1_200, 1_000), onCooldown); + + private static ChannelOpenClassification Evaluate(PeerSnapshot peer, ChannelOpenInitiatorTunables? t = null) + => ChannelOpenInitiatorService.Evaluate([peer], t ?? Tunables); + + [Fact] + public void Evaluate_PeerAtEveryThreshold_IsPlannedAtTheFixedSizeAndInheritedPolicy() + { + var result = Evaluate(Peer()); + + result.Rejected.Should().BeEmpty(); + var plan = result.Plans.Should().ContainSingle().Subject; + plan.PeerPubKey.Should().Be("03peer"); + plan.SuggestedCapacitySats.Should().Be(Size); + plan.EarnedFeeSats.Should().Be(10_000); + plan.Refusals.Should().Be(5); + plan.UsableLocalSats.Should().Be(1_999_999); + plan.PeerCapacitySats.Should().Be(10_000_000); + plan.InheritedFeeRatePpm.Should().Be(1_200); + plan.InheritedBaseFeeMsat.Should().Be(1_000); + plan.Status.Should().Be(ChannelOpenRecommendationStatus.Open); + } + + [Fact] + public void Evaluate_EarnedTooLittle_IsRejected() + => Evaluate(Peer(earnedFeeSats: 9_999)).Plans.Should().BeEmpty(); + + [Fact] + public void Evaluate_TooFewRefusals_IsRejected() + => Evaluate(Peer(refusals: 4)).Plans.Should().BeEmpty(); + + [Fact] + public void Evaluate_OutboundAtTheThreshold_IsRejected() + { + // 20% of 10M exactly: the shortage has passed, whatever the refusals said. + var result = Evaluate(Peer(usableLocalSats: 2_000_000)); + + result.Plans.Should().BeEmpty(); + result.Rejected.Should().ContainSingle().Which.Reason.Should().Contain("usable outbound"); + } + + [Fact] + public void Evaluate_OnCooldown_IsRejected() + => Evaluate(Peer(onCooldown: true)).Plans.Should().BeEmpty(); + + [Fact] + public void Evaluate_NoOutboundPolicy_IsRejected() + => Evaluate(Peer(noPolicy: true)).Plans.Should().BeEmpty(); + + [Fact] + public void Evaluate_NoSizeConfigured_IsRejected() + => Evaluate(Peer(), Tunables with { SizeSats = 0 }).Plans.Should().BeEmpty(); + + [Fact] + public void Evaluate_WalletCannotFundTheSize_IsRejectedRatherThanShrunk() + { + var result = Evaluate(Peer(), Tunables with { WalletSpendableSats = Size - 1 }); + + result.Plans.Should().BeEmpty(); + result.Rejected.Should().ContainSingle().Which.Reason.Should().Contain("funding wallet"); + } + + [Fact] + public void Evaluate_BudgetCannotCoverTheSize_IsRejectedRatherThanShrunk() + { + var result = Evaluate(Peer(), Tunables with { RemainingBudgetSats = Size - 1 }); + + result.Plans.Should().BeEmpty(); + result.Rejected.Should().ContainSingle().Which.Reason.Should().Contain("budget"); + } + + [Fact] + public void Evaluate_MorePeersThanTheRunCap_KeepsTheHighestEarners() + { + var peers = new[] + { + Peer("03low", earnedFeeSats: 10_000), + Peer("03high", earnedFeeSats: 90_000), + Peer("03mid", earnedFeeSats: 50_000), + }; + + var result = ChannelOpenInitiatorService.Evaluate(peers, Tunables with { MaxPlansPerRun = 2 }); + + result.Plans.Select(x => x.PeerPubKey).Should().Equal("03high", "03mid"); + result.Rejected.Should().ContainSingle().Which.PeerPubKey.Should().Be("03low"); + } +} diff --git a/test/NodeGuard.Tests/Services/ChannelOpenPromotionServiceTests.cs b/test/NodeGuard.Tests/Services/ChannelOpenPromotionServiceTests.cs new file mode 100644 index 000000000..245d0e84e --- /dev/null +++ b/test/NodeGuard.Tests/Services/ChannelOpenPromotionServiceTests.cs @@ -0,0 +1,451 @@ +/* + * NodeGuard + * Copyright (C) 2023 Elenpay + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see http://www.gnu.org/licenses/. + * + */ + +using FluentAssertions; +using Lnrpc; +using Microsoft.Extensions.Logging; +using NBitcoin; +using NodeGuard.Data.Models; +using NodeGuard.Data.Repositories.Interfaces; +using NodeGuard.Helpers; +using Quartz; + +namespace NodeGuard.Services; + +/// +/// This is where a recommendation turns into a funding instruction, so these cover what the request +/// is built with and which wallets get dispatched without a human signature. +/// +public class ChannelOpenPromotionServiceTests +{ + private const int RecommendationId = 11; + private const int NodeIdValue = 7; + private const int WalletIdValue = 3; + private const int DestNodeId = 99; + private const string PeerPubKey = "03peer"; + private const string NodePubKey = "03alice"; + + /// Any valid PSBT will do; the code under test only checks it is not null. + private const string TemplatePsbtHex = "70736274ff01005e01000000013f8f745a7b40c6df77d5c558361509612d34a9fec5540d9e0ab10f1bc1d4eeec0000000000ffffffff0113601200000000002200200b977d20c92e6fb7efaf6286b58f00f4a40cbab98ce7e44fe704b9ac886e3a41000000004f01043587cf032f11242c80000001fc3bee423a018ceb6d226a0663288ed0fb5ee0fa9d790ab370d030e04730e6c803808e2e1cd482bdd07196943c5a8133d169af86022b6bb0381771644ec07444d7101fcce4de3000008001000080010000804f01043587cf0356ac03f480000001f908ae4a66b0ffa1ab14b55af0ce48f2a70225cb9010902d6901af90b93e8f810251af15e05bb8b7eac1895b3f5f47ffefecd8321a02ef22298f89d0a2037df0601060f3a0b33000008001000080010000804f01043587cf037db9468d80000001f52270c7687a3afb351ef4f1b9a30c10f3b6d392170683aea9488c139a11c998032223852338ea67fbfd8dc352ab2625e79a27764621236bf1c0213090d3489e9f10ed0210c83000008001000080010000800001012b8f62120000000000220020997a5fd26a72084c8a2d12bf902acec18669900dd09891d2ea24a8711ca3ec6e220203b0dbc01268f283bf00120c763686bd8984e7789442cf5c2802095f78b9b9ab9a47304402202e1820e8f1e3b8ad7d10117a9a83a3a8567537d73336d01b9f08859fda4856fe0220727a714631e4ffcd954ae4e011b3039232fa16e1ef99f7e6bd6f422fd3187b8502010304020000000105695221028761458f9cc5c051ed6baf4076df9d89ed21daf2d0f7570382c1bcf23c09878121035a4be5f58b8bbe9d399d9f2d8e004b42643649a5c75575fc3739dfac73264b2c2103b0dbc01268f283bf00120c763686bd8984e7789442cf5c2802095f78b9b9ab9a53ae2206028761458f9cc5c051ed6baf4076df9d89ed21daf2d0f7570382c1bcf23c0987811860f3a0b330000080010000800100008001000000050000002206035a4be5f58b8bbe9d399d9f2d8e004b42643649a5c75575fc3739dfac73264b2c18ed0210c83000008001000080010000800100000005000000220603b0dbc01268f283bf00120c763686bd8984e7789442cf5c2802095f78b9b9ab9a181fcce4de30000080010000800100008001000000050000000000"; + + private readonly Mock> _logger = new(); + private readonly Mock _recommendationRepository = new(); + private readonly Mock _channelOperationRequestRepository = new(); + private readonly Mock _nodeRepository = new(); + private readonly Mock _walletRepository = new(); + private readonly Mock _lightningService = new(); + private readonly Mock _schedulerFactory = new(); + private readonly Mock _scheduler = new(); + private readonly Mock _auditService = new(); + + private ChannelOpenPromotionService BuildService() => + new( + _logger.Object, + _recommendationRepository.Object, + _channelOperationRequestRepository.Object, + _nodeRepository.Object, + _walletRepository.Object, + _lightningService.Object, + _schedulerFactory.Object, + _auditService.Object); + + private static ChannelOpenRecommendation Recommendation( + ChannelOpenRecommendationStatus status = ChannelOpenRecommendationStatus.Open, + int? walletId = WalletIdValue) => new() + { + Id = RecommendationId, + NodeId = NodeIdValue, + PeerPubKey = PeerPubKey, + InheritedFeeRatePpm = 2_850, + InheritedBaseFeeMsat = 1_000, + SuggestedCapacitySats = 5_000_000, + EarnedFeeSats = 25_000, + Refusals = 7, + Status = status, + Node = new Node + { + Id = NodeIdValue, + Name = "alice", + PubKey = NodePubKey, + AutoChannelOpenWalletId = walletId, + }, + }; + + /// + /// The whole happy path wired up. drives the branch that decides + /// whether NodeGuard dispatches the open itself or leaves it for human signers. + /// + private void ArrangePromotable( + ChannelOpenRecommendationStatus status = ChannelOpenRecommendationStatus.Open, + int? walletId = WalletIdValue, + bool isHotWallet = false, + bool templatePsbtGenerated = true, + bool signaturesCollected = true) + { + _recommendationRepository.Setup(x => x.GetById(RecommendationId)) + .ReturnsAsync(Recommendation(status, walletId)); + + _recommendationRepository.Setup(x => x.UpdateIfStatus(It.IsAny(), ChannelOpenRecommendationStatus.Open)).ReturnsAsync((true, (string?)null)); + + _nodeRepository.Setup(x => x.GetOrCreateByPubKey(PeerPubKey, It.IsAny())) + .ReturnsAsync(new Node { Id = DestNodeId, PubKey = PeerPubKey }); + + // The service reads request.Id straight after, so the insert has to look like one. + _channelOperationRequestRepository + .Setup(x => x.AddAsync(It.IsAny())) + .ReturnsAsync((ChannelOperationRequest r) => { r.Id = 500; return (true, (string?)null); }); + + var wallet = new Wallet { Id = WalletIdValue, IsHotWallet = isHotWallet, MofN = 2 }; + _walletRepository.Setup(x => x.GetById(WalletIdValue)).ReturnsAsync(wallet); + + _lightningService.Setup(x => x.GenerateTemplatePSBT(It.IsAny())) + .ReturnsAsync(templatePsbtGenerated ? (PSBT.Parse(TemplatePsbtHex, Network.RegTest), false) : ((PSBT?)null, false)); + + var persisted = new ChannelOperationRequest + { + Id = 500, + Wallet = wallet, + ChannelOperationRequestPsbts = signaturesCollected + ? new List { new() { IsTemplatePSBT = true } } + : new List(), + }; + _channelOperationRequestRepository.Setup(x => x.GetById(500)).ReturnsAsync(persisted); + _channelOperationRequestRepository.Setup(x => x.Update(It.IsAny())).Returns((true, (string?)null)); + + _schedulerFactory.Setup(x => x.GetScheduler(default)).ReturnsAsync(_scheduler.Object); + } + + // ── Promote: refusals ────────────────────────────────────────────────────────────── + + [Fact] + public async Task Promote_RecommendationNotFound_Refuses() + { + _recommendationRepository.Setup(x => x.GetById(RecommendationId)).ReturnsAsync((ChannelOpenRecommendation?)null); + + var (ok, error) = await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + ok.Should().BeFalse(); + error.Should().Contain("not found"); + } + + [Theory] + [InlineData(ChannelOpenRecommendationStatus.Promoted)] + [InlineData(ChannelOpenRecommendationStatus.Dismissed)] + [InlineData(ChannelOpenRecommendationStatus.Expired)] + public async Task Promote_RecommendationAlreadyDecided_RefusesNamingTheStatus(ChannelOpenRecommendationStatus status) + { + ArrangePromotable(status: status); + + var (ok, error) = await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + ok.Should().BeFalse(); + error.Should().Contain(status.ToString()); + _channelOperationRequestRepository.Verify(x => x.AddAsync(It.IsAny()), Times.Never); + } + + [Fact] + public async Task Promote_NodeWithoutAFundingWallet_RefusesBeforeCreatingAnything() + { + ArrangePromotable(walletId: null); + + var (ok, error) = await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + ok.Should().BeFalse(); + error.Should().Contain("funding wallet"); + _channelOperationRequestRepository.Verify(x => x.AddAsync(It.IsAny()), Times.Never); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(19_999)] + public async Task Promote_CapacityBelowTheChannelMinimum_Refuses(long capacity) + { + ArrangePromotable(); + + var (ok, error) = await BuildService().Promote(RecommendationId, capacity, userId: "u1"); + + ok.Should().BeFalse(); + error.Should().Contain($"{Constants.MINIMUM_CHANNEL_CAPACITY_SATS} sats"); + _channelOperationRequestRepository.Verify(x => x.AddAsync(It.IsAny()), Times.Never); + } + + // ── Promote: the request it builds ───────────────────────────────────────────────── + + [Fact] + public async Task Promote_BuildsAPendingOpenRequestFundedFromTheNodesWallet() + { + ArrangePromotable(); + ChannelOperationRequest? captured = null; + _channelOperationRequestRepository + .Setup(x => x.AddAsync(It.IsAny())) + .ReturnsAsync((ChannelOperationRequest r) => { r.Id = 500; captured = r; return (true, (string?)null); }); + + var (ok, _) = await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + ok.Should().BeTrue(); + captured.Should().NotBeNull(); + captured!.Status.Should().Be(ChannelOperationRequestStatus.Pending); + captured.RequestType.Should().Be(OperationRequestType.Open); + captured.WalletId.Should().Be(WalletIdValue); + captured.SourceNodeId.Should().Be(NodeIdValue); + captured.DestNodeId.Should().Be(DestNodeId); + captured.UserId.Should().Be("u1"); + } + + [Fact] + public async Task Promote_CapacityEditedByTheOperator_OverridesTheSuggestion() + { + ArrangePromotable(); + ChannelOperationRequest? captured = null; + _channelOperationRequestRepository + .Setup(x => x.AddAsync(It.IsAny())) + .ReturnsAsync((ChannelOperationRequest r) => { r.Id = 500; captured = r; return (true, (string?)null); }); + + // The panel lets the number be changed before promoting, so the suggestion must not win. + await BuildService().Promote(RecommendationId, 9_999_999, userId: "u1"); + + captured!.SatsAmount.Should().Be(9_999_999); + captured.Description.Should().Contain("Auto channel open"); + } + + [Fact] + public async Task Promote_MarksTheRecommendationPromotedAndLinksItToTheRequest() + { + ArrangePromotable(); + ChannelOpenRecommendation? updated = null; + _recommendationRepository + .Setup(x => x.UpdateIfStatus(It.IsAny(), ChannelOpenRecommendationStatus.Open)) + .ReturnsAsync((ChannelOpenRecommendation r, ChannelOpenRecommendationStatus _) => { updated = r; return (true, (string?)null); }); + + await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + // The link is what later tells the job that this peer's open has not resolved yet. + updated!.Status.Should().Be(ChannelOpenRecommendationStatus.Promoted); + updated.ChannelOperationRequestId.Should().Be(500); + } + + [Fact] + public async Task Promote_RecommendationNoLongerOpenOnceTheRequestExists_CancelsTheRequest() + { + // Another promotion, or the job expiring the row, got there between the read and the write. + ArrangePromotable(); + _recommendationRepository + .Setup(x => x.UpdateIfStatus(It.IsAny(), ChannelOpenRecommendationStatus.Open)) + .ReturnsAsync((false, "Recommendation is no longer Open")); + ChannelOperationRequest? cancelled = null; + _channelOperationRequestRepository + .Setup(x => x.Update(It.IsAny())) + .Returns((ChannelOperationRequest r) => { cancelled = r; return (true, (string?)null); }); + + var (ok, error) = await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + ok.Should().BeFalse(); + error.Should().Be("Recommendation is no longer Open"); + cancelled!.Id.Should().Be(500); + cancelled.Status.Should().Be(ChannelOperationRequestStatus.Cancelled); + _lightningService.Verify(x => x.GenerateTemplatePSBT(It.IsAny()), Times.Never); + } + + // ── Promote: the fee the channel opens at ────────────────────────────────────────── + + [Fact] + public async Task Promote_OpensAtThePolicyTheRecommendationWasGatedOn() + { + // The new channel arrives full next to a sibling the engine already priced high. Opening at the + // global default would make it the cheap route to a peer we know drains us. + ArrangePromotable(); + + ChannelOperationRequest? captured = null; + _channelOperationRequestRepository + .Setup(x => x.AddAsync(It.IsAny())) + .ReturnsAsync((ChannelOperationRequest r) => { r.Id = 500; captured = r; return (true, (string?)null); }); + + await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + captured!.InitialChannelFeeRatePpm.Should().Be(2_850); + captured.InitialChannelBaseFeeMsat.Should().Be(1_000); + } + + [Fact] + public async Task Promote_NeverRepricesAgainstLND() + { + // Re-reading the policy here would price off gossip and could contradict the number the + // operator saw and approved on the panel. + ArrangePromotable(); + + await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + _lightningService.Verify(x => x.GetChannelFeePolicy(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task Promote_RowPredatingFeeCapture_RefusesRatherThanGuessingAPrice() + { + // A row written before the policy was captured has no price to open at, and inventing one + // would just undercut the sibling. The next run replaces it with a priced row. + ArrangePromotable(); + _recommendationRepository + .Setup(x => x.GetById(RecommendationId)) + .ReturnsAsync(() => + { + var stale = Recommendation(); + stale.InheritedFeeRatePpm = null; + stale.InheritedBaseFeeMsat = null; + return stale; + }); + + var (ok, error) = await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + ok.Should().BeFalse(); + error.Should().Contain("no inherited fee policy"); + _channelOperationRequestRepository.Verify(x => x.AddAsync(It.IsAny()), Times.Never); + } + + [Fact] + public async Task Promote_PeerChargedZeroPpm_OpensAtZeroRatherThanRefusing() + { + // Zero is a captured price, not a missing one: the peer can still earn through the base fee. + ArrangePromotable(); + _recommendationRepository + .Setup(x => x.GetById(RecommendationId)) + .ReturnsAsync(() => + { + var zeroPpm = Recommendation(); + zeroPpm.InheritedFeeRatePpm = 0; + return zeroPpm; + }); + ChannelOperationRequest? captured = null; + _channelOperationRequestRepository + .Setup(x => x.AddAsync(It.IsAny())) + .ReturnsAsync((ChannelOperationRequest r) => { r.Id = 500; captured = r; return (true, (string?)null); }); + + var (ok, _) = await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + ok.Should().BeTrue(); + captured!.InitialChannelFeeRatePpm.Should().Be(0); + captured.InitialChannelBaseFeeMsat.Should().Be(1_000); + } + + // ── Promote: dispatch ────────────────────────────────────────────────────────────── + + [Fact] + public async Task Promote_MultisigWallet_LeavesTheRequestPendingForSigners() + { + ArrangePromotable(isHotWallet: false); + + var (ok, error) = await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + ok.Should().BeTrue(); + error.Should().BeNull(); + _lightningService.Verify(x => x.GenerateTemplatePSBT(It.IsAny()), Times.Never); + _scheduler.Verify(x => x.ScheduleJob(It.IsAny(), It.IsAny(), default), Times.Never); + } + + [Fact] + public async Task Promote_HotWalletWithItsTemplate_SchedulesTheOpenItself() + { + // A hot wallet has no external signer, so without this the request would sit Pending forever + // with no UI action that can move it. + ArrangePromotable(isHotWallet: true); + + var (ok, _) = await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + ok.Should().BeTrue(); + _scheduler.Verify(x => x.ScheduleJob(It.IsAny(), It.IsAny(), default), Times.Once); + } + + [Fact] + public async Task Promote_HotWalletWithNoTemplatePsbt_FailsTheRequestRatherThanLeavingItPending() + { + ArrangePromotable(isHotWallet: true, templatePsbtGenerated: false); + ChannelOperationRequest? failed = null; + _channelOperationRequestRepository + .Setup(x => x.Update(It.IsAny())) + .Returns((ChannelOperationRequest r) => { failed = r; return (true, (string?)null); }); + + var (ok, error) = await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + ok.Should().BeFalse(); + error.Should().NotBeNull(); + failed!.Status.Should().Be(ChannelOperationRequestStatus.Failed); + _scheduler.Verify(x => x.ScheduleJob(It.IsAny(), It.IsAny(), default), Times.Never); + } + + [Fact] + public async Task Promote_DispatchThrowsAfterThePromotionIsSaved_FailsTheRequestRatherThanLeavingItPending() + { + ArrangePromotable(isHotWallet: true); + _scheduler + .Setup(x => x.ScheduleJob(It.IsAny(), It.IsAny(), default)) + .ThrowsAsync(new SchedulerException("store unavailable")); + ChannelOperationRequest? failed = null; + _channelOperationRequestRepository + .Setup(x => x.Update(It.IsAny())) + .Returns((ChannelOperationRequest r) => { failed = r; return (true, (string?)null); }); + + var (ok, error) = await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + // Failed is what lets the next run release the peer and the coins the template locked. + ok.Should().BeFalse(); + error.Should().NotBeNull(); + failed!.Id.Should().Be(500); + failed.Status.Should().Be(ChannelOperationRequestStatus.Failed); + } + + [Fact] + public async Task Promote_HotWalletStillMissingSignatures_DoesNotSchedule() + { + ArrangePromotable(isHotWallet: true, signaturesCollected: false); + + var (ok, _) = await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + ok.Should().BeTrue(); + _scheduler.Verify(x => x.ScheduleJob(It.IsAny(), It.IsAny(), default), Times.Never); + } + + // ── Dismiss ──────────────────────────────────────────────────────────────────────── + + [Fact] + public async Task Dismiss_RecordsTheStatusAndTheReason() + { + ArrangePromotable(); + ChannelOpenRecommendation? updated = null; + _recommendationRepository + .Setup(x => x.UpdateIfStatus(It.IsAny(), ChannelOpenRecommendationStatus.Open)) + .ReturnsAsync((ChannelOpenRecommendation r, ChannelOpenRecommendationStatus _) => { updated = r; return (true, (string?)null); }); + + var (ok, _) = await BuildService().Dismiss(RecommendationId, "not now", userId: "u1"); + + ok.Should().BeTrue(); + updated!.Status.Should().Be(ChannelOpenRecommendationStatus.Dismissed); + updated.DismissReason.Should().Be("not now"); + } + + [Fact] + public async Task Dismiss_AlreadyDecided_Refuses() + { + ArrangePromotable(status: ChannelOpenRecommendationStatus.Promoted); + + var (ok, error) = await BuildService().Dismiss(RecommendationId, "not now", userId: "u1"); + + ok.Should().BeFalse(); + error.Should().Contain("dismissed"); + } +} diff --git a/test/NodeGuard.Tests/TestHelpers/TestUtxos.cs b/test/NodeGuard.Tests/TestHelpers/TestUtxos.cs new file mode 100644 index 000000000..1ff5d6a3d --- /dev/null +++ b/test/NodeGuard.Tests/TestHelpers/TestUtxos.cs @@ -0,0 +1,43 @@ +/* + * NodeGuard + * Copyright (C) 2023 Elenpay + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see http://www.gnu.org/licenses/. + * + */ + +using NBitcoin; +using NBXplorer.DerivationStrategy; +using NBXplorer.Models; +using NodeGuard.Data.Models; + +namespace NodeGuard.TestHelpers; + +public static class TestUtxos +{ + /// A UTXO carrying the key path and script the wallet derives for it. + public static UTXO Spendable(Wallet wallet, uint index, long satoshis, int confirmations = 1) + { + var keyPath = KeyPath.Parse($"0/{index}"); + + return new UTXO + { + Outpoint = new OutPoint(new uint256(index + 1), 0), + Value = new Money(satoshis), + Confirmations = confirmations, + KeyPath = keyPath, + ScriptPubKey = ((StandardDerivationStrategyBase)wallet.GetDerivationStrategy()!).GetDerivation(keyPath).ScriptPubKey + }; + } +}