From 05c874ce1fa06a962d8e60260b3c2548e9ebf751 Mon Sep 17 00:00:00 2001 From: Marcos Date: Wed, 7 Oct 2026 15:33:46 +0200 Subject: [PATCH 1/2] fix: update wallet funding logic to ensure fees and dust change are accounted for --- docs/auto-channel-open.md | 15 +++-- src/Helpers/LightningHelper.cs | 25 ++++++++ src/Jobs/AutoChannelOpenJob.cs | 27 ++++++--- src/Services/ChannelOpenInitiatorService.cs | 10 ++-- .../Helpers/LightningHelperTests.cs | 59 +++++++++++++++++++ .../Jobs/AutoChannelOpenJobTests.cs | 50 ++++++++++++++-- .../ChannelOpenInitiatorServiceTests.cs | 2 +- .../Services/CoinSelectionServiceTests.cs | 26 ++------ test/NodeGuard.Tests/TestHelpers/TestUtxos.cs | 43 ++++++++++++++ 9 files changed, 209 insertions(+), 48 deletions(-) create mode 100644 test/NodeGuard.Tests/TestHelpers/TestUtxos.cs diff --git a/docs/auto-channel-open.md b/docs/auto-channel-open.md index 289a92f51..47d48a2c2 100644 --- a/docs/auto-channel-open.md +++ b/docs/auto-channel-open.md @@ -216,9 +216,16 @@ Applied in this order. `BindingClamp` records the last one that reduced the size | Reserve | `target / 0.99`. LND keeps ~1% as channel reserve, which can't be used for routing. Without this the usable outbound falls short of the target. Not reported as a clamp. | | Wumbo ceiling | 16,777,215 sats. **Regtest only.** On other networks wumbo is assumed. | | Node max | `AutoChannelOpenMaxSizeSats` | -| Wallet | confirmed balance of the funding wallet | +| Wallet | the biggest channel the funding wallet can fund, after the funding fee and a dust change output (below) | | Budget | remaining budget for the period (§7) | +The wallet limit (`LightningHelper.MaxFundableChannelSats`) matches the open that actually runs. That +open isn't changeless: it pays the fee on top of the channel amount and keeps a change output. So the +limit is the coins coin selection would use (no locked, frozen or dust UTXOs), minus the fee for +spending all of them into the funding output plus a change output, minus `MINIMUM_UTXO_VALUE_SATS` +(546) so the change stays above dust. NBitcoin sizes the transaction from the wallet's real scripts, +at `HourFee`, which is at or above the `EconomyFee` the funding transaction uses. + Then two checks on the final size. Failing either one means no recommendation, and the reason is logged: @@ -467,9 +474,6 @@ finished yet blocks a second one. A pending open to the same peer created by han **Peer reachability isn't checked.** If the peer is offline, `ChannelOpenJob` fails, the recommendation becomes `Failed`, and the next run can propose it again. -**The wallet clamp leaves no room for fees.** A plan can be sized to the wallet's full confirmed -balance, which doesn't leave enough to pay for the funding transaction. - **No coordination with the other tools.** The rebalancer may be refilling the same peer while this proposes buying capacity for it. The only thing shared is the price: the new channel opens at what we already charge that peer. @@ -488,8 +492,7 @@ cost. Cost of capital and how long the channel stays open aren't considered. 2. **Payback model.** Replace the flat fee threshold with amortized cost (open + close + cost of capital over the expected lifetime), and use the same model for sizing. 3. **Escalation ladder.** Only propose an open after rebalancing has clearly failed. -4. **Fee headroom in the wallet clamp**, and a reachability check (`ListPeers` / `ConnectPeer`) - before promoting. +4. **Reachability check** (`ListPeers` / `ConnectPeer`) before promoting. 5. **Group bursts by timelock.** Treat (burst, `OutgoingTimelock`) as one payment and take its largest amount. First check prod data: count distinct timelocks per burst, and whether amounts under one timelock look like halving chains or unrelated payments. 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 index a1cb4fc7f..5a9b68fd6 100644 --- a/src/Jobs/AutoChannelOpenJob.cs +++ b/src/Jobs/AutoChannelOpenJob.cs @@ -52,6 +52,7 @@ public class AutoChannelOpenJob : IJob private readonly INBXplorerService _nbXplorerService; private readonly IChannelOperationRequestRepository _channelOperationRequestRepository; private readonly IAuditService _auditService; + private readonly ICoinSelectionService _coinSelectionService; public AutoChannelOpenJob( ILogger logger, @@ -62,7 +63,8 @@ public AutoChannelOpenJob( ILightningService lightningService, INBXplorerService nbXplorerService, IChannelOperationRequestRepository channelOperationRequestRepository, - IAuditService auditService) + IAuditService auditService, + ICoinSelectionService coinSelectionService) { _logger = logger; _nodeRepository = nodeRepository; @@ -73,6 +75,7 @@ public AutoChannelOpenJob( _nbXplorerService = nbXplorerService; _channelOperationRequestRepository = channelOperationRequestRepository; _auditService = auditService; + _coinSelectionService = coinSelectionService; } public async Task Execute(IJobExecutionContext context) @@ -170,16 +173,16 @@ private async Task ProcessNode(Node node, decimal feeRate) return; } - var walletBalanceSats = await GetWalletBalanceSats(node); - if (walletBalanceSats <= 0) + var walletSpendableSats = await GetWalletSpendableSats(node, feeRate); + if (walletSpendableSats <= 0) { - _logger.LogInformation("Node {NodeName}: funding wallet has no confirmed balance", node.Name); + _logger.LogInformation("Node {NodeName}: funding wallet has nothing spendable once the funding fee is paid", node.Name); return; } var tunables = ChannelOpenInitiatorTunables.FromConstants( node, - walletBalanceSats, + walletSpendableSats, remainingBudget, (long)(feeRate * EstimatedOpenCloseVBytes)); @@ -303,16 +306,22 @@ private async Task ProcessNode(Node node, decimal feeRate) return failures.FirstOrDefault(x => ids.Contains(x.OutgoingChannelId))?.OutgoingPeerAlias; } - private async Task GetWalletBalanceSats(Node node) + /// + /// The biggest channel the wallet can fund from the coins coin selection would hand it, with the + /// funding fee already taken out. + /// + /// HourFee, at or above the EconomyFee the funding tx is built at. + private async Task GetWalletSpendableSats(Node node, decimal feeRate) { - if (node.AutoChannelOpenWallet == null) + var derivationStrategy = node.AutoChannelOpenWallet?.GetDerivationStrategy(); + if (derivationStrategy == null) { return 0; } - var balance = await _lightningService.GetWalletBalance(node.AutoChannelOpenWallet); + var utxos = await _coinSelectionService.GetAvailableUTXOsAsync(derivationStrategy); - return balance?.Confirmed is Money confirmed ? confirmed.Satoshi : 0; + return LightningHelper.MaxFundableChannelSats(derivationStrategy, utxos, feeRate); } /// diff --git a/src/Services/ChannelOpenInitiatorService.cs b/src/Services/ChannelOpenInitiatorService.cs index f8d91f7c2..ef8b543d7 100644 --- a/src/Services/ChannelOpenInitiatorService.cs +++ b/src/Services/ChannelOpenInitiatorService.cs @@ -56,14 +56,14 @@ public record ChannelOpenInitiatorTunables( bool AllowWumbo, long NodeMinSizeSats, long NodeMaxSizeSats, - long WalletBalanceSats, + long WalletSpendableSats, long RemainingBudgetSats, long EstimatedChainCostSats, int MaxPlansPerRun) { public static ChannelOpenInitiatorTunables FromConstants( Node node, - long walletBalanceSats, + long walletSpendableSats, long remainingBudgetSats, long estimatedChainCostSats) => new( WindowHours: Constants.AUTO_CHANNEL_OPEN_WINDOW_HOURS, @@ -78,7 +78,7 @@ public static ChannelOpenInitiatorTunables FromConstants( AllowWumbo: CurrentNetworkHelper.GetCurrentNetwork() != Network.RegTest, NodeMinSizeSats: node.AutoChannelOpenMinSizeSats ?? 0, NodeMaxSizeSats: node.AutoChannelOpenMaxSizeSats ?? long.MaxValue, - WalletBalanceSats: walletBalanceSats, + WalletSpendableSats: walletSpendableSats, RemainingBudgetSats: remainingBudgetSats, EstimatedChainCostSats: estimatedChainCostSats, MaxPlansPerRun: Constants.AUTO_CHANNEL_OPEN_MAX_PLANS_PER_RUN); @@ -300,9 +300,9 @@ internal static (long Capacity, ChannelOpenSizingRegime Regime, ChannelOpenBindi clamp = ChannelOpenBindingClamp.NodeMax; } - if (target > t.WalletBalanceSats) + if (target > t.WalletSpendableSats) { - target = t.WalletBalanceSats; + target = t.WalletSpendableSats; clamp = ChannelOpenBindingClamp.WalletBalance; } 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 index b2b84adf9..e36ec58d8 100644 --- a/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs +++ b/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs @@ -20,11 +20,13 @@ using FluentAssertions; using Microsoft.Extensions.Logging; using NBitcoin; +using NBXplorer.DerivationStrategy; using NBXplorer.Models; using NodeGuard.Data.Models; using NodeGuard.Data.Repositories.Interfaces; using NodeGuard.Helpers; using NodeGuard.Services; +using NodeGuard.TestHelpers; using NodeGuard.Tests.Jobs; using Quartz; @@ -61,6 +63,7 @@ public class AutoChannelOpenJobTests private readonly Mock _nbXplorerService = new(); private readonly Mock _channelOperationRequestRepository = new(); private readonly Mock _auditService = new(); + private readonly Mock _coinSelectionService = new(); private AutoChannelOpenJob BuildJob() => new( @@ -72,7 +75,8 @@ private AutoChannelOpenJob BuildJob() => _lightningService.Object, _nbXplorerService.Object, _channelOperationRequestRepository.Object, - _auditService.Object); + _auditService.Object, + _coinSelectionService.Object); /// /// Both switches are process-wide statics, so they are set and restored around every run to keep @@ -104,7 +108,7 @@ private Node ArrangeQualifyingDemand( long budgetSats = 1_000_000_000, long committedSats = 0, bool dryRun = false, - long walletBalanceSats = 1_000_000_000, + long[]? walletUtxoSats = null, bool secondPeer = false) { var node = new Node @@ -115,7 +119,7 @@ private Node ArrangeQualifyingDemand( AutoChannelOpenEnabled = true, AutoChannelOpenMode = mode, AutoChannelOpenWalletId = 3, - AutoChannelOpenWallet = new Wallet { Id = 3 }, + AutoChannelOpenWallet = FundingWallet(), AutoChannelOpenBudgetSats = budgetSats, AutoChannelOpenBudgetStartDatetime = DateTimeOffset.UtcNow.AddHours(-1), RoutingEngineDryRun = dryRun, @@ -180,8 +184,11 @@ private Node ArrangeQualifyingDemand( _recommendationRepository.Setup(x => x.GetLastDecisionByPeer(NodeId)) .ReturnsAsync(new Dictionary()); - _lightningService.Setup(x => x.GetWalletBalance(It.IsAny())) - .ReturnsAsync(new GetBalanceResponse { Confirmed = Money.Satoshis(walletBalanceSats) }); + 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); @@ -192,6 +199,13 @@ private Node ArrangeQualifyingDemand( return node; } + 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())) @@ -304,13 +318,37 @@ public async Task Execute_BudgetExhausted_StillExpiresAndRecordsNothing() [Fact] public async Task Execute_FundingWalletEmpty_RecordsNothing() { - ArrangeQualifyingDemand(walletBalanceSats: 0); + ArrangeQualifyingDemand(walletUtxoSats: []); await Run(); VerifyRecorded(Times.Never()); } + [Fact] + public async Task Execute_FundingWalletCannotCoverTheFundingFee_RecordsNothing() + { + // 10 sat/vB × 153 vB (one P2WPKH in, funding and change out) + 546 sats of change against a 1,000 sat coin + ArrangeQualifyingDemand(walletUtxoSats: [1_000]); + + await Run(); + + VerifyRecorded(Times.Never()); + } + + [Fact] + public async Task Execute_WalletBinds_LeavesRoomForTheFeeAndChange() + { + // 10 sat/vB × 221 vB = 2,210 sats of fee, plus a 546 sat change output so the open still relays + ArrangeQualifyingDemand(walletUtxoSats: [6_000_000, 4_000_000]); + + await Run(); + + _recommendationRepository.Verify(x => x.Upsert(It.Is(r => + r.SuggestedCapacitySats == 10_000_000 - 2_210 - 546 + && r.BindingClamp == ChannelOpenBindingClamp.WalletBalance)), Times.Once); + } + // ── Record, audit, promote ───────────────────────────────────────────────────────── [Fact] diff --git a/test/NodeGuard.Tests/Services/ChannelOpenInitiatorServiceTests.cs b/test/NodeGuard.Tests/Services/ChannelOpenInitiatorServiceTests.cs index 3b3147544..1ca7b86f5 100644 --- a/test/NodeGuard.Tests/Services/ChannelOpenInitiatorServiceTests.cs +++ b/test/NodeGuard.Tests/Services/ChannelOpenInitiatorServiceTests.cs @@ -51,7 +51,7 @@ private static ChannelOpenInitiatorTunables Tunables( AllowWumbo: allowWumbo, NodeMinSizeSats: nodeMin, NodeMaxSizeSats: nodeMax, - WalletBalanceSats: walletBalance, + WalletSpendableSats: walletBalance, RemainingBudgetSats: remainingBudget, EstimatedChainCostSats: chainCost, MaxPlansPerRun: maxPlans); diff --git a/test/NodeGuard.Tests/Services/CoinSelectionServiceTests.cs b/test/NodeGuard.Tests/Services/CoinSelectionServiceTests.cs index a5c03790f..b403ae0bd 100644 --- a/test/NodeGuard.Tests/Services/CoinSelectionServiceTests.cs +++ b/test/NodeGuard.Tests/Services/CoinSelectionServiceTests.cs @@ -439,22 +439,6 @@ public async Task GetAvailableUTXOsAsync_ExcludesDustAndLockedUTXOs() availableUTXOs[0].Outpoint.Should().Be(availableUtxo.Outpoint); } - /// A UTXO complete enough for LightningHelper.SelectCoins to turn it into a coin. - private static UTXO CreateSpendableUtxo(Wallet wallet, uint index, long satoshis, int confirmations = 1) - { - var keyPath = KeyPath.Parse($"0/{index}"); - - return new UTXO - { - Outpoint = new OutPoint(new uint256(index), 0), - Value = new Money(satoshis), - Confirmations = confirmations, - KeyPath = keyPath, - ScriptPubKey = (wallet.GetDerivationStrategy() as StandardDerivationStrategyBase)! - .GetDerivation(keyPath).ScriptPubKey - }; - } - private static WalletWithdrawalRequest CreateRequest(Wallet wallet, decimal amountBtc) { return new WalletWithdrawalRequest @@ -481,9 +465,9 @@ public async Task GetTxInputCoins_WithStrategy_SelectsInTheOrderNBXplorerReturns // SelectUTXOsByOldest pops in ascending confirmations, so it would take the 100k UTXO on its // own. Following NBXplorer's order instead takes the two small ones. - var small = CreateSpendableUtxo(wallet, 1, 6_000, confirmations: 2); - var smaller = CreateSpendableUtxo(wallet, 2, 5_000, confirmations: 3); - var big = CreateSpendableUtxo(wallet, 3, 100_000, confirmations: 1); + var small = TestUtxos.Spendable(wallet, 1, 6_000, confirmations: 2); + var smaller = TestUtxos.Spendable(wallet, 2, 5_000, confirmations: 3); + var big = TestUtxos.Spendable(wallet, 3, 100_000, confirmations: 1); var fmutxoRepository = new Mock(); fmutxoRepository.Setup(x => x.GetLockedUTXOs(null, null)).ReturnsAsync(new List()); @@ -537,7 +521,7 @@ public async Task GetTxInputCoins_WithoutStrategy_KeepsTheOldestFirstSelection() // Arrange var wallet = CreateWallet.SingleSig(_internalWallet); var derivationStrategy = wallet.GetDerivationStrategy(); - var utxo = CreateSpendableUtxo(wallet, 1, 100_000); + var utxo = TestUtxos.Spendable(wallet, 1, 100_000); var nbXplorerService = new Mock(); var coinSelectionService = new CoinSelectionService(_logger, new Mock().Object, @@ -568,7 +552,7 @@ public async Task GetTxInputCoins_WithStrategy_ReturnsNothingWhenTheSetIsShort() // Arrange var wallet = CreateWallet.SingleSig(_internalWallet); var derivationStrategy = wallet.GetDerivationStrategy(); - var utxo = CreateSpendableUtxo(wallet, 1, 1_000); + var utxo = TestUtxos.Spendable(wallet, 1, 1_000); var fmutxoRepository = new Mock(); fmutxoRepository.Setup(x => x.GetLockedUTXOs(null, null)).ReturnsAsync(new List()); 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 + }; + } +} From 5bb1c3e943261c6c1e9975b91fd9a9c9c27de6d6 Mon Sep 17 00:00:00 2001 From: Marcos Date: Wed, 7 Oct 2026 15:49:33 +0200 Subject: [PATCH 2/2] test: add e2e for this case --- .../E2E/AutoChannelOpenE2ETests.cs | 405 ++++++++++++------ 1 file changed, 283 insertions(+), 122 deletions(-) diff --git a/test/NodeGuard.Tests/E2E/AutoChannelOpenE2ETests.cs b/test/NodeGuard.Tests/E2E/AutoChannelOpenE2ETests.cs index 4ff697379..50d5d8f02 100644 --- a/test/NodeGuard.Tests/E2E/AutoChannelOpenE2ETests.cs +++ b/test/NodeGuard.Tests/E2E/AutoChannelOpenE2ETests.cs @@ -21,7 +21,11 @@ using Lnrpc; using Microsoft.EntityFrameworkCore; using NodeGuard.Data.Models; +using NBitcoin; +using NBXplorer; +using NBXplorer.DerivationStrategy; using NodeGuard.Helpers; +using NodeGuard.TestHelpers; using Xunit.Abstractions; namespace NodeGuard.Tests.E2E; @@ -60,6 +64,12 @@ public class AutoChannelOpenE2ETests : RoutingEngineE2EBase private const double CostToEarnRatio = 1_000; private const long BudgetSats = 50_000_000; + // Two coins under the plan's ~4M sats, so the wallet clamp is what binds and the open spends both + private static readonly long[] SmallWalletCoinSats = [1_500_000, 1_300_000]; + private const string SmallWalletName = "E2E auto channel open small wallet"; + // An internal-wallet account no seeded wallet uses, so its addresses never collide with theirs + private const string SmallWalletAccountId = "77"; + private const int JobWaitAttempts = 150; // 5 min of 2s polls; the job runs every ROUTING_ENGINE_JOB_INTERVAL_SECONDS public AutoChannelOpenE2ETests(ITestOutputHelper output) : base(output) @@ -69,136 +79,21 @@ public AutoChannelOpenE2ETests(ITestOutputHelper output) : base(output) [E2EFact, Trait("Speed", "Slow")] public async Task AutoChannelOpen_RefusedForwardsToDrainedPeer_OpensSecondChannelAtInheritedFee() { - var client = CreateClient(out var headers); - var rpc = CreateBitcoindRpc(); - - var nodes = await WaitForNodesAsync(client, headers); - var aliceNode = nodes.Single(n => n.Name == "alice"); - var bobNode = nodes.Single(n => n.Name == "bob"); - var carolNode = nodes.Single(n => n.Name == "carol"); - _output.WriteLine($"alice={aliceNode.PubKey} bob={bobNode.PubKey} carol={carolNode.PubKey}"); - - var alice = LndTestClient.FromEnv("alice", aliceNode.PubKey); - var bob = LndTestClient.FromEnv("bob", bobNode.PubKey); - var carol = LndTestClient.FromEnv("carol", carolNode.PubKey); + var scenario = await LoadScenarioAsync(); + var (client, headers, rpc) = (scenario.Client, scenario.Headers, scenario.Rpc); + var (bob, carolNode) = (scenario.Bob, scenario.Carol); + var (bobNodeId, carolNodeId) = (scenario.BobNodeId, scenario.CarolNodeId); var walletId = int.Parse(Env("E2E_HOT_WALLET_ID", "3")); - int bobNodeId, carolNodeId; - bool bobDynamicFees; - await using (var db = CreateDbContext()) - { - var bobRow = await db.Nodes.AsNoTracking().SingleAsync(n => n.PubKey == bobNode.PubKey); - bobNodeId = bobRow.Id; - bobDynamicFees = bobRow.DynamicFeeManagementEnabled; - carolNodeId = await db.Nodes.AsNoTracking().Where(n => n.PubKey == carolNode.PubKey) - .Select(n => n.Id).SingleAsync(); - } - try { - await ResetAutoChannelOpenAsync(bobNodeId, dynamicFees: false); - - var aliceToBobScid = await ResolveAliceToBobAsync(client, headers, rpc, alice, bobNode.PubKey); - _output.WriteLine($"[setup] alice→bob first hop scid {aliceToBobScid}"); - - await DrainUsableLocalAsync(bob, carol); - - // After the drain, so bob's own settled sends to carol can't read as settled outbound demand - await Task.Delay(TimeSpan.FromSeconds(3)); - await ResetRoutingEngineStateAsync(); - - // The planner prices by the dearest of bob's carol channels, off FeeReport - var carolScids = (await bob.ChannelsToAsync(carolNode.PubKey)).Select(c => c.ChanId).ToHashSet(); - var policies = new List(); - foreach (var scid in carolScids) - { - var policy = await bob.OutboundPolicyAsync(scid); - if (policy != null) policies.Add(policy); - } - var dearest = policies.MaxBy(p => p.FeePerMil); - dearest.Should().NotBeNull("bob must report an outbound policy toward carol, or nothing can be priced"); - dearest!.FeePerMil.Should().BePositive("a zero-ppm peer earns nothing and is never planned"); - _output.WriteLine($"[setup] bob's dearest carol policy: {dearest.FeePerMil} ppm / {dearest.BaseFeeMsat} msat on scid {dearest.ChanId}"); - - await SendRefusedBurstsAsync(alice, bob, carol, aliceToBobScid); - - var failures = await PollAsync( - async () => - { - await using var db = CreateDbContext(); - return await db.ForwardingHtlcEvents.AsNoTracking() - .Where(e => e.ManagedNodePubKey == bobNode.PubKey - && e.EventType == HtlcEventType.Forward - && e.EventCase == HtlcEventCase.LinkFailEvent - && e.FailureDetail == (int)Routerrpc.FailureDetail.InsufficientBalance) - .ToListAsync(); - }, - rows => rows.Count >= Bursts * AttemptsPerBurst, - attempts: 20, delay: TimeSpan.FromSeconds(3), - what: "NodeHtlcSubscribeJob recorded bob's refused forwards"); - failures.Should().HaveCount(Bursts * AttemptsPerBurst, "every refused attempt is one LinkFailEvent row"); - failures.Should().OnlyContain(e => e.OutgoingAmountMsat == (ulong)RefusedPaymentSats * 1_000); - failures.Should().OnlyContain(e => carolScids.Contains(e.OutgoingChannelId), - "the refusing link is one of bob's channels to carol"); - - var eventPpm = failures.Max(e => e.RoutingFeePpm) ?? dearest.FeePerMil; - var expectedMissedFeeMsat = Bursts * (RefusedPaymentSats * 1_000 * eventPpm / 1_000_000); - expectedMissedFeeMsat.Should().BeGreaterThanOrEqualTo(Constants.AUTO_CHANNEL_OPEN_MIN_MISSED_FEE_MSAT, - "the shaped demand must clear the fee gate, or there is nothing for the job to plan"); + var (carolScids, dearest, expectedMissedFeeMsat) = await ShapeRefusedDemandAsync(scenario); // Earlier scenarios leave unconfirmed change in the hot wallet; with no spendable coin the first // promotion fails and a later cycle re-promotes the same row onto a new request await MineAsync(rpc, 6); - // Only now, so no run can see a partial burst set and plan off it - await using (var db = CreateDbContext()) - { - var updated = await db.Nodes - .Where(n => n.Id == bobNodeId) - .ExecuteUpdateAsync(s => s - .SetProperty(n => n.AutoChannelOpenEnabled, true) - .SetProperty(n => n.AutoChannelOpenMode, AutoChannelOpenMode.Auto) - .SetProperty(n => n.AutoChannelOpenWalletId, (int?)walletId) - .SetProperty(n => n.AutoChannelOpenBudgetSats, (long?)BudgetSats) - // Null start ⇒ a fresh period, so opens from other scenarios don't count against it - .SetProperty(n => n.AutoChannelOpenBudgetStartDatetime, (DateTimeOffset?)null) - .SetProperty(n => n.AutoChannelOpenBudgetRefreshInterval, (TimeSpan?)null) - .SetProperty(n => n.AutoChannelOpenMinSizeSats, (long?)null) - .SetProperty(n => n.AutoChannelOpenMaxSizeSats, (long?)null) - .SetProperty(n => n.MaxChannelOpenCostToEarnRatio, (double?)CostToEarnRatio) - .SetProperty(n => n.RoutingEngineDryRun, false)); - updated.Should().Be(1, "bob should be seeded and have automatic channel opening switched on"); - } - - ChannelOpenRecommendation? recommendation = null; - ChannelOperationRequestStatus? requestStatus = null; - for (var attempt = 0; attempt < JobWaitAttempts; attempt++) - { - await using (var db = CreateDbContext()) - { - recommendation = await db.ChannelOpenRecommendations.AsNoTracking() - .FirstOrDefaultAsync(r => r.NodeId == bobNodeId && r.PeerPubKey == carolNode.PubKey); - requestStatus = recommendation?.ChannelOperationRequestId is { } id - ? await db.ChannelOperationRequests.AsNoTracking().Where(r => r.Id == id) - .Select(r => (ChannelOperationRequestStatus?)r.Status).SingleOrDefaultAsync() - : null; - } - - if (recommendation != null) - _output.WriteLine( - $"[recommendation] #{recommendation.Id} status={recommendation.Status} bursts={recommendation.Bursts} capacity={recommendation.SuggestedCapacitySats} request={recommendation.ChannelOperationRequestId} requestStatus={requestStatus}"); - - // A request that failed before dispatch gets replaced on a later cycle, so wait for a live one - if (recommendation is { Status: ChannelOpenRecommendationStatus.Promoted } - && requestStatus is not ChannelOperationRequestStatus.Failed) break; - - await Task.Delay(TimeSpan.FromSeconds(2)); - } - - recommendation.Should().NotBeNull("AutoChannelOpenJob should have recommended a channel to the drained peer"); - recommendation!.Status.Should().Be(ChannelOpenRecommendationStatus.Promoted, "Auto mode promotes what it recommends"); - requestStatus.Should().NotBe(ChannelOperationRequestStatus.Failed, - "the promoted request must reach dispatch — check NodeGuard's log for the promotion failure reason"); + var recommendation = await EnableAutoAndAwaitPromotionAsync(scenario, walletId); // Evidence: each payment tried twice, all refused recommendation.Bursts.Should().Be(Bursts); @@ -268,8 +163,274 @@ public async Task AutoChannelOpen_RefusedForwardsToDrainedPeer_OpensSecondChanne } finally { - await ResetAutoChannelOpenAsync(bobNodeId, dynamicFees: bobDynamicFees); + await ResetAutoChannelOpenAsync(bobNodeId, dynamicFees: scenario.BobDynamicFees); + } + } + + /// + /// The wallet clamp's own case: a funding wallet too small for the plan. The channel must be sized to + /// what the wallet can fund and still open, with every coin spent and change left above dust. + /// + [E2EFact, Trait("Speed", "Slow")] + public async Task AutoChannelOpen_FundingWalletSmallerThanThePlan_OpensTheBiggestChannelItCanFund() + { + var scenario = await LoadScenarioAsync(); + var (client, headers, rpc) = (scenario.Client, scenario.Headers, scenario.Rpc); + + try + { + // Funding mines first, so a channel an earlier scenario left pending confirms before the + // drain sees it rather than after, when it would refill bob's outbound and void the demand + var (walletId, coins) = await FundSmallWalletAsync(rpc); + + await ShapeRefusedDemandAsync(scenario); + var walletSats = coins.Sum(c => c.Value); + + var recommendation = await EnableAutoAndAwaitPromotionAsync(scenario, walletId); + + var (unclampedCapacity, _) = ExpectedSize(recommendation); + unclampedCapacity.Should().BeGreaterThan(walletSats, "the plan has to outgrow the wallet for its clamp to bind"); + recommendation.BindingClamp.Should().Be(ChannelOpenBindingClamp.WalletBalance); + recommendation.SuggestedCapacitySats.Should().BeLessThan(walletSats - Constants.MINIMUM_UTXO_VALUE_SATS, + "the clamp holds back the funding fee and a change output"); + _output.WriteLine($"[sizing] wallet {walletSats} sats in {coins.Count} coin(s) → {recommendation.SuggestedCapacitySats} sats (unclamped {unclampedCapacity})"); + + var requestId = recommendation.ChannelOperationRequestId!.Value; + var channelId = (int)await MineUntilChannelOpenedAsync(client, headers, rpc, requestId); + + string fundingTxId; + await using (var db = CreateDbContext()) + { + fundingTxId = await db.Channels.AsNoTracking().Where(c => c.Id == channelId).Select(c => c.FundingTx).SingleAsync(); + } + + var fundingTx = await rpc.GetRawTransactionAsync(uint256.Parse(fundingTxId)); + fundingTx.Inputs.Select(i => i.PrevOut).Should().BeEquivalentTo(coins.Select(c => c.Outpoint), "every coin funds the channel"); + fundingTx.Outputs.Should().HaveCount(2, "a normal open keeps a change output next to the funding one"); + + var channelOutput = fundingTx.Outputs.Single(o => o.Value.Satoshi == recommendation.SuggestedCapacitySats); + var change = fundingTx.Outputs.Single(o => o != channelOutput).Value.Satoshi; + change.Should().BeGreaterThanOrEqualTo(Constants.MINIMUM_UTXO_VALUE_SATS, "a dust change output would not relay"); + _output.WriteLine($"[result] funding tx {fundingTxId}: channel {channelOutput.Value.Satoshi} sats, change {change} sats"); + } + finally + { + await ResetAutoChannelOpenAsync(scenario.BobNodeId, dynamicFees: scenario.BobDynamicFees); + } + } + + private sealed record Scenario( + Nodeguard.NodeGuardService.NodeGuardServiceClient Client, + Grpc.Core.Metadata Headers, + NBitcoin.RPC.RPCClient Rpc, + LndTestClient Alice, + LndTestClient Bob, + LndTestClient Carol, + int BobNodeId, + int CarolNodeId, + bool BobDynamicFees); + + private async Task LoadScenarioAsync() + { + var client = CreateClient(out var headers); + + var nodes = await WaitForNodesAsync(client, headers); + var aliceNode = nodes.Single(n => n.Name == "alice"); + var bobNode = nodes.Single(n => n.Name == "bob"); + var carolNode = nodes.Single(n => n.Name == "carol"); + _output.WriteLine($"alice={aliceNode.PubKey} bob={bobNode.PubKey} carol={carolNode.PubKey}"); + + await using var db = CreateDbContext(); + var bobRow = await db.Nodes.AsNoTracking().SingleAsync(n => n.PubKey == bobNode.PubKey); + var carolNodeId = await db.Nodes.AsNoTracking().Where(n => n.PubKey == carolNode.PubKey) + .Select(n => n.Id).SingleAsync(); + + return new Scenario( + client, headers, CreateBitcoindRpc(), + LndTestClient.FromEnv("alice", aliceNode.PubKey), + LndTestClient.FromEnv("bob", bobNode.PubKey), + LndTestClient.FromEnv("carol", carolNode.PubKey), + bobRow.Id, carolNodeId, bobRow.DynamicFeeManagementEnabled); + } + + /// + /// Drains bob→carol and has alice send refused payments through it, waiting until + /// every refusal is recorded. Returns bob's carol channels, his dearest policy toward carol, and the + /// missed fee the planner should derive from the refusals. + /// + private async Task<(HashSet CarolScids, ChannelFeeReport Dearest, long ExpectedMissedFeeMsat)> ShapeRefusedDemandAsync(Scenario scenario) + { + var (alice, bob, carol) = (scenario.Alice, scenario.Bob, scenario.Carol); + + await ResetAutoChannelOpenAsync(scenario.BobNodeId, dynamicFees: false); + + var aliceToBobScid = await ResolveAliceToBobAsync(scenario.Client, scenario.Headers, scenario.Rpc, alice, bob.PubKey); + _output.WriteLine($"[setup] alice→bob first hop scid {aliceToBobScid}"); + + await DrainUsableLocalAsync(bob, carol); + + // After the drain, so bob's own settled sends to carol can't read as settled outbound demand + await Task.Delay(TimeSpan.FromSeconds(3)); + await ResetRoutingEngineStateAsync(); + + // The planner prices by the dearest of bob's carol channels, off FeeReport + var carolScids = (await bob.ChannelsToAsync(carol.PubKey)).Select(c => c.ChanId).ToHashSet(); + var policies = new List(); + foreach (var scid in carolScids) + { + var policy = await bob.OutboundPolicyAsync(scid); + if (policy != null) policies.Add(policy); + } + var dearest = policies.MaxBy(p => p.FeePerMil); + dearest.Should().NotBeNull("bob must report an outbound policy toward carol, or nothing can be priced"); + dearest!.FeePerMil.Should().BePositive("a zero-ppm peer earns nothing and is never planned"); + _output.WriteLine($"[setup] bob's dearest carol policy: {dearest.FeePerMil} ppm / {dearest.BaseFeeMsat} msat on scid {dearest.ChanId}"); + + await SendRefusedBurstsAsync(alice, bob, carol, aliceToBobScid); + + var failures = await PollAsync( + async () => + { + await using var db = CreateDbContext(); + return await db.ForwardingHtlcEvents.AsNoTracking() + .Where(e => e.ManagedNodePubKey == bob.PubKey + && e.EventType == HtlcEventType.Forward + && e.EventCase == HtlcEventCase.LinkFailEvent + && e.FailureDetail == (int)Routerrpc.FailureDetail.InsufficientBalance) + .ToListAsync(); + }, + rows => rows.Count >= Bursts * AttemptsPerBurst, + attempts: 20, delay: TimeSpan.FromSeconds(3), + what: "NodeHtlcSubscribeJob recorded bob's refused forwards"); + failures.Should().HaveCount(Bursts * AttemptsPerBurst, "every refused attempt is one LinkFailEvent row"); + failures.Should().OnlyContain(e => e.OutgoingAmountMsat == (ulong)RefusedPaymentSats * 1_000); + failures.Should().OnlyContain(e => carolScids.Contains(e.OutgoingChannelId), + "the refusing link is one of bob's channels to carol"); + + // The planner prefers the fee alice offered over bob's rate: her gossip view of his policy can lag + // the fee engine. Same route every attempt, so one offer; ppm only if no row recorded it. + var offeredFeesMsat = failures.Select(e => e.FeeMsat).Distinct().ToList(); + offeredFeesMsat.Should().ContainSingle("every attempt took the same route at the same price"); + var eventPpm = failures.Max(e => e.RoutingFeePpm) ?? dearest.FeePerMil; + var feePerPaymentMsat = offeredFeesMsat[0] ?? RefusedPaymentSats * 1_000 * eventPpm / 1_000_000; + var expectedMissedFeeMsat = Bursts * feePerPaymentMsat; + expectedMissedFeeMsat.Should().BeGreaterThanOrEqualTo(Constants.AUTO_CHANNEL_OPEN_MIN_MISSED_FEE_MSAT, + "the shaped demand must clear the fee gate, or there is nothing for the job to plan"); + + return (carolScids, dearest, expectedMissedFeeMsat); + } + + /// + /// Only after the demand is in place, so no run can see a partial burst set and plan off it. Waits for + /// the job to record and promote carol's recommendation onto a request that reached dispatch. + /// + private async Task EnableAutoAndAwaitPromotionAsync(Scenario scenario, int walletId) + { + await using (var db = CreateDbContext()) + { + var updated = await db.Nodes + .Where(n => n.Id == scenario.BobNodeId) + .ExecuteUpdateAsync(s => s + .SetProperty(n => n.AutoChannelOpenEnabled, true) + .SetProperty(n => n.AutoChannelOpenMode, AutoChannelOpenMode.Auto) + .SetProperty(n => n.AutoChannelOpenWalletId, (int?)walletId) + .SetProperty(n => n.AutoChannelOpenBudgetSats, (long?)BudgetSats) + // Null start ⇒ a fresh period, so opens from other scenarios don't count against it + .SetProperty(n => n.AutoChannelOpenBudgetStartDatetime, (DateTimeOffset?)null) + .SetProperty(n => n.AutoChannelOpenBudgetRefreshInterval, (TimeSpan?)null) + .SetProperty(n => n.AutoChannelOpenMinSizeSats, (long?)null) + .SetProperty(n => n.AutoChannelOpenMaxSizeSats, (long?)null) + .SetProperty(n => n.MaxChannelOpenCostToEarnRatio, (double?)CostToEarnRatio) + .SetProperty(n => n.RoutingEngineDryRun, false)); + updated.Should().Be(1, "bob should be seeded and have automatic channel opening switched on"); + } + + ChannelOpenRecommendation? recommendation = null; + ChannelOperationRequestStatus? requestStatus = null; + for (var attempt = 0; attempt < JobWaitAttempts; attempt++) + { + await using (var db = CreateDbContext()) + { + recommendation = await db.ChannelOpenRecommendations.AsNoTracking() + .FirstOrDefaultAsync(r => r.NodeId == scenario.BobNodeId && r.PeerPubKey == scenario.Carol.PubKey); + requestStatus = recommendation?.ChannelOperationRequestId is { } id + ? await db.ChannelOperationRequests.AsNoTracking().Where(r => r.Id == id) + .Select(r => (ChannelOperationRequestStatus?)r.Status).SingleOrDefaultAsync() + : null; + } + + if (recommendation != null) + _output.WriteLine( + $"[recommendation] #{recommendation.Id} status={recommendation.Status} bursts={recommendation.Bursts} capacity={recommendation.SuggestedCapacitySats} clamp={recommendation.BindingClamp} request={recommendation.ChannelOperationRequestId} requestStatus={requestStatus}"); + + // A request that failed before dispatch gets replaced on a later cycle, so wait for a live one + if (recommendation is { Status: ChannelOpenRecommendationStatus.Promoted } + && requestStatus is not ChannelOperationRequestStatus.Failed) break; + + await Task.Delay(TimeSpan.FromSeconds(2)); + } + + recommendation.Should().NotBeNull("AutoChannelOpenJob should have recommended a channel to the drained peer"); + recommendation!.Status.Should().Be(ChannelOpenRecommendationStatus.Promoted, "Auto mode promotes what it recommends"); + requestStatus.Should().NotBe(ChannelOperationRequestStatus.Failed, + "the promoted request must reach dispatch — check NodeGuard's log for the promotion failure reason"); + + return recommendation; + } + + /// + /// A hot wallet of its own, so the dev wallet's 20 BTC stays untouched: reused across runs, topped up + /// each time with coins and confirmed. Returns every confirmed coin + /// it holds, leftover change from an earlier run included, since the clamp counts those too. + /// + private async Task<(int WalletId, List<(NBitcoin.OutPoint Outpoint, long Value)> Coins)> FundSmallWalletAsync(NBitcoin.RPC.RPCClient rpc) + { + int walletId; + DerivationStrategyBase derivationStrategy; + await using (var db = CreateDbContext()) + { + var wallet = await db.Wallets.Include(w => w.Keys).FirstOrDefaultAsync(w => w.Name == SmallWalletName); + if (wallet == null) + { + var internalWallet = await db.InternalWallets.AsNoTracking().FirstAsync(); + wallet = CreateWallet.SingleSig(internalWallet, SmallWalletAccountId); + wallet.Name = SmallWalletName; + // Already persisted; the ids are enough and re-attaching would insert it again + wallet.InternalWallet = null; + db.Wallets.Add(wallet); + await db.SaveChangesAsync(); + } + + walletId = wallet.Id; + derivationStrategy = wallet.GetDerivationStrategy()!; + } + + var explorer = new ExplorerClient( + new NBXplorerNetworkProvider(ChainName.Regtest).GetFromCryptoCode("BTC"), + new Uri(Env("NBXPLORER_URI", "http://localhost:32838"))); + await explorer.TrackAsync(derivationStrategy); + + foreach (var sats in SmallWalletCoinSats) + { + var address = (await explorer.GetUnusedAsync(derivationStrategy, DerivationFeature.Deposit, reserve: true)).Address; + await rpc.SendToAddressAsync(address, Money.Satoshis(sats)); } + await MineAsync(rpc, 6); + + var minimumSats = SmallWalletCoinSats.Sum(); + var utxos = await PollAsync( + () => explorer.GetUTXOsAsync(derivationStrategy), + u => u.Confirmed.UTXOs.Sum(x => ((Money)x.Value).Satoshi) >= minimumSats && u.Unconfirmed.UTXOs.Count == 0, + attempts: 30, delay: TimeSpan.FromSeconds(2), + what: $"NBXplorer confirmed the small funding wallet's {SmallWalletCoinSats.Length} new coin(s)"); + + var coins = utxos.Confirmed.UTXOs + .Where(u => ((Money)u.Value).Satoshi > Constants.MINIMUM_UTXO_VALUE_SATS) + .Select(u => (u.Outpoint, ((Money)u.Value).Satoshi)) + .ToList(); + _output.WriteLine($"[setup] small funding wallet #{walletId}: {coins.Count} coin(s), {coins.Sum(c => c.Item2)} sats"); + + return (walletId, coins); } ///