From c06d7b8792cb065f535c338e6012f2ef21f06db8 Mon Sep 17 00:00:00 2001 From: Marcos Date: Wed, 14 Oct 2026 16:30:25 +0200 Subject: [PATCH 1/3] fix: withdrawal stuck when mining previous transaction --- docker/e2e/README.md | 3 + .../WalletWithdrawalRequestRepository.cs | 28 ++- src/Jobs/MonitorWithdrawalsJob.cs | 10 +- src/Jobs/PerformWithdrawalJob.cs | 36 +-- src/Pages/Withdrawals.razor | 7 +- src/Services/WithdrawalRequestService.cs | 73 +++++- .../WalletWithdrawalRequestRepositoryTests.cs | 156 +++++++++++++ .../E2E/WithdrawalRbfBumpE2ETests.cs | 212 +++++++++++++++++- .../Jobs/MonitorWithdrawalsJobTests.cs | 147 ++++++++++++ .../Jobs/PerformWithdrawalJobTests.cs | 154 +++++++++++++ .../Services/WithdrawalRequestServiceTests.cs | 112 +++++++++ .../TestHelpers/TestEnvironment.cs | 2 + 12 files changed, 903 insertions(+), 37 deletions(-) create mode 100644 test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestRepositoryTests.cs create mode 100644 test/NodeGuard.Tests/Jobs/MonitorWithdrawalsJobTests.cs create mode 100644 test/NodeGuard.Tests/Jobs/PerformWithdrawalJobTests.cs diff --git a/docker/e2e/README.md b/docker/e2e/README.md index 1ba02acdf..06b5a84ed 100644 --- a/docker/e2e/README.md +++ b/docker/e2e/README.md @@ -73,6 +73,9 @@ tests (`DustUtxoWithdrawalE2ETests`, `WithdrawalRbfBumpE2ETests`, `GetNewWalletA over gRPC, asserting bitcoind evicts the original for the higher-fee replacement, NodeGuard marks the original `WITHDRAWAL_BUMPED`, and the replacement settles once mined. It relies on `MONITOR_WITHDRAWALS_CRON` being fast on the `nodeguard` service (10s here; prod keeps the every-5-minutes default) and never mines between the two calls. + The mined-original theory mines the ORIGINAL with `generateblock` (raw tx, bypassing the mempool) after a bump or + cancel, and asserts NodeGuard settles the original and fails the replacement. The bump-of-a-bump test does the same + with three transactions (A bumped to B, B to C, A mined): A settles, C fails, B stays bumped. - **Adding an e2e test**: put it in `[Collection("E2E")]` (so it serialises with the others on the one regtest chain — without it the class runs in parallel and they interfere), have it provision the resources it needs and reset its own state, and gate it with `[E2EFact]`. diff --git a/src/Data/Repositories/WalletWithdrawalRequestRepository.cs b/src/Data/Repositories/WalletWithdrawalRequestRepository.cs index 9f2a20798..5da905049 100644 --- a/src/Data/Repositories/WalletWithdrawalRequestRepository.cs +++ b/src/Data/Repositories/WalletWithdrawalRequestRepository.cs @@ -83,17 +83,41 @@ public async Task> GetByReferenceIds(List await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); // RBF replacements inherit the reference id of the request they replace, so a reference id can match a whole - // chain of requests. Only the latest one of each chain reflects the current status of the withdrawal. + // chain of requests. The latest one reflects the current status of the withdrawal, unless a request it + // replaced was mined instead: that one is the payment that happened. var requests = await applicationDbContext.WalletWithdrawalRequests .Where(wr => !string.IsNullOrEmpty(wr.ReferenceId) && referenceIds.Contains(wr.ReferenceId)) .ToListAsync(); return requests .GroupBy(wr => wr.ReferenceId!) - .Select(g => g.OrderByDescending(wr => wr.Id).First()) + .Select(g => SettledInChainOrLatest(g.ToList())) .ToList(); } + /// + /// Walks back from the latest request through the requests it replaced, and returns the settled one if any. + /// Only that chain: reference ids are not unique, so an unrelated earlier withdrawal must not stand in for it. + /// + private static WalletWithdrawalRequest SettledInChainOrLatest(List sameReference) + { + var byId = sameReference.ToDictionary(wr => wr.Id); + var latest = sameReference.MaxBy(wr => wr.Id)!; + + var request = latest; + while (request != null) + { + if (request.Status == WalletWithdrawalRequestStatus.OnChainConfirmed) return request; + + // A replacement is always newer than what it replaces, so ids only go down and the walk ends. + request = request.BumpingWalletWithdrawalRequestId is { } replacedId && replacedId < request.Id + ? byId.GetValueOrDefault(replacedId) + : null; + } + + return latest; + } + public async Task GetByTxHash(string txHash) { await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); diff --git a/src/Jobs/MonitorWithdrawalsJob.cs b/src/Jobs/MonitorWithdrawalsJob.cs index c1ecf2d46..6955f9276 100644 --- a/src/Jobs/MonitorWithdrawalsJob.cs +++ b/src/Jobs/MonitorWithdrawalsJob.cs @@ -34,15 +34,18 @@ public class MonitorWithdrawalsJob : IJob private readonly ILogger _logger; private readonly IWalletWithdrawalRequestRepository _walletWithdrawalRequestRepository; private readonly INBXplorerService _nbXplorerService; + private readonly IWithdrawalRequestService _withdrawalRequestService; public MonitorWithdrawalsJob(ILogger logger, IWalletWithdrawalRequestRepository walletWithdrawalRequestRepository, - INBXplorerService nbXplorerService + INBXplorerService nbXplorerService, + IWithdrawalRequestService withdrawalRequestService ) { _logger = logger; _walletWithdrawalRequestRepository = walletWithdrawalRequestRepository; _nbXplorerService = nbXplorerService; + _withdrawalRequestService = withdrawalRequestService; } public async Task Execute(IJobExecutionContext context) @@ -79,6 +82,11 @@ public async Task Execute(IJobExecutionContext context) walletWithdrawalRequest.Id, walletWithdrawalRequest.Status); } } + else if (walletWithdrawalRequest.BumpingWalletWithdrawalRequestId != null && getTxResult.Confirmations == 0) + { + // An RBF replacement can lose the race: the transaction it replaced may be mined instead. + await _withdrawalRequestService.SettleMinedOriginalAsync(walletWithdrawalRequest); + } } catch (Exception e) { diff --git a/src/Jobs/PerformWithdrawalJob.cs b/src/Jobs/PerformWithdrawalJob.cs index ba016d3cd..8a3566444 100644 --- a/src/Jobs/PerformWithdrawalJob.cs +++ b/src/Jobs/PerformWithdrawalJob.cs @@ -36,13 +36,16 @@ public class PerformWithdrawalJob : IJob private readonly ILogger _logger; private readonly IBitcoinService _bitcoinService; private readonly IWalletWithdrawalRequestRepository _walletWithdrawalRequestRepository; + private readonly IWithdrawalRequestService _withdrawalRequestService; - public PerformWithdrawalJob(ILogger logger, IBitcoinService bitcoinService, IWalletWithdrawalRequestRepository walletWithdrawalRequestRepository) + public PerformWithdrawalJob(ILogger logger, IBitcoinService bitcoinService, + IWalletWithdrawalRequestRepository walletWithdrawalRequestRepository, IWithdrawalRequestService withdrawalRequestService) { _logger = logger; _bitcoinService = bitcoinService; _walletWithdrawalRequestRepository = walletWithdrawalRequestRepository; + _withdrawalRequestService = withdrawalRequestService; } public async Task Execute(IJobExecutionContext context) @@ -58,36 +61,19 @@ public async Task Execute(IJobExecutionContext context) catch (Exception e) { var request = await _walletWithdrawalRequestRepository.GetById(withdrawalRequestId); - - // If an error occurs and the wd was bumping another one, we need to update the status of the withdrawal request to previous status - if (request != null && request!.BumpingWalletWithdrawalRequestId.HasValue) + if (request != null) { - var bumped = await _walletWithdrawalRequestRepository.GetById(request.BumpingWalletWithdrawalRequestId.Value); - if (bumped == null) - { - _logger.LogError("Failed to find withdrawal request with ID {WithdrawalRequestId}", withdrawalRequestId); - return; - } + // A failed replacement gives the request it replaced back its pending-confirmation status. + await _withdrawalRequestService.RevertOriginalAsync(request); - bumped.Status = WalletWithdrawalRequestStatus.OnChainConfirmationPending; - var (ok, _) = _walletWithdrawalRequestRepository.Update(bumped); - if (!ok) - { - _logger.LogError("Failed to update withdrawal request status to OnChainConfirmationPending for ID {WithdrawalRequestId}", withdrawalRequestId); - } - else + request.Status = WalletWithdrawalRequestStatus.Failed; + var (updated, _) = _walletWithdrawalRequestRepository.Update(request); + if (!updated) { - _logger.LogInformation("Updated withdrawal request status to OnChainConfirmationPending for ID {WithdrawalRequestId}", withdrawalRequestId); + _logger.LogError("Failed to update withdrawal request status to failed"); } } - request!.Status = WalletWithdrawalRequestStatus.Failed; - var (updated, _) = _walletWithdrawalRequestRepository.Update(request); - if (!updated) - { - _logger.LogError("Failed to update withdrawal request status to failed"); - } - _logger.LogError(e, "Error on {JobName}", nameof(PerformWithdrawalJob)); } diff --git a/src/Pages/Withdrawals.razor b/src/Pages/Withdrawals.razor index 23ae6b6a6..a7a98c9b0 100644 --- a/src/Pages/Withdrawals.razor +++ b/src/Pages/Withdrawals.razor @@ -1072,10 +1072,13 @@ _selectedRequest = await WalletWithdrawalRequestRepository.GetById(_selectedRequest.Id); if (_selectedRequest != null) { + // Mark the replaced request before the job runs, so a failed broadcast's revert has the last word. + await WithdrawalRequestService.MarkOriginalAsReplacedAsync(_selectedRequest); await CreateJob(); - if (_selectedRequest?.BumpingWalletWithdrawalRequestId != null) + // CreateJob reports a scheduling failure by failing the request. + if (_selectedRequest?.Status == WalletWithdrawalRequestStatus.Failed) { - await WithdrawalRequestService.MarkOriginalAsReplacedAsync(_selectedRequest); + await WithdrawalRequestService.RevertOriginalAsync(_selectedRequest); } } } diff --git a/src/Services/WithdrawalRequestService.cs b/src/Services/WithdrawalRequestService.cs index 686c9673c..d5e271b6d 100644 --- a/src/Services/WithdrawalRequestService.cs +++ b/src/Services/WithdrawalRequestService.cs @@ -67,8 +67,8 @@ Task CreateCancelRequestAsync(int originalRequestId, Me /// /// Marks the request replaced by as Bumped (fee bump) or Cancelled (RBF cancellation). - /// Cold-wallet flow: called when the last human signature lands and the withdrawal job is scheduled. No-op when the - /// request is not a replacement. + /// Cold-wallet flow: called when the last human signature lands, before the withdrawal job is scheduled. No-op when + /// the request is not a replacement or the replaced request is no longer pending confirmation. /// Task MarkOriginalAsReplacedAsync(WalletWithdrawalRequest replacement); @@ -78,6 +78,13 @@ Task CreateCancelRequestAsync(int originalRequestId, Me /// No-op otherwise. /// Task RevertOriginalAsync(WalletWithdrawalRequest replacement); + + /// + /// RBF does not guarantee the replacement wins: a miner can still mine a transaction it replaced. When a request + /// replaced, directly or through earlier replacements, has a transaction with the + /// settlement confirmations, that request is settled and the replacement fails. Returns whether that happened. + /// + Task SettleMinedOriginalAsync(WalletWithdrawalRequest replacement); } public class WithdrawalRequestService : IWithdrawalRequestService @@ -362,6 +369,14 @@ public async Task MarkOriginalAsReplacedAsync(WalletWithdrawalRequest replacemen : WalletWithdrawalRequestStatus.Bumped; if (original.Status == targetStatus) return; + if (original.Status != WalletWithdrawalRequestStatus.OnChainConfirmationPending) + { + // E.g. the original was mined and settled while a cold-wallet replacement was collecting signatures. + _logger.LogWarning("Not marking withdrawal request {RequestId} as {TargetStatus}: it is {Status}", + originalId, targetStatus, original.Status); + return; + } + original.Status = targetStatus; if (replacement.IsRbfCancellation) { @@ -399,6 +414,60 @@ public async Task RevertOriginalAsync(WalletWithdrawalRequest replacement) } } + public async Task SettleMinedOriginalAsync(WalletWithdrawalRequest replacement) + { + // An unset TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS is 0, and an unconfirmed original was never mined. + var minimumConfirmations = Math.Max(1, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS); + var visited = new HashSet { replacement.Id }; + var originalId = replacement.BumpingWalletWithdrawalRequestId; + + while (originalId is { } id && visited.Add(id)) + { + var original = await _walletWithdrawalRequestRepository.GetById(id); + if (original == null) return false; + + if (!string.IsNullOrEmpty(original.TxId)) + { + var originalTx = await _nbXplorerService.GetTransactionAsync(uint256.Parse(original.TxId)); + if (originalTx != null && originalTx.Confirmations >= minimumConfirmations) + { + return SettleOriginalAndFailReplacement(original, replacement); + } + } + + originalId = original.BumpingWalletWithdrawalRequestId; + } + + return false; + } + + private bool SettleOriginalAndFailReplacement(WalletWithdrawalRequest original, WalletWithdrawalRequest replacement) + { + original.Status = WalletWithdrawalRequestStatus.OnChainConfirmed; + original.RejectCancelDescription = null; + var (originalUpdated, originalUpdateError) = _walletWithdrawalRequestRepository.Update(original); + if (!originalUpdated) + { + // The replacement stays pending so the next monitoring run retries both. + _logger.LogError("Could not settle withdrawal request {RequestId}, mined instead of its replacement {ReplacementId}: {Error}", + original.Id, replacement.Id, originalUpdateError); + return false; + } + + replacement.Status = WalletWithdrawalRequestStatus.Failed; + replacement.RejectCancelDescription = $"Withdrawal request {original.Id} was mined instead (tx {original.TxId})"; + var (replacementUpdated, replacementUpdateError) = _walletWithdrawalRequestRepository.Update(replacement); + if (!replacementUpdated) + { + _logger.LogError("Could not mark replacement withdrawal request {RequestId} as failed: {Error}", + replacement.Id, replacementUpdateError); + } + + _logger.LogInformation("Withdrawal request {RequestId} was mined instead of its replacement {ReplacementId}", + original.Id, replacement.Id); + return true; + } + private async Task ResolveFeeRateAsync(MempoolRecommendedFeesType feeType, decimal? customFeeRate) { if (feeType == MempoolRecommendedFeesType.CustomFee) diff --git a/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestRepositoryTests.cs b/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestRepositoryTests.cs new file mode 100644 index 000000000..cf296ef24 --- /dev/null +++ b/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestRepositoryTests.cs @@ -0,0 +1,156 @@ +/* + * 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 AutoMapper; +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using NodeGuard.Data.Models; +using NodeGuard.Data.Repositories.Interfaces; +using NodeGuard.Services; + +namespace NodeGuard.Data.Repositories; + +/// +/// GetByReferenceIds answers "what happened to this external withdrawal". RBF replacements inherit the reference id of +/// the request they replace, so it has to pick the request of the chain that tells the truth: the latest one, unless a +/// request it replaced was mined instead. +/// +public class WalletWithdrawalRequestRepositoryTests +{ + private const string Reference = "store-settlement-1"; + + private readonly Random _random = new(); + + private Mock> SetupDbContextFactory() + { + var dbContextFactory = new Mock>(); + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: "WalletWithdrawalRequestRepositoryTests" + _random.Next()) + .Options; + var context = () => new ApplicationDbContext(options); + dbContextFactory.Setup(x => x.CreateDbContext()).Returns(context); + dbContextFactory.Setup(x => x.CreateDbContextAsync(default)).ReturnsAsync(context); + return dbContextFactory; + } + + // NotificationService is not used by the reads under test. + private static WalletWithdrawalRequestRepository CreateRepository(Mock> factory) + => new(new Mock>().Object, + NullLogger.Instance, + factory.Object, + new Mock().Object, + null!, + new Mock().Object); + + private static async Task SeedAsync( + Mock> factory, params WalletWithdrawalRequest[] requests) + { + await using var context = await factory.Object.CreateDbContextAsync(); + await context.WalletWithdrawalRequests.AddRangeAsync(requests); + await context.SaveChangesAsync(); + return CreateRepository(factory); + } + + private static WalletWithdrawalRequest Request(int id, WalletWithdrawalRequestStatus status, int? replaces = null, + string reference = Reference) => new() + { + Id = id, + Description = "reference id test", + ReferenceId = reference, + Status = status, + BumpingWalletWithdrawalRequestId = replaces, + }; + + [Fact] + public async Task GetByReferenceIds_ReplacementInFlight_ReturnsTheLatestRequest() + { + var repository = await SeedAsync(SetupDbContextFactory(), + Request(1, WalletWithdrawalRequestStatus.Bumped), + Request(2, WalletWithdrawalRequestStatus.OnChainConfirmationPending, replaces: 1)); + + var result = await repository.GetByReferenceIds(new List { Reference }); + + result.Should().ContainSingle().Which.Id.Should().Be(2); + } + + [Fact] + public async Task GetByReferenceIds_ReplacementConfirmed_ReturnsTheReplacement() + { + var repository = await SeedAsync(SetupDbContextFactory(), + Request(1, WalletWithdrawalRequestStatus.Bumped), + Request(2, WalletWithdrawalRequestStatus.OnChainConfirmed, replaces: 1)); + + var result = await repository.GetByReferenceIds(new List { Reference }); + + result.Should().ContainSingle().Which.Id.Should().Be(2); + } + + [Fact] + public async Task GetByReferenceIds_OriginalMinedInstead_ReturnsTheSettledOriginal() + { + var repository = await SeedAsync(SetupDbContextFactory(), + Request(1, WalletWithdrawalRequestStatus.OnChainConfirmed), + Request(2, WalletWithdrawalRequestStatus.Failed, replaces: 1)); + + var result = await repository.GetByReferenceIds(new List { Reference }); + + result.Should().ContainSingle().Which.Id.Should().Be(1, + "the failed replacement lost the race: reporting it would tell the caller a paid withdrawal failed"); + } + + [Fact] + public async Task GetByReferenceIds_BumpOfABumpWithTheFirstMined_ReturnsTheFirstRequest() + { + var repository = await SeedAsync(SetupDbContextFactory(), + Request(1, WalletWithdrawalRequestStatus.OnChainConfirmed), + Request(2, WalletWithdrawalRequestStatus.Bumped, replaces: 1), + Request(3, WalletWithdrawalRequestStatus.Failed, replaces: 2)); + + var result = await repository.GetByReferenceIds(new List { Reference }); + + result.Should().ContainSingle().Which.Id.Should().Be(1); + } + + [Fact] + public async Task GetByReferenceIds_ReusedReferenceId_DoesNotReportAnUnrelatedEarlierWithdrawal() + { + var repository = await SeedAsync(SetupDbContextFactory(), + Request(1, WalletWithdrawalRequestStatus.OnChainConfirmed), + Request(2, WalletWithdrawalRequestStatus.Failed)); + + var result = await repository.GetByReferenceIds(new List { Reference }); + + result.Should().ContainSingle().Which.Id.Should().Be(2, + "reference ids are not unique: only requests the latest one replaced can stand in for it"); + } + + [Fact] + public async Task GetByReferenceIds_SeveralReferences_ResolvesEachOnItsOwn() + { + var repository = await SeedAsync(SetupDbContextFactory(), + Request(1, WalletWithdrawalRequestStatus.OnChainConfirmed, reference: "a"), + Request(2, WalletWithdrawalRequestStatus.Failed, replaces: 1, reference: "a"), + Request(3, WalletWithdrawalRequestStatus.OnChainConfirmationPending, reference: "b")); + + var result = await repository.GetByReferenceIds(new List { "a", "b" }); + + result.Select(r => r.Id).Should().BeEquivalentTo(new[] { 1, 3 }); + } +} diff --git a/test/NodeGuard.Tests/E2E/WithdrawalRbfBumpE2ETests.cs b/test/NodeGuard.Tests/E2E/WithdrawalRbfBumpE2ETests.cs index 8a9cd7218..3f775c827 100644 --- a/test/NodeGuard.Tests/E2E/WithdrawalRbfBumpE2ETests.cs +++ b/test/NodeGuard.Tests/E2E/WithdrawalRbfBumpE2ETests.cs @@ -31,8 +31,10 @@ namespace NodeGuard.Tests.E2E; /// over gRPC. Fee bump: RequestWithdrawal broadcasts an RBF-signalling transaction, BumpWithdrawal replaces it with a /// higher-fee version of the same payment, bitcoind evicts the original, NodeGuard marks it WITHDRAWAL_BUMPED and, once /// mined, settles the replacement. Cancellation: CancelWithdrawal replaces it with a transaction that returns the funds to -/// the wallet, the destination is never paid and the original ends up WITHDRAWAL_CANCELLED. The UI and the RPCs share -/// WithdrawalRequestService, so these scenarios exercise the same orchestration the Withdrawals page runs. +/// the wallet, the destination is never paid and the original ends up WITHDRAWAL_CANCELLED. Mined original: either +/// replacement loses the race to the original, which NodeGuard must then settle while failing the replacement, also when +/// the original was bumped twice. The UI and the RPCs share WithdrawalRequestService, so these scenarios exercise the +/// same orchestration the Withdrawals page runs. /// /// Shared plumbing in ; gated by . Env: see /// . Never mine between the withdrawal and its replacement — the original must @@ -46,6 +48,7 @@ public class WithdrawalRbfBumpE2ETests : E2ETestBase private const long WithdrawalAmountSats = 1_000_000; private const int OriginalFeeRateSatPerVb = 2; private const int BumpedFeeRateSatPerVb = 10; + private const int SecondBumpFeeRateSatPerVb = 20; private const long ProbeAmountSats = 2_000_000; public WithdrawalRbfBumpE2ETests(ITestOutputHelper output) : base(output) @@ -239,8 +242,189 @@ await RetryAsync(async () => }, attempts: 30, delay: TimeSpan.FromSeconds(4), what: "returned funds spendable again"); } + /// + /// A replacement is not guaranteed to win: a miner that never saw it can still mine the original. The original's + /// payment is then the one that happened, so NodeGuard must settle the original and fail the replacement, instead of + /// leaving the original Bumped / Cancelled while its transaction is confirmed on-chain. + /// + [E2ETheory] + [InlineData(false)] + [InlineData(true)] + public async Task Replacement_WhenTheOriginalIsMinedInstead_SettlesTheOriginalAndFailsTheReplacement(bool cancellation) + { + var client = CreateClient(out var headers); + var rpc = CreateBitcoindRpc(); + var walletId = await EnsureHotWalletReadyAsync(client, headers); + + // 1. A hot-wallet withdrawal at a low fee rate. Its signed transaction is kept: it is what the other miner mines. + var destination = await rpc.GetNewAddressAsync(); + var referenceId = $"e2e-rbf-mined-original-{Guid.NewGuid():N}"; + var withdrawal = await RequestHotWithdrawalAsync(client, headers, walletId, destination, + $"E2E RBF {(cancellation ? "cancel" : "bump")} mined-original test", referenceId); + var originalTxId = uint256.Parse(withdrawal.Txid); + var originalTx = await WaitForBroadcastAsync(rpc, originalTxId, "original withdrawal broadcast"); + + await PollAsync(() => GetStatusesAsync(client, headers, withdrawal.RequestId), + s => s[withdrawal.RequestId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingConfirmation, + attempts: 30, delay: TimeSpan.FromSeconds(2), what: "original pending confirmation"); + + // 2. Replace it: bitcoind evicts the original and NodeGuard marks it bumped / cancelled. + var (replacementId, replacementTxId) = await ReplaceAsync(client, headers, withdrawal.Txid, cancellation); + var replacedStatus = cancellation + ? WITHDRAWAL_REQUEST_STATUS.WithdrawalCancelled + : WITHDRAWAL_REQUEST_STATUS.WithdrawalBumped; + + await WaitForBroadcastAsync(rpc, replacementTxId, "replacement broadcast"); + await WaitUntilEvictedAsync(rpc, originalTxId); + await PollAsync(() => GetStatusesAsync(client, headers, withdrawal.RequestId, replacementId), + s => s[replacementId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingConfirmation + && s[withdrawal.RequestId].Status == replacedStatus, + attempts: 30, delay: TimeSpan.FromSeconds(2), what: $"replacement pending confirmation, original {replacedStatus}"); + + // 3. The original is mined instead, which evicts the replacement as a double spend. + await MineBypassingTheMempoolAsync(rpc, originalTx); + await MineAsync(rpc, 5); + + var originalInfo = await rpc.GetRawTransactionInfoAsync(originalTxId); + ((uint?)originalInfo.Confirmations ?? 0).Should().BeGreaterThan(0u, "the original was mined"); + (await rpc.GetRawTransactionAsync(replacementTxId, throwIfNotFound: false)).Should().BeNull( + "the replacement double-spends a confirmed transaction and can never confirm"); + + // 4. NodeGuard's view must follow the chain: the original settled, the replacement failed. + var settled = await PollAsync(() => GetStatusesAsync(client, headers, withdrawal.RequestId, replacementId), + s => + { + _output.WriteLine($"original {s[withdrawal.RequestId].Status}, replacement {s[replacementId].Status}"); + return s[withdrawal.RequestId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalSettled + && s[replacementId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalFailed; + }, + attempts: 40, delay: TimeSpan.FromSeconds(5), what: "original settled, replacement failed"); + + settled[withdrawal.RequestId].TxId.Should().Be(withdrawal.Txid, "the original's own transaction is the one that confirmed"); + settled[withdrawal.RequestId].Confirmations.Should().BeGreaterThan(0UL); + if (cancellation) + { + settled[withdrawal.RequestId].RejectOrCancelReason.Should().BeEmpty( + "the cancellation never took effect: the destination was paid"); + } + + await AssertReferenceResolvesToSettledAsync(client, headers, referenceId, withdrawal.RequestId); + } + + /// + /// The same race one bump deeper: A is bumped to B, B is bumped to C, and A is mined. NodeGuard must settle A and fail + /// C; B was replaced and never confirmed, so it stays bumped. + /// + [E2EFact] + public async Task BumpOfABump_WhenTheFirstTransactionIsMined_SettlesItAndFailsTheLastReplacement() + { + var client = CreateClient(out var headers); + var rpc = CreateBitcoindRpc(); + var walletId = await EnsureHotWalletReadyAsync(client, headers); + + // 1. A: a hot-wallet withdrawal at a low fee rate. Its signed transaction is kept: it is what gets mined. + var destination = await rpc.GetNewAddressAsync(); + var referenceId = $"e2e-rbf-bump-of-a-bump-{Guid.NewGuid():N}"; + var first = await RequestHotWithdrawalAsync(client, headers, walletId, destination, + "E2E RBF bump-of-a-bump mined-first test", referenceId); + var firstTxId = uint256.Parse(first.Txid); + var firstTx = await WaitForBroadcastAsync(rpc, firstTxId, "first withdrawal broadcast"); + + await PollAsync(() => GetStatusesAsync(client, headers, first.RequestId), + s => s[first.RequestId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingConfirmation, + attempts: 30, delay: TimeSpan.FromSeconds(2), what: "first pending confirmation"); + + // 2. B bumps A. + var (secondId, secondTxId) = await ReplaceAsync(client, headers, first.Txid, cancellation: false); + await WaitForBroadcastAsync(rpc, secondTxId, "first bump broadcast"); + await WaitUntilEvictedAsync(rpc, firstTxId); + + await PollAsync(() => GetStatusesAsync(client, headers, first.RequestId, secondId), + s => s[secondId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingConfirmation + && s[first.RequestId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalBumped, + attempts: 30, delay: TimeSpan.FromSeconds(2), what: "first bump pending confirmation, first bumped"); + + // 3. C bumps B at a higher fee rate again: three transactions over the same inputs, only C in the mempool. + var (thirdId, thirdTxId) = await ReplaceAsync(client, headers, secondTxId.ToString(), cancellation: false, + SecondBumpFeeRateSatPerVb); + var thirdTx = await WaitForBroadcastAsync(rpc, thirdTxId, "second bump broadcast"); + await WaitUntilEvictedAsync(rpc, secondTxId); + + thirdTx.Inputs.Select(i => i.PrevOut).Should().BeEquivalentTo(firstTx.Inputs.Select(i => i.PrevOut), + "every replacement spends the inputs of the first transaction"); + await PollAsync(() => GetStatusesAsync(client, headers, first.RequestId, secondId, thirdId), + s => s[thirdId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingConfirmation + && s[secondId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalBumped + && s[first.RequestId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalBumped, + attempts: 30, delay: TimeSpan.FromSeconds(2), what: "second bump pending confirmation, first and first bump bumped"); + + // 4. The oldest transaction, A, is mined, which evicts C as a double spend. + await MineBypassingTheMempoolAsync(rpc, firstTx); + await MineAsync(rpc, 5); + + var firstInfo = await rpc.GetRawTransactionInfoAsync(firstTxId); + ((uint?)firstInfo.Confirmations ?? 0).Should().BeGreaterThan(0u, "the first transaction was mined"); + (await rpc.GetRawTransactionAsync(secondTxId, throwIfNotFound: false)).Should().BeNull("B can never confirm"); + (await rpc.GetRawTransactionAsync(thirdTxId, throwIfNotFound: false)).Should().BeNull("C can never confirm"); + + // 5. NodeGuard's view must follow the chain: A settled, C failed, B still bumped. + var settled = await PollAsync(() => GetStatusesAsync(client, headers, first.RequestId, secondId, thirdId), + s => + { + _output.WriteLine($"A {s[first.RequestId].Status}, B {s[secondId].Status}, C {s[thirdId].Status}"); + return s[first.RequestId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalSettled + && s[thirdId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalFailed; + }, + attempts: 40, delay: TimeSpan.FromSeconds(5), what: "first settled, second bump failed"); + + settled[first.RequestId].TxId.Should().Be(first.Txid, "A's own transaction is the one that confirmed"); + settled[first.RequestId].Confirmations.Should().BeGreaterThan(0UL); + settled[secondId].Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalBumped, "B was replaced by C and never confirmed"); + settled[thirdId].RejectOrCancelReason.Should().Contain(first.RequestId.ToString(), + "the failure names the request that was mined instead"); + + await AssertReferenceResolvesToSettledAsync(client, headers, referenceId, first.RequestId); + } + // ---- plumbing ------------------------------------------------------------------------------------------------ + /// Bumps or cancels at sat/vB. + private async Task<(int RequestId, uint256 TxId)> ReplaceAsync(NodeGuardService.NodeGuardServiceClient client, + Metadata headers, string txId, bool cancellation, int feeRate = BumpedFeeRateSatPerVb) + { + if (cancellation) + { + var cancel = await client.CancelWithdrawalAsync(new CancelWithdrawalRequest + { + TxId = txId, + MempoolFeeRate = FEES_TYPE.CustomFee, + CustomFeeRate = feeRate, + }, headers); + _output.WriteLine($"cancel request {cancel.RequestId} → txid {cancel.Txid}"); + return (cancel.RequestId, uint256.Parse(cancel.Txid)); + } + + var bump = await client.BumpWithdrawalAsync(new BumpWithdrawalRequest + { + TxId = txId, + MempoolFeeRate = FEES_TYPE.CustomFee, + CustomFeeRate = feeRate, + }, headers); + _output.WriteLine($"bump request {bump.RequestId} → txid {bump.Txid}"); + return (bump.RequestId, uint256.Parse(bump.Txid)); + } + + /// + /// Mines as a miner that never saw its replacements would: generateblock takes the raw + /// transaction, bypassing the mempool the replacement sits in. + /// + private async Task MineBypassingTheMempoolAsync(RPCClient rpc, Transaction tx) + { + var minerAddress = await rpc.GetNewAddressAsync(); + var block = await rpc.SendCommandAsync("generateblock", minerAddress.ToString(), new[] { tx.ToHex() }); + _output.WriteLine($"{tx.GetHash()} mined in block {block.Result["hash"]}"); + } + /// NodeGuard up and the dev hot wallet spendable (DbInitializer funds it; another e2e may hold it briefly). private async Task EnsureHotWalletReadyAsync(NodeGuardService.NodeGuardServiceClient client, Metadata headers) { @@ -266,16 +450,19 @@ await RetryAsync(async () => } private async Task RequestHotWithdrawalAsync(NodeGuardService.NodeGuardServiceClient client, - Metadata headers, int walletId, BitcoinAddress destination, string description) + Metadata headers, int walletId, BitcoinAddress destination, string description, string? referenceId = null) { - var withdrawal = await client.RequestWithdrawalAsync(new RequestWithdrawalRequest + var request = new RequestWithdrawalRequest { WalletId = walletId, Description = description, Destinations = { new Destination { Address = destination.ToString(), AmountSats = WithdrawalAmountSats } }, MempoolFeeRate = FEES_TYPE.CustomFee, CustomFeeRate = OriginalFeeRateSatPerVb, - }, headers); + }; + if (referenceId != null) request.ReferenceId = referenceId; + + var withdrawal = await client.RequestWithdrawalAsync(request, headers); _output.WriteLine($"withdrawal request {withdrawal.RequestId} → txid {withdrawal.Txid}"); withdrawal.IsHotWallet.Should().BeTrue(); return withdrawal; @@ -299,6 +486,21 @@ await RetryAsync(async () => }, attempts: 15, delay: TimeSpan.FromSeconds(2), what: "original evicted by the replacement"); } + /// + /// What a caller tracking the withdrawal by reference id sees. Replacements share the reference id, and the + /// request that settled must win over the newer replacement that failed, or a paid withdrawal reads as failed. + /// + private static async Task AssertReferenceResolvesToSettledAsync(NodeGuardService.NodeGuardServiceClient client, + Metadata headers, string referenceId, int settledRequestId) + { + var response = await client.GetWithdrawalsRequestStatusByReferenceIdsAsync( + new GetWithdrawalsRequestStatusByReferenceIdsRequest { ReferenceIds = { referenceId } }, headers); + + var tracked = response.WithdrawalRequests.Should().ContainSingle().Subject; + tracked.RequestId.Should().Be(settledRequestId, "the request whose transaction confirmed is the payment that happened"); + tracked.Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalSettled); + } + private static async Task> GetStatusesAsync( NodeGuardService.NodeGuardServiceClient client, Metadata headers, params int[] requestIds) { diff --git a/test/NodeGuard.Tests/Jobs/MonitorWithdrawalsJobTests.cs b/test/NodeGuard.Tests/Jobs/MonitorWithdrawalsJobTests.cs new file mode 100644 index 000000000..ab2e56e7d --- /dev/null +++ b/test/NodeGuard.Tests/Jobs/MonitorWithdrawalsJobTests.cs @@ -0,0 +1,147 @@ +/* + * 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.Abstractions; +using NBitcoin; +using NBXplorer.Models; +using NodeGuard.Data.Models; +using NodeGuard.Data.Repositories.Interfaces; +using NodeGuard.Helpers; +using NodeGuard.Services; +using Quartz; + +namespace NodeGuard.Jobs; + +/// +/// MonitorWithdrawalsJob settles withdrawals whose transaction reached the settlement depth, and asks +/// WithdrawalRequestService whether an RBF replacement lost the race to a transaction it replaced. That question only +/// makes sense while the replacement itself is unconfirmed: once it is mined, nothing it replaced can be. +/// +public class MonitorWithdrawalsJobTests +{ + private readonly Mock _requests = new(); + private readonly Mock _nbXplorer = new(); + private readonly Mock _withdrawalRequestService = new(); + + public MonitorWithdrawalsJobTests() + { + _requests.Setup(x => x.Update(It.IsAny())).Returns((true, (string?)null)); + } + + private Task ExecuteAsync(params WalletWithdrawalRequest[] pending) + { + _requests.Setup(x => x.GetOnChainPendingWithdrawals()).ReturnsAsync(pending.ToList()); + + var job = new MonitorWithdrawalsJob(NullLogger.Instance, _requests.Object, + _nbXplorer.Object, _withdrawalRequestService.Object); + return job.Execute(new Mock().Object); + } + + /// A broadcast request waiting for confirmation whose transaction has . + private WalletWithdrawalRequest Pending(int id, int confirmations, int? replaces = null) + { + var txId = new uint256((ulong)id); + _nbXplorer.Setup(x => x.GetTransactionAsync(txId, It.IsAny())) + .ReturnsAsync(new TransactionResult { Confirmations = confirmations }); + + return new WalletWithdrawalRequest + { + Id = id, + Status = WalletWithdrawalRequestStatus.OnChainConfirmationPending, + TxId = txId.ToString(), + BumpingWalletWithdrawalRequestId = replaces, + }; + } + + [Fact] + public async Task Execute_WithdrawalAtTheSettlementDepth_IsSettled() + { + var request = Pending(1, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS); + + await ExecuteAsync(request); + + request.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed); + _requests.Verify(x => x.Update(request), Times.Once); + _withdrawalRequestService.Verify(x => x.SettleMinedOriginalAsync(It.IsAny()), Times.Never); + } + + [Fact] + public async Task Execute_ReplacementAtTheSettlementDepth_IsSettledWithoutLookingAtWhatItReplaced() + { + var replacement = Pending(2, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS, replaces: 1); + + await ExecuteAsync(replacement); + + replacement.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed); + _withdrawalRequestService.Verify(x => x.SettleMinedOriginalAsync(It.IsAny()), Times.Never); + } + + [Fact] + public async Task Execute_UnconfirmedReplacement_ChecksWhetherWhatItReplacedWasMined() + { + var replacement = Pending(2, confirmations: 0, replaces: 1); + + await ExecuteAsync(replacement); + + _withdrawalRequestService.Verify(x => x.SettleMinedOriginalAsync(replacement), Times.Once); + replacement.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending, + "settling the original and failing the replacement is the service's decision, not the job's"); + } + + [Fact] + public async Task Execute_ReplacementMinedButNotYetSettled_LeavesWhatItReplacedAlone() + { + var replacement = Pending(2, confirmations: 1, replaces: 1); + + await ExecuteAsync(replacement); + + replacement.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending, "it is not deep enough yet"); + _withdrawalRequestService.Verify(x => x.SettleMinedOriginalAsync(It.IsAny()), Times.Never, + "the replacement is mined, so nothing it replaced can be"); + _requests.Verify(x => x.Update(It.IsAny()), Times.Never); + } + + [Fact] + public async Task Execute_UnconfirmedWithdrawalThatReplacesNothing_IsLeftPending() + { + var request = Pending(1, confirmations: 0); + + await ExecuteAsync(request); + + request.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending); + _withdrawalRequestService.Verify(x => x.SettleMinedOriginalAsync(It.IsAny()), Times.Never); + _requests.Verify(x => x.Update(It.IsAny()), Times.Never); + } + + [Fact] + public async Task Execute_MixedBatch_HandlesEachRequestOnItsOwn() + { + var settling = Pending(1, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS); + var lostRace = Pending(3, confirmations: 0, replaces: 2); + var inFlight = Pending(4, confirmations: 0); + + await ExecuteAsync(settling, lostRace, inFlight); + + settling.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed); + _withdrawalRequestService.Verify(x => x.SettleMinedOriginalAsync(lostRace), Times.Once); + _withdrawalRequestService.Verify(x => x.SettleMinedOriginalAsync(It.IsAny()), Times.Once); + inFlight.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending); + } +} diff --git a/test/NodeGuard.Tests/Jobs/PerformWithdrawalJobTests.cs b/test/NodeGuard.Tests/Jobs/PerformWithdrawalJobTests.cs new file mode 100644 index 000000000..4a1ea098a --- /dev/null +++ b/test/NodeGuard.Tests/Jobs/PerformWithdrawalJobTests.cs @@ -0,0 +1,154 @@ +/* + * 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.Abstractions; +using NodeGuard.Data.Models; +using NodeGuard.Data.Repositories.Interfaces; +using NodeGuard.Services; +using Quartz; + +namespace NodeGuard.Jobs; + +/// +/// When PerformWithdrawalJob cannot sign or broadcast, the request fails and, if it was an RBF replacement, the request +/// it replaced gets back its pending-confirmation status. That revert goes through WithdrawalRequestService, so it only +/// undoes what the replacement did: an original that settled meanwhile (the cold-wallet case, where approvals take +/// hours) is left settled, and a reverted cancellation loses its "Cancelled by RBF" reason. +/// +public class PerformWithdrawalJobTests +{ + private const int OriginalId = 10; + private const int ReplacementId = 11; + + private readonly Mock _requests = new(); + private readonly Mock _bitcoin = new(); + + public PerformWithdrawalJobTests() + { + _requests.Setup(x => x.Update(It.IsAny())).Returns((true, (string?)null)); + _bitcoin.Setup(x => x.PerformWithdrawal(It.IsAny())) + .ThrowsAsync(new InvalidOperationException("Failed tx broadcast")); + } + + private Task ExecuteAsync(int requestId) + { + // The real service: what happens to the replaced request is RevertOriginalAsync's behaviour. + var withdrawalRequestService = new WithdrawalRequestService(NullLogger.Instance, + _requests.Object, Mock.Of(), Mock.Of(), Mock.Of(), + _bitcoin.Object, Mock.Of()); + var job = new PerformWithdrawalJob(NullLogger.Instance, _bitcoin.Object, _requests.Object, + withdrawalRequestService); + + var context = new Mock(); + context.Setup(x => x.JobDetail).Returns(JobBuilder.Create() + .UsingJobData("withdrawalRequestId", requestId) + .Build()); + return job.Execute(context.Object); + } + + private WalletWithdrawalRequest Stored(int id, WalletWithdrawalRequestStatus status, int? replaces = null, + bool cancellation = false) + { + var request = new WalletWithdrawalRequest + { + Id = id, + Description = "perform withdrawal test", + Status = status, + BumpingWalletWithdrawalRequestId = replaces, + IsRbfCancellation = cancellation, + }; + _requests.Setup(x => x.GetById(id)).ReturnsAsync(request); + return request; + } + + [Fact] + public async Task Execute_FailedBump_RevertsTheBumpedOriginalAndFailsTheBump() + { + var original = Stored(OriginalId, WalletWithdrawalRequestStatus.Bumped); + var bump = Stored(ReplacementId, WalletWithdrawalRequestStatus.FinalizingPSBT, replaces: OriginalId); + + await ExecuteAsync(ReplacementId); + + bump.Status.Should().Be(WalletWithdrawalRequestStatus.Failed); + original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending, + "the bump never went out, so the original transaction is still the one waiting to confirm"); + } + + [Fact] + public async Task Execute_FailedCancellation_RestoresTheOriginalAndClearsTheCancellationReason() + { + var original = Stored(OriginalId, WalletWithdrawalRequestStatus.Cancelled); + original.RejectCancelDescription = $"Cancelled by RBF replacement request {ReplacementId}"; + var cancel = Stored(ReplacementId, WalletWithdrawalRequestStatus.FinalizingPSBT, replaces: OriginalId, cancellation: true); + + await ExecuteAsync(ReplacementId); + + cancel.Status.Should().Be(WalletWithdrawalRequestStatus.Failed); + original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending); + original.RejectCancelDescription.Should().BeNull("the cancellation never went out"); + } + + [Fact] + public async Task Execute_FailedReplacementOfAnOriginalThatAlreadySettled_LeavesItSettled() + { + var original = Stored(OriginalId, WalletWithdrawalRequestStatus.OnChainConfirmed); + var bump = Stored(ReplacementId, WalletWithdrawalRequestStatus.FinalizingPSBT, replaces: OriginalId); + + await ExecuteAsync(ReplacementId); + + bump.Status.Should().Be(WalletWithdrawalRequestStatus.Failed); + original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed, + "it was mined while the replacement waited for its signatures; that is why the broadcast failed"); + _requests.Verify(x => x.Update(original), Times.Never); + } + + [Fact] + public async Task Execute_FailedWithdrawalThatReplacesNothing_IsMarkedFailed() + { + var request = Stored(OriginalId, WalletWithdrawalRequestStatus.FinalizingPSBT); + + await ExecuteAsync(OriginalId); + + request.Status.Should().Be(WalletWithdrawalRequestStatus.Failed); + _requests.Verify(x => x.Update(It.IsAny()), Times.Once); + } + + [Fact] + public async Task Execute_RequestGoneByTheTimeItFails_DoesNotThrow() + { + var act = () => ExecuteAsync(OriginalId); + + await act.Should().NotThrowAsync(); + _requests.Verify(x => x.Update(It.IsAny()), Times.Never); + } + + [Fact] + public async Task Execute_SuccessfulBroadcast_LeavesTheReplacedRequestAsItWas() + { + _bitcoin.Setup(x => x.PerformWithdrawal(It.IsAny())).Returns(Task.CompletedTask); + var original = Stored(OriginalId, WalletWithdrawalRequestStatus.Bumped); + Stored(ReplacementId, WalletWithdrawalRequestStatus.FinalizingPSBT, replaces: OriginalId); + + await ExecuteAsync(ReplacementId); + + original.Status.Should().Be(WalletWithdrawalRequestStatus.Bumped); + _requests.Verify(x => x.Update(It.IsAny()), Times.Never); + } +} diff --git a/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs b/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs index 804481629..0391ebe9d 100644 --- a/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs +++ b/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs @@ -528,8 +528,120 @@ public async Task MarkOriginalAsReplacedAsync_NotAReplacement_IsANoOp() _requests.Verify(x => x.Update(It.IsAny()), Times.Never); } + [Fact] + public async Task MarkOriginalAsReplacedAsync_OriginalAlreadySettled_IsLeftAlone() + { + var original = SetupOriginal(ColdWallet(), status: WalletWithdrawalRequestStatus.OnChainConfirmed, confirmations: SettledDepth); + var bump = HotRequest(WalletWithdrawalRequestStatus.PSBTSignaturesPending, bumping: OriginalId); + + await CreateService().MarkOriginalAsReplacedAsync(bump); + + original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed, + "it was mined while the cold-wallet replacement was collecting signatures"); + _requests.Verify(x => x.Update(It.IsAny()), Times.Never); + } + + // ---- SettleMinedOriginalAsync ----------------------------------------------------------------------------- + + [Fact] + public async Task SettleMinedOriginalAsync_OriginalMined_SettlesItAndFailsTheReplacement() + { + var original = SetupOriginal(HotWallet(), status: WalletWithdrawalRequestStatus.Bumped, confirmations: SettledDepth); + var bump = HotRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending, bumping: OriginalId); + + var settled = await CreateService().SettleMinedOriginalAsync(bump); + + settled.Should().BeTrue(); + original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed, "its transaction is the one that confirmed"); + bump.Status.Should().Be(WalletWithdrawalRequestStatus.Failed, "it double-spends a confirmed transaction"); + bump.RejectCancelDescription.Should().Contain(OriginalId.ToString()).And.Contain(_originalTxId.ToString()); + } + + [Fact] + public async Task SettleMinedOriginalAsync_CancelledOriginalMined_ClearsTheCancellationReason() + { + var original = SetupOriginal(HotWallet(), status: WalletWithdrawalRequestStatus.Cancelled, confirmations: SettledDepth); + original.RejectCancelDescription = $"Cancelled by RBF replacement request {BumpId}"; + var cancel = HotRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending, bumping: OriginalId, cancellation: true); + + await CreateService().SettleMinedOriginalAsync(cancel); + + original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed); + original.RejectCancelDescription.Should().BeNull("the cancellation never took effect: the destination was paid"); + cancel.Status.Should().Be(WalletWithdrawalRequestStatus.Failed); + } + + [Fact] + public async Task SettleMinedOriginalAsync_OriginalUnconfirmed_LeavesBothAlone() + { + var original = SetupOriginal(HotWallet(), status: WalletWithdrawalRequestStatus.Bumped, confirmations: 0); + var bump = HotRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending, bumping: OriginalId); + + var settled = await CreateService().SettleMinedOriginalAsync(bump); + + settled.Should().BeFalse(); + original.Status.Should().Be(WalletWithdrawalRequestStatus.Bumped); + bump.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending); + _requests.Verify(x => x.Update(It.IsAny()), Times.Never); + } + + [Fact] + public async Task SettleMinedOriginalAsync_BumpOfABump_SettlesTheMinedRequestAndLeavesTheMiddleOneBumped() + { + const int middleId = 12; + var middleTxId = new uint256(2); + var first = SetupOriginal(HotWallet(), status: WalletWithdrawalRequestStatus.Bumped, confirmations: SettledDepth); + var middle = new WalletWithdrawalRequest + { + Id = middleId, + Status = WalletWithdrawalRequestStatus.Bumped, + TxId = middleTxId.ToString(), + BumpingWalletWithdrawalRequestId = OriginalId, + }; + _requests.Setup(x => x.GetById(middleId)).ReturnsAsync(middle); + _nbXplorer.Setup(x => x.GetTransactionAsync(middleTxId, It.IsAny())) + .ReturnsAsync(new TransactionResult { Confirmations = 0 }); + var last = HotRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending, bumping: middleId); + + var settled = await CreateService().SettleMinedOriginalAsync(last); + + settled.Should().BeTrue(); + first.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed); + middle.Status.Should().Be(WalletWithdrawalRequestStatus.Bumped, "it was replaced and never confirmed"); + last.Status.Should().Be(WalletWithdrawalRequestStatus.Failed); + } + + [Fact] + public async Task SettleMinedOriginalAsync_NotAReplacement_IsANoOp() + { + var request = HotRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending); + + var settled = await CreateService().SettleMinedOriginalAsync(request); + + settled.Should().BeFalse(); + _requests.Verify(x => x.Update(It.IsAny()), Times.Never); + _nbXplorer.Verify(x => x.GetTransactionAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task SettleMinedOriginalAsync_SettlingTheOriginalFails_LeavesTheReplacementPending() + { + SetupOriginal(HotWallet(), status: WalletWithdrawalRequestStatus.Bumped, confirmations: SettledDepth); + var bump = HotRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending, bumping: OriginalId); + _requests.Setup(x => x.Update(It.Is(r => r.Id == OriginalId))).Returns((false, "db down")); + + var settled = await CreateService().SettleMinedOriginalAsync(bump); + + settled.Should().BeFalse(); + bump.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending, "the next monitoring run retries both"); + _requests.Verify(x => x.Update(It.Is(r => r.Id == BumpId)), Times.Never); + } + // ---- fixtures --------------------------------------------------------------------------------------------- + /// Confirmations at which the monitor settles a withdrawal (the constant is 0 when its env var is unset). + private static int SettledDepth => Math.Max(1, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS); + private async Task AssertRefusedAsync(BumpingErrorReason reason, MempoolRecommendedFeesType feeType, decimal? customFeeRate, bool cancellation = false) { diff --git a/test/NodeGuard.Tests/TestHelpers/TestEnvironment.cs b/test/NodeGuard.Tests/TestHelpers/TestEnvironment.cs index 66d895042..ff9894205 100644 --- a/test/NodeGuard.Tests/TestHelpers/TestEnvironment.cs +++ b/test/NodeGuard.Tests/TestHelpers/TestEnvironment.cs @@ -36,6 +36,8 @@ internal static class TestEnvironment internal static void Initialize() { SetIfMissing("NBXPLORER_URI", "http://localhost:32838"); + // The dev / e2e depth: an unset value is 0, which would settle unconfirmed withdrawals. + SetIfMissing("TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS", "6"); } private static void SetIfMissing(string name, string value) From 66bac9aa64614000037f6956a9a149bbe117623b Mon Sep 17 00:00:00 2001 From: Marcos Date: Mon, 19 Oct 2026 15:40:31 +0200 Subject: [PATCH 2/3] Keep replaced withdrawals pending until their RBF replacement confirms A withdrawal request's status now only describes its own transaction. Creating, executing or abandoning an RBF replacement never writes the request it replaces: the API derives WITHDRAWAL_BUMPED / _CANCELLED from a broadcast replacement, and the monitor stores Bumped / Cancelled only once a replacement confirms, or settles the request itself when it was mined instead. Bumped is terminal. - Replacements navigation, EffectiveStatus and the one-live-replacement guard (service check plus partial unique index) on WalletWithdrawalRequest - MonitorWithdrawalsJob: null-safe, per-row errors, floor of one confirmation, then ReconcileReplacementChainsAsync writes each linked row from its chain alone (fails every replacement of a mined original, a bump of a bump included; a bump of a cancellation still cancels) - GetWithdrawalsRequestStatusByReferenceIds returns the whole chain, and WithdrawalRequest gains replaced_by_request_id - Migration repairs legacy Bumped / RBF-cancelled rows with no confirmed replacement back to pending and guards the index creation - Withdrawals page gates bump / cancel on no live replacement, shows the derived status, and the revert paths are gone --- docker/e2e/README.md | 14 +- src/Automapper/MapperProfile.cs | 5 +- src/Data/ApplicationDbContext.cs | 14 + src/Data/Models/WalletWithdrawalRequest.cs | 70 +- .../IWalletWithdrawalRequestRepository.cs | 15 + .../WalletWithdrawalRequestRepository.cs | 104 +- src/Jobs/MonitorWithdrawalsJob.cs | 74 +- src/Jobs/PerformWithdrawalJob.cs | 9 +- ...019133733_BumpedIsTerminalOnly.Designer.cs | 2006 +++++++++++++++++ .../20261019133733_BumpedIsTerminalOnly.cs | 89 + .../ApplicationDbContextModelSnapshot.cs | 8 +- src/Pages/Withdrawals.razor | 31 +- src/Proto/nodeguard.proto | 20 +- src/Rpc/NodeGuardService.cs | 13 +- src/Services/WithdrawalRequestService.cs | 219 +- .../WalletWithdrawalRequestRepositoryTests.cs | 153 +- .../E2E/WithdrawalRbfBumpE2ETests.cs | 54 +- .../Jobs/MonitorWithdrawalsJobTests.cs | 129 +- .../Jobs/PerformWithdrawalJobTests.cs | 50 +- .../Rpc/NodeGuardServiceTests.cs | 155 ++ .../Services/WithdrawalRequestServiceTests.cs | 357 ++- 21 files changed, 3105 insertions(+), 484 deletions(-) create mode 100644 src/Migrations/20261019133733_BumpedIsTerminalOnly.Designer.cs create mode 100644 src/Migrations/20261019133733_BumpedIsTerminalOnly.cs diff --git a/docker/e2e/README.md b/docker/e2e/README.md index 06b5a84ed..dd592d4bb 100644 --- a/docker/e2e/README.md +++ b/docker/e2e/README.md @@ -70,12 +70,14 @@ tests (`DustUtxoWithdrawalE2ETests`, `WithdrawalRbfBumpE2ETests`, `GetNewWalletA those two in sync between the `nodeguard` and `e2e-runner` services**, or the test asserts against numbers NodeGuard didn't plan with. - **RBF bump scenario** (`WithdrawalRbfBumpE2ETests`): `RequestWithdrawal` on the hot wallet, then `BumpWithdrawal` - over gRPC, asserting bitcoind evicts the original for the higher-fee replacement, NodeGuard marks the original - `WITHDRAWAL_BUMPED`, and the replacement settles once mined. It relies on `MONITOR_WITHDRAWALS_CRON` being fast on - the `nodeguard` service (10s here; prod keeps the every-5-minutes default) and never mines between the two calls. - The mined-original theory mines the ORIGINAL with `generateblock` (raw tx, bypassing the mempool) after a bump or - cancel, and asserts NodeGuard settles the original and fails the replacement. The bump-of-a-bump test does the same - with three transactions (A bumped to B, B to C, A mined): A settles, C fails, B stays bumped. + over gRPC, asserting bitcoind evicts the original for the higher-fee replacement, NodeGuard reports the original + `WITHDRAWAL_BUMPED` while the replacement is in the mempool (its stored status stays pending confirmation), and once + the replacement is mined it settles and the original is stored as `WITHDRAWAL_BUMPED`. It relies on + `MONITOR_WITHDRAWALS_CRON` being fast on the `nodeguard` service (10s here; prod keeps the every-5-minutes default) + and never mines between the two calls. The mined-original theory mines the ORIGINAL with `generateblock` (raw tx, + bypassing the mempool) after a bump or cancel, and asserts NodeGuard settles the original and fails the replacement. + The bump-of-a-bump test does the same with three transactions (A bumped to B, B to C, A mined): A settles, B and C + fail. The by-reference lookup returns the whole chain, each request with its own status. - **Adding an e2e test**: put it in `[Collection("E2E")]` (so it serialises with the others on the one regtest chain — without it the class runs in parallel and they interfere), have it provision the resources it needs and reset its own state, and gate it with `[E2EFact]`. diff --git a/src/Automapper/MapperProfile.cs b/src/Automapper/MapperProfile.cs index 77680116d..2ec0843a1 100644 --- a/src/Automapper/MapperProfile.cs +++ b/src/Automapper/MapperProfile.cs @@ -60,7 +60,10 @@ public MapperProfile() .ForMember(x => x.Wallet, opt => opt.Ignore()) .ForMember(x => x.WalletWithdrawalRequestPSBTs, opt => opt.Ignore()) .ForMember(x => x.UserRequestor, opt => opt.Ignore()) - .ForMember(x => x.UTXOs, opt => opt.Ignore()); + .ForMember(x => x.UTXOs, opt => opt.Ignore()) + // Update attaches the whole mapped graph as Modified: an RBF neighbour must never ride along. + .ForMember(x => x.BumpingWalletWithdrawalRequest, opt => opt.Ignore()) + .ForMember(x => x.Replacements, opt => opt.Ignore()); CreateMap() .ForMember(x => x.TxId, opt => opt.MapFrom(x => x.Outpoint.Hash.ToString())) diff --git a/src/Data/ApplicationDbContext.cs b/src/Data/ApplicationDbContext.cs index af5617ba6..d7916d996 100644 --- a/src/Data/ApplicationDbContext.cs +++ b/src/Data/ApplicationDbContext.cs @@ -86,6 +86,20 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .IsUnique() .HasFilter("\"IsTemplatePSBT\""); + // RBF: a withdrawal may be replaced several times over its life (each replacement abandoned before the + // next), but at most one replacement may be live, or two NodeGuard transactions would compete for the + // same inputs. Partial unique index over the live statuses: Pending, PSBTSignaturesPending, + // OnChainConfirmationPending, FinalizingPSBT. Same named-overload and plain-FK-index rules as above. + modelBuilder.Entity() + .HasOne(x => x.BumpingWalletWithdrawalRequest) + .WithMany(x => x.Replacements) + .HasForeignKey(x => x.BumpingWalletWithdrawalRequestId); + modelBuilder.Entity().HasIndex(x => x.BumpingWalletWithdrawalRequestId); + modelBuilder.Entity() + .HasIndex(x => x.BumpingWalletWithdrawalRequestId, "IX_WalletWithdrawalRequests_LiveReplacement") + .IsUnique() + .HasFilter("\"BumpingWalletWithdrawalRequestId\" IS NOT NULL AND \"Status\" IN (0, 3, 4, 7)"); + modelBuilder.Entity().HasIndex(x => x.NormalizedUserName).IsUnique(); diff --git a/src/Data/Models/WalletWithdrawalRequest.cs b/src/Data/Models/WalletWithdrawalRequest.cs index b3d253322..804af0113 100644 --- a/src/Data/Models/WalletWithdrawalRequest.cs +++ b/src/Data/Models/WalletWithdrawalRequest.cs @@ -66,7 +66,8 @@ public enum WalletWithdrawalRequestStatus FinalizingPSBT = 7, /// - /// The tx was bumped by Replace by Fee (RBF) method + /// Superseded: an RBF replacement of this request (or of one of its replacements) confirmed. Terminal, written + /// only by the monitor. While a replacement is merely in flight the request keeps its own status. /// Bumped = 8 } @@ -224,10 +225,75 @@ public bool Equals(WalletWithdrawalRequest? other) /// /// True when this request replaces to CANCEL it (RBF): same inputs, - /// a single output back to the wallet, and the replaced request ends up Cancelled instead of Bumped. + /// a single output back to the wallet, and once this one confirms the replaced request ends up Cancelled + /// instead of Bumped. /// public bool IsRbfCancellation { get; set; } + /// + /// Requests that replace this one through RBF (fee bumps and cancellations). Which of them is live or confirmed + /// is what makes this request "replaced": its own status only ever describes its own transaction. + /// + public List Replacements { get; set; } = new(); + + /// + /// Statuses in which a request can still put (or has put) a transaction in the mempool. A replacement in any of + /// them blocks a second replacement of the same request (IX_WalletWithdrawalRequests_LiveReplacement). + /// + public static readonly WalletWithdrawalRequestStatus[] LiveStatuses = + { + WalletWithdrawalRequestStatus.Pending, + WalletWithdrawalRequestStatus.PSBTSignaturesPending, + WalletWithdrawalRequestStatus.FinalizingPSBT, + WalletWithdrawalRequestStatus.OnChainConfirmationPending, + }; + + [NotMapped] + public bool IsLive => LiveStatuses.Contains(Status); + + [NotMapped] + public bool IsAbandoned => Status is WalletWithdrawalRequestStatus.Failed + or WalletWithdrawalRequestStatus.Cancelled + or WalletWithdrawalRequestStatus.Rejected; + + /// The replacement still in flight, if any. Needs loaded. + [NotMapped] + public WalletWithdrawalRequest? LiveReplacement => Replacements?.FirstOrDefault(r => r.IsLive); + + /// The replacement whose transaction competes with this one's in the mempool, if any. + [NotMapped] + public WalletWithdrawalRequest? BroadcastReplacement => + Replacements?.FirstOrDefault(r => r.Status == WalletWithdrawalRequestStatus.OnChainConfirmationPending); + + public const string RbfCancellationReasonPrefix = "Cancelled by RBF replacement request"; + + public static string RbfCancellationReason(int replacementId, string? txId) => + $"{RbfCancellationReasonPrefix} {replacementId}" + (string.IsNullOrEmpty(txId) ? "" : $" (tx {txId})"); + + public static string ReplacedReason(int replacementId, string? txId) => + $"Replaced by request {replacementId}" + (string.IsNullOrEmpty(txId) ? "" : $" (tx {txId})"); + + /// + /// The status to report for this request. The stored one describes its own transaction only: while a + /// replacement's transaction is in the mempool and this one has no confirmations, it is reported as Bumped + /// (Cancelled for an RBF cancellation), the status it will be stored with once that replacement settles. + /// ReplacedById is the newest replacement that was not abandoned, so a chain can be followed by id. + /// + public (WalletWithdrawalRequestStatus Status, string? Reason, int? ReplacedById) EffectiveStatus(ulong ownConfirmations = 0) + { + var replacedBy = Replacements?.Where(r => !r.IsAbandoned).MaxBy(r => r.Id); + + if (Status == WalletWithdrawalRequestStatus.OnChainConfirmationPending && ownConfirmations == 0 + && BroadcastReplacement is { } broadcast) + { + return broadcast.IsRbfCancellation + ? (WalletWithdrawalRequestStatus.Cancelled, RbfCancellationReason(broadcast.Id, broadcast.TxId), broadcast.Id) + : (WalletWithdrawalRequestStatus.Bumped, null, broadcast.Id); + } + + return (Status, RejectCancelDescription, replacedBy?.Id); + } + public List WalletWithdrawalRequestPSBTs { get; set; } public List UTXOs { get; set; } diff --git a/src/Data/Repositories/Interfaces/IWalletWithdrawalRequestRepository.cs b/src/Data/Repositories/Interfaces/IWalletWithdrawalRequestRepository.cs index 7990ff738..06f6f0a5e 100644 --- a/src/Data/Repositories/Interfaces/IWalletWithdrawalRequestRepository.cs +++ b/src/Data/Repositories/Interfaces/IWalletWithdrawalRequestRepository.cs @@ -58,4 +58,19 @@ public interface IWalletWithdrawalRequestRepository : IBitcoinRequestRepository Task> GetPendingRequests(); Task> GetOnChainPendingWithdrawals(); + + /// Whether a request that replaces this one (RBF) is in a live status. + Task HasLiveReplacementAsync(int requestId); + + /// + /// Every request connected to this one through RBF links, in both directions, the request itself included. + /// Untracked, no navigations loaded. + /// + Task> GetRbfChainAsync(int requestId); + + /// + /// Requests in Pending, PSBTSignaturesPending or OnChainConfirmationPending that replace another request or are + /// replaced by one. Not FinalizingPSBT: PerformWithdrawal writes that row whole when it broadcasts. + /// + Task> GetLiveRbfLinkedRequestsAsync(); } \ No newline at end of file diff --git a/src/Data/Repositories/WalletWithdrawalRequestRepository.cs b/src/Data/Repositories/WalletWithdrawalRequestRepository.cs index 5da905049..ef992bd7b 100644 --- a/src/Data/Repositories/WalletWithdrawalRequestRepository.cs +++ b/src/Data/Repositories/WalletWithdrawalRequestRepository.cs @@ -66,6 +66,7 @@ INBXplorerService nBXplorerService .Include(x => x.WalletWithdrawalRequestPSBTs) .Include(x => x.WalletWithdrawalRequestDestinations) .Include(x => x.UTXOs) + .Include(x => x.Replacements) .SingleOrDefaultAsync(x => x.Id == id); return request; @@ -75,47 +76,23 @@ public async Task> GetByIds(List ids) { await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); - return await applicationDbContext.WalletWithdrawalRequests.Where(wr => ids.Contains(wr.Id)).ToListAsync(); + return await applicationDbContext.WalletWithdrawalRequests + .Include(x => x.Replacements) + .Where(wr => ids.Contains(wr.Id)) + .ToListAsync(); } public async Task> GetByReferenceIds(List referenceIds) { await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); - // RBF replacements inherit the reference id of the request they replace, so a reference id can match a whole - // chain of requests. The latest one reflects the current status of the withdrawal, unless a request it - // replaced was mined instead: that one is the payment that happened. - var requests = await applicationDbContext.WalletWithdrawalRequests + // RBF replacements inherit the reference id of the request they replace, so a reference id matches a whole + // chain. Every request of it is returned, oldest first, each reporting its own (derived) status. + return await applicationDbContext.WalletWithdrawalRequests + .Include(x => x.Replacements) .Where(wr => !string.IsNullOrEmpty(wr.ReferenceId) && referenceIds.Contains(wr.ReferenceId)) + .OrderBy(wr => wr.Id) .ToListAsync(); - - return requests - .GroupBy(wr => wr.ReferenceId!) - .Select(g => SettledInChainOrLatest(g.ToList())) - .ToList(); - } - - /// - /// Walks back from the latest request through the requests it replaced, and returns the settled one if any. - /// Only that chain: reference ids are not unique, so an unrelated earlier withdrawal must not stand in for it. - /// - private static WalletWithdrawalRequest SettledInChainOrLatest(List sameReference) - { - var byId = sameReference.ToDictionary(wr => wr.Id); - var latest = sameReference.MaxBy(wr => wr.Id)!; - - var request = latest; - while (request != null) - { - if (request.Status == WalletWithdrawalRequestStatus.OnChainConfirmed) return request; - - // A replacement is always newer than what it replaces, so ids only go down and the walk ends. - request = request.BumpingWalletWithdrawalRequestId is { } replacedId && replacedId < request.Id - ? byId.GetValueOrDefault(replacedId) - : null; - } - - return latest; } public async Task GetByTxHash(string txHash) @@ -123,6 +100,7 @@ private static WalletWithdrawalRequest SettledInChainOrLatest(List x.Replacements) .FirstOrDefaultAsync(wr => wr.TxId == txHash); } @@ -169,6 +147,7 @@ public async Task> GetAll() .Include(x => x.WalletWithdrawalRequestPSBTs) .Include(x => x.WalletWithdrawalRequestDestinations) .Include(x => x.UTXOs) + .Include(x => x.Replacements) .AsSplitQuery() .AsQueryable(); @@ -406,6 +385,65 @@ public async Task> GetPendingRequests() return walletWithdrawalRequests; } + public async Task HasLiveReplacementAsync(int requestId) + { + await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); + + var live = WalletWithdrawalRequest.LiveStatuses; + return await applicationDbContext.WalletWithdrawalRequests + .AnyAsync(x => x.BumpingWalletWithdrawalRequestId == requestId && live.Contains(x.Status)); + } + + public async Task> GetRbfChainAsync(int requestId) + { + await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); + + // Breadth-first over the link in both directions, one query per hop. Chains are a handful of rows. + var chain = new Dictionary(); + var frontier = new List { requestId }; + while (frontier.Count > 0) + { + var ids = frontier; + var hop = await applicationDbContext.WalletWithdrawalRequests + .AsNoTracking() + .Where(x => ids.Contains(x.Id) + || (x.BumpingWalletWithdrawalRequestId != null && ids.Contains(x.BumpingWalletWithdrawalRequestId.Value))) + .ToListAsync(); + + frontier = new List(); + foreach (var request in hop) + { + if (!chain.TryAdd(request.Id, request)) continue; + + frontier.Add(request.Id); + if (request.BumpingWalletWithdrawalRequestId is { } replacedId && !chain.ContainsKey(replacedId)) + { + frontier.Add(replacedId); + } + } + } + + return chain.Values.OrderBy(x => x.Id).ToList(); + } + + public async Task> GetLiveRbfLinkedRequestsAsync() + { + await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); + + var statuses = new[] + { + WalletWithdrawalRequestStatus.Pending, + WalletWithdrawalRequestStatus.PSBTSignaturesPending, + WalletWithdrawalRequestStatus.OnChainConfirmationPending, + }; + + return await applicationDbContext.WalletWithdrawalRequests + .AsNoTracking() + .Where(x => statuses.Contains(x.Status) + && (x.BumpingWalletWithdrawalRequestId != null || x.Replacements.Any())) + .ToListAsync(); + } + public async Task> GetOnChainPendingWithdrawals() { await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); diff --git a/src/Jobs/MonitorWithdrawalsJob.cs b/src/Jobs/MonitorWithdrawalsJob.cs index 6955f9276..7a44abe0c 100644 --- a/src/Jobs/MonitorWithdrawalsJob.cs +++ b/src/Jobs/MonitorWithdrawalsJob.cs @@ -26,7 +26,9 @@ namespace NodeGuard.Jobs; /// -/// Monitors that withdrawals on-chain txs are confirmed +/// Settles withdrawals whose transaction reached the confirmation depth, then gives every request linked by RBF its +/// final status from what its chain holds (a replaced request that was mined instead, a replacement that confirmed). +/// Each row is written on its own, so a failing one is retried on the next run without touching the rest. /// [DisallowConcurrentExecution] public class MonitorWithdrawalsJob : IJob @@ -53,48 +55,54 @@ public async Task Execute(IJobExecutionContext context) _logger.LogInformation($"Job {nameof(MonitorWithdrawalsJob)} started"); var withdrawalsPending = await _walletWithdrawalRequestRepository.GetOnChainPendingWithdrawals(); + // An unset TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS is 0. Replaced requests are polled too, and one whose + // transaction was evicted sits at 0 confirmations: that is not mined. + var minimumConfirmations = Math.Max(1, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS); + foreach (var walletWithdrawalRequest in withdrawalsPending) { - if (!string.IsNullOrEmpty(walletWithdrawalRequest.TxId)) + if (string.IsNullOrEmpty(walletWithdrawalRequest.TxId)) continue; + + try { - try + var getTxResult = await _nbXplorerService.GetTransactionAsync(uint256.Parse(walletWithdrawalRequest.TxId), default); + if (getTxResult == null) { - //Let's check if the minimum amount of confirmations are established - - var getTxResult = await _nbXplorerService.GetTransactionAsync(uint256.Parse(walletWithdrawalRequest.TxId), default); - - if (getTxResult.Confirmations >= Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS) - { - walletWithdrawalRequest.Status = WalletWithdrawalRequestStatus.OnChainConfirmed; + _logger.LogWarning("Transaction {TxId} of withdrawal request {RequestId} is unknown to NBXplorer", + walletWithdrawalRequest.TxId, walletWithdrawalRequest.Id); + continue; + } - var updateResult = _walletWithdrawalRequestRepository.Update(walletWithdrawalRequest); + if (getTxResult.Confirmations < minimumConfirmations) continue; - if (!updateResult.Item1) - { - _logger.LogError( - "Error while updating wallet withdrawal: {RequestId}, status: {RequestStatus}", - walletWithdrawalRequest.Id, - walletWithdrawalRequest.Status); - } - else - { - _logger.LogInformation("Updating wallet withdrawal: {RequestId} to status: {RequestStatus}", - walletWithdrawalRequest.Id, walletWithdrawalRequest.Status); - } - } - else if (walletWithdrawalRequest.BumpingWalletWithdrawalRequestId != null && getTxResult.Confirmations == 0) - { - // An RBF replacement can lose the race: the transaction it replaced may be mined instead. - await _withdrawalRequestService.SettleMinedOriginalAsync(walletWithdrawalRequest); - } + walletWithdrawalRequest.Status = WalletWithdrawalRequestStatus.OnChainConfirmed; + var (updated, _) = _walletWithdrawalRequestRepository.Update(walletWithdrawalRequest); + if (updated) + { + _logger.LogInformation("Updating wallet withdrawal: {RequestId} to status: {RequestStatus}", + walletWithdrawalRequest.Id, walletWithdrawalRequest.Status); } - catch (Exception e) + else { - _logger.LogError(e, "Error while monitoring TxId: {TxId}", walletWithdrawalRequest.TxId); - - throw new JobExecutionException(e, false); + _logger.LogError("Error while updating wallet withdrawal: {RequestId}, status: {RequestStatus}", + walletWithdrawalRequest.Id, walletWithdrawalRequest.Status); } } + catch (Exception e) + { + // One request must not stop the rest of the batch. + _logger.LogError(e, "Error while monitoring TxId: {TxId}", walletWithdrawalRequest.TxId); + } + } + + try + { + // After settling, so a request confirmed in this run already drives its RBF chain in this run. + await _withdrawalRequestService.ReconcileReplacementChainsAsync(); + } + catch (Exception e) + { + _logger.LogError(e, "Error while reconciling RBF replacement chains"); } _logger.LogInformation($"Job {nameof(MonitorWithdrawalsJob)} ended"); diff --git a/src/Jobs/PerformWithdrawalJob.cs b/src/Jobs/PerformWithdrawalJob.cs index 8a3566444..e6d5e04bd 100644 --- a/src/Jobs/PerformWithdrawalJob.cs +++ b/src/Jobs/PerformWithdrawalJob.cs @@ -36,16 +36,13 @@ public class PerformWithdrawalJob : IJob private readonly ILogger _logger; private readonly IBitcoinService _bitcoinService; private readonly IWalletWithdrawalRequestRepository _walletWithdrawalRequestRepository; - private readonly IWithdrawalRequestService _withdrawalRequestService; - public PerformWithdrawalJob(ILogger logger, IBitcoinService bitcoinService, - IWalletWithdrawalRequestRepository walletWithdrawalRequestRepository, IWithdrawalRequestService withdrawalRequestService) + IWalletWithdrawalRequestRepository walletWithdrawalRequestRepository) { _logger = logger; _bitcoinService = bitcoinService; _walletWithdrawalRequestRepository = walletWithdrawalRequestRepository; - _withdrawalRequestService = withdrawalRequestService; } public async Task Execute(IJobExecutionContext context) @@ -63,9 +60,7 @@ public async Task Execute(IJobExecutionContext context) var request = await _walletWithdrawalRequestRepository.GetById(withdrawalRequestId); if (request != null) { - // A failed replacement gives the request it replaced back its pending-confirmation status. - await _withdrawalRequestService.RevertOriginalAsync(request); - + // A failed RBF replacement needs nothing else: the request it replaced never left its own status. request.Status = WalletWithdrawalRequestStatus.Failed; var (updated, _) = _walletWithdrawalRequestRepository.Update(request); if (!updated) diff --git a/src/Migrations/20261019133733_BumpedIsTerminalOnly.Designer.cs b/src/Migrations/20261019133733_BumpedIsTerminalOnly.Designer.cs new file mode 100644 index 000000000..046b34b72 --- /dev/null +++ b/src/Migrations/20261019133733_BumpedIsTerminalOnly.Designer.cs @@ -0,0 +1,2006 @@ +// +using System; +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using NodeGuard.Data; +using NodeGuard.Helpers; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace NodeGuard.Migrations +{ + [DbContext(typeof(ApplicationDbContext))] + [Migration("20261019133733_BumpedIsTerminalOnly")] + partial class BumpedIsTerminalOnly + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.1") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("ApplicationUserNode", b => + { + b.Property("NodesId") + .HasColumnType("integer"); + + b.Property("UsersId") + .HasColumnType("text"); + + b.HasKey("NodesId", "UsersId"); + + b.HasIndex("UsersId"); + + b.ToTable("ApplicationUserNode"); + }); + + modelBuilder.Entity("ChannelOperationRequestFMUTXO", b => + { + b.Property("ChannelOperationRequestsId") + .HasColumnType("integer"); + + b.Property("UtxosId") + .HasColumnType("integer"); + + b.HasKey("ChannelOperationRequestsId", "UtxosId"); + + b.HasIndex("UtxosId"); + + b.ToTable("ChannelOperationRequestFMUTXO"); + }); + + modelBuilder.Entity("FMUTXOWalletWithdrawalRequest", b => + { + b.Property("UTXOsId") + .HasColumnType("integer"); + + b.Property("WalletWithdrawalRequestsId") + .HasColumnType("integer"); + + b.HasKey("UTXOsId", "WalletWithdrawalRequestsId"); + + b.HasIndex("WalletWithdrawalRequestsId"); + + b.ToTable("FMUTXOWalletWithdrawalRequest"); + }); + + modelBuilder.Entity("KeyWallet", b => + { + b.Property("KeysId") + .HasColumnType("integer"); + + b.Property("WalletsId") + .HasColumnType("integer"); + + b.HasKey("KeysId", "WalletsId"); + + b.HasIndex("WalletsId"); + + b.ToTable("KeyWallet"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Discriminator") + .IsRequired() + .HasMaxLength(21) + .HasColumnType("character varying(21)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + + b.HasDiscriminator().HasValue("IdentityUser"); + + b.UseTphMappingStrategy(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProviderKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Name") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.APIToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatorId") + .IsRequired() + .HasColumnType("text"); + + b.Property("ExpirationDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsBlocked") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CreatorId"); + + b.ToTable("ApiTokens"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ActionType") + .HasColumnType("integer"); + + b.Property("Details") + .HasColumnType("text"); + + b.Property("EventType") + .HasColumnType("integer"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("character varying(45)"); + + b.Property("ObjectAffected") + .HasColumnType("integer"); + + b.Property("ObjectId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("Username") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.ToTable("AuditLogs"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Channel", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BtcCloseAddress") + .HasColumnType("text"); + + b.Property("ChanId") + .HasColumnType("numeric(20,0)"); + + b.Property("ClosedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByNodeGuard") + .HasColumnType("boolean"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("DestinationNodeId") + .HasColumnType("integer"); + + b.Property("FundingTx") + .IsRequired() + .HasColumnType("text"); + + b.Property("FundingTxOutputIndex") + .HasColumnType("bigint"); + + b.Property("IsAutoRebalanceEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsAutomatedLiquidityEnabled") + .HasColumnType("boolean"); + + b.Property("IsDynamicFeeEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsPrivate") + .HasColumnType("boolean"); + + b.Property("SatsAmount") + .HasColumnType("bigint"); + + b.Property("SourceNodeId") + .HasColumnType("integer"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("DestinationNodeId"); + + b.HasIndex("SourceNodeId"); + + b.ToTable("Channels"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelFeeState", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ChannelId") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("LastAppliedInboundBaseMsat") + .HasColumnType("integer"); + + b.Property("LastAppliedInboundPpm") + .HasColumnType("integer"); + + b.Property("LastAppliedOutboundBaseFeeMsat") + .HasColumnType("bigint"); + + b.Property("LastAppliedOutboundPpm") + .HasColumnType("bigint"); + + b.Property("LastComputedTarget") + .HasColumnType("double precision"); + + b.Property("LastFeeUpdateAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastObservedRatio") + .HasColumnType("double precision"); + + b.Property("ManagedNodePubKey") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ChannelId", "ManagedNodePubKey") + .IsUnique(); + + b.ToTable("ChannelFeeStates"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOperationRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AmountCryptoUnit") + .HasColumnType("integer"); + + b.Property("Changeless") + .HasColumnType("boolean"); + + b.Property("ChannelId") + .HasColumnType("integer"); + + b.Property("ClosingReason") + .HasColumnType("text"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DestNodeId") + .HasColumnType("integer"); + + b.Property("FeeRate") + .HasColumnType("numeric"); + + b.Property("InitialChannelBaseFeeMsat") + .HasColumnType("bigint"); + + b.Property("InitialChannelFeeRatePpm") + .HasColumnType("bigint"); + + b.Property("IsChannelPrivate") + .HasColumnType("boolean"); + + b.Property("MempoolRecommendedFeesType") + .HasColumnType("integer"); + + b.Property("RequestType") + .HasColumnType("integer"); + + b.Property("SatsAmount") + .HasColumnType("bigint"); + + b.Property("SourceNodeId") + .HasColumnType("integer"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property>("StatusLogs") + .HasColumnType("jsonb"); + + b.Property("TxId") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("text"); + + b.Property("WalletId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ChannelId"); + + b.HasIndex("DestNodeId"); + + b.HasIndex("SourceNodeId"); + + b.HasIndex("UserId"); + + b.HasIndex("WalletId"); + + b.ToTable("ChannelOperationRequests"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOperationRequestPSBT", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ChannelOperationRequestId") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("IsFinalisedPSBT") + .HasColumnType("boolean"); + + b.Property("IsInternalWalletPSBT") + .HasColumnType("boolean"); + + b.Property("IsTemplatePSBT") + .HasColumnType("boolean"); + + b.Property("PSBT") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserSignerId") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ChannelOperationRequestId"); + + b.HasIndex("UserSignerId"); + + b.HasIndex(new[] { "ChannelOperationRequestId" }, "IX_ChannelOperationRequestPSBTs_Template") + .IsUnique() + .HasFilter("\"IsTemplatePSBT\""); + + b.ToTable("ChannelOperationRequestPSBTs"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelRoutingState", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AgeBlocks") + .HasColumnType("bigint"); + + b.Property("ChanIdLnd") + .HasColumnType("numeric(20,0)"); + + b.Property("ChannelId") + .HasColumnType("integer"); + + b.Property("ConsecutiveCategoryCyclesInNewState") + .HasColumnType("bigint"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("EmaLocalRatio") + .HasColumnType("double precision"); + + b.Property("FundingBlockHeight") + .HasColumnType("bigint"); + + b.Property("LastCategorizedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastEvaluatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastKnownLifetime") + .HasColumnType("bigint"); + + b.Property("LastKnownNumUpdates") + .HasColumnType("bigint"); + + b.Property("LastKnownUptime") + .HasColumnType("bigint"); + + b.Property("ManagedNodePubKey") + .IsRequired() + .HasColumnType("text"); + + b.Property("NetFlowRatio") + .HasColumnType("double precision"); + + b.Property("PeerFlowCategory") + .HasColumnType("integer"); + + b.Property("PeerInitiated") + .HasColumnType("boolean"); + + b.Property("PendingCategory") + .HasColumnType("integer"); + + b.Property("PullMsatWindow") + .HasColumnType("bigint"); + + b.Property("PushMsatWindow") + .HasColumnType("bigint"); + + b.Property("TargetLocalRatio") + .HasColumnType("double precision"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ChannelId", "ManagedNodePubKey") + .IsUnique(); + + b.ToTable("ChannelRoutingStates"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.FMUTXO", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("OutputIndex") + .HasColumnType("bigint"); + + b.Property("SatsAmount") + .HasColumnType("bigint"); + + b.Property("TxId") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.ToTable("FMUTXOs"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ForwardingHtlcEvent", b => + { + b.Property("ManagedNodePubKey") + .HasColumnType("text"); + + b.Property("IncomingChannelId") + .HasColumnType("numeric(20,0)"); + + b.Property("OutgoingChannelId") + .HasColumnType("numeric(20,0)"); + + b.Property("IncomingHtlcId") + .HasColumnType("numeric(20,0)"); + + b.Property("OutgoingHtlcId") + .HasColumnType("numeric(20,0)"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("EventCase") + .HasColumnType("integer"); + + b.Property("EventTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("EventType") + .HasColumnType("integer"); + + b.Property("FailureDetail") + .HasColumnType("integer"); + + b.Property("FailureString") + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("FeeMsat") + .HasColumnType("bigint"); + + b.Property("GrossFeeMsat") + .HasColumnType("bigint"); + + b.Property("InboundFeeMsat") + .HasColumnType("bigint"); + + b.Property("InboundFeePpm") + .HasColumnType("bigint"); + + b.Property("IncomingAmountMsat") + .HasColumnType("numeric(20,0)"); + + b.Property("IncomingPeerAlias") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IncomingTimelock") + .HasColumnType("bigint"); + + b.Property("ManagedNodeName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Outcome") + .HasColumnType("integer"); + + b.Property("OutgoingAmountMsat") + .HasColumnType("numeric(20,0)"); + + b.Property("OutgoingPeerAlias") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("OutgoingTimelock") + .HasColumnType("bigint"); + + b.Property("RoutingFeePpm") + .HasColumnType("bigint"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("WireFailureCode") + .HasColumnType("integer"); + + b.HasKey("ManagedNodePubKey", "IncomingChannelId", "OutgoingChannelId", "IncomingHtlcId", "OutgoingHtlcId"); + + b.HasIndex("CreationDatetime"); + + b.HasIndex("EventTimestamp"); + + b.ToTable("ForwardingHtlcEvents"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.InternalWallet", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("DerivationPath") + .IsRequired() + .HasColumnType("text"); + + b.Property("MasterFingerprint") + .HasColumnType("text"); + + b.Property("MnemonicString") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("XPUB") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("InternalWallets"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Key", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("InternalWalletId") + .HasColumnType("integer"); + + b.Property("IsArchived") + .HasColumnType("boolean"); + + b.Property("IsBIP39ImportedKey") + .HasColumnType("boolean"); + + b.Property("IsCompromised") + .HasColumnType("boolean"); + + b.Property("MasterFingerprint") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("Path") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("text"); + + b.Property("XPUB") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("InternalWalletId"); + + b.HasIndex("UserId"); + + b.ToTable("Keys"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.LiquidityRule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ChannelId") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("IsReverseSwapWalletRule") + .HasColumnType("boolean"); + + b.Property("MinimumLocalBalance") + .HasColumnType("numeric"); + + b.Property("MinimumRemoteBalance") + .HasColumnType("numeric"); + + b.Property("NodeId") + .HasColumnType("integer"); + + b.Property("RebalanceTarget") + .HasColumnType("numeric"); + + b.Property("ReverseSwapAddress") + .HasColumnType("text"); + + b.Property("ReverseSwapWalletId") + .HasColumnType("integer"); + + b.Property("SwapWalletId") + .HasColumnType("integer"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ChannelId") + .IsUnique(); + + b.HasIndex("NodeId"); + + b.HasIndex("ReverseSwapWalletId"); + + b.HasIndex("SwapWalletId"); + + b.ToTable("LiquidityRules"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Node", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AllowPositiveInboundFees") + .HasColumnType("boolean"); + + b.Property("AutoLiquidityManagementEnabled") + .HasColumnType("boolean"); + + b.Property("AutoRebalanceEnabled") + .HasColumnType("boolean"); + + b.Property("AutosweepEnabled") + .HasColumnType("boolean"); + + b.Property("ChannelAdminMacaroon") + .HasColumnType("text"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DynamicFeeManagementEnabled") + .HasColumnType("boolean"); + + b.Property("Endpoint") + .HasColumnType("text"); + + b.Property("FortySwapEndpoint") + .HasColumnType("text"); + + b.Property("FortySwapWeight") + .HasColumnType("integer"); + + b.Property("FundsDestinationWalletId") + .HasColumnType("integer"); + + b.Property("IsNodeDisabled") + .HasColumnType("boolean"); + + b.Property("LoopSwapWeight") + .HasColumnType("integer"); + + b.Property("LoopdCert") + .HasColumnType("text"); + + b.Property("LoopdEndpoint") + .HasColumnType("text"); + + b.Property("LoopdMacaroon") + .HasColumnType("text"); + + b.Property("MaxRebalanceCostToEarnRatio") + .HasColumnType("double precision"); + + b.Property("MaxRebalancesInFlight") + .HasColumnType("integer"); + + b.Property("MaxSwapRoutingFeeRatio") + .HasColumnType("numeric"); + + b.Property("MaxSwapsInFlight") + .HasColumnType("integer"); + + b.Property("MinimumBalanceThresholdSats") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("PubKey") + .IsRequired() + .HasColumnType("text"); + + b.Property("RebalanceBudgetRefreshInterval") + .HasColumnType("interval"); + + b.Property("RebalanceBudgetSats") + .HasColumnType("bigint"); + + b.Property("RebalanceBudgetStartDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("RoutingEngineDryRun") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("SparkSwapWeight") + .HasColumnType("integer"); + + b.Property("SparkWalletId") + .HasColumnType("integer"); + + b.Property("SwapBudgetRefreshInterval") + .HasColumnType("interval"); + + b.Property("SwapBudgetSats") + .HasColumnType("bigint"); + + b.Property("SwapBudgetStartDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("SwapMaxAmountSats") + .HasColumnType("bigint"); + + b.Property("SwapMinAmountSats") + .HasColumnType("bigint"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("FundsDestinationWalletId"); + + b.HasIndex("PubKey") + .IsUnique(); + + b.HasIndex("SparkWalletId"); + + b.ToTable("Nodes"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Rebalance", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AmountBackoffRatio") + .HasColumnType("double precision"); + + b.Property("AttemptNumber") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("FeePaidMsat") + .HasColumnType("bigint"); + + b.Property("FeePaidSats") + .HasColumnType("bigint"); + + b.Property("IsManual") + .HasColumnType("boolean"); + + b.Property("MaxAttempts") + .HasColumnType("integer"); + + b.Property("MaxFeePct") + .HasColumnType("double precision"); + + b.Property("NodeId") + .HasColumnType("integer"); + + b.Property("PaymentHashHex") + .HasColumnType("text"); + + b.Property("PaymentRequest") + .HasColumnType("text"); + + b.Property("PreimageHex") + .HasColumnType("text"); + + b.Property("RequestedAmountSats") + .HasColumnType("bigint"); + + b.Property("RetryMaxFeePct") + .HasColumnType("double precision"); + + b.Property("SatsAmount") + .HasColumnType("bigint"); + + b.Property("SourceChanIdLnd") + .HasColumnType("numeric(20,0)"); + + b.Property("SourceChannelId") + .HasColumnType("integer"); + + b.Property("SourceNodePubKey") + .HasColumnType("text"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TargetPubkey") + .HasColumnType("text"); + + b.Property("TimeoutSeconds") + .HasColumnType("integer"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserRequestorId") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("NodeId"); + + b.HasIndex("SourceChannelId"); + + b.HasIndex("UserRequestorId"); + + b.ToTable("Rebalances"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.SwapOut", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("DestinationAddress") + .HasColumnType("text"); + + b.Property("DestinationWalletId") + .HasColumnType("integer"); + + b.Property("ErrorDetails") + .HasColumnType("text"); + + b.Property("IsManual") + .HasColumnType("boolean"); + + b.Property("LightningFeeSats") + .HasColumnType("bigint"); + + b.Property("NodeId") + .HasColumnType("integer"); + + b.Property("OnChainFeeSats") + .HasColumnType("bigint"); + + b.Property("PaymentHash") + .HasColumnType("text"); + + b.Property("PayoutSats") + .HasColumnType("bigint"); + + b.Property("Provider") + .HasColumnType("integer"); + + b.Property("ProviderId") + .HasColumnType("text"); + + b.Property("ReferenceId") + .HasColumnType("text"); + + b.Property("SatsAmount") + .HasColumnType("bigint"); + + b.Property("ServiceFeeSats") + .HasColumnType("bigint"); + + b.Property("SparkIdentity") + .HasColumnType("text"); + + b.Property("SparkLeafIds") + .HasColumnType("text"); + + b.Property("SparkReceivedSats") + .HasColumnType("bigint"); + + b.Property("SparkTransferId") + .HasColumnType("text"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TxId") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserRequestorId") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("DestinationWalletId"); + + b.HasIndex("NodeId"); + + b.HasIndex("ReferenceId") + .IsUnique() + .HasFilter("\"ReferenceId\" IS NOT NULL"); + + b.HasIndex("UserRequestorId"); + + b.ToTable("SwapOuts"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.UTXOTag", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Key") + .IsRequired() + .HasColumnType("text"); + + b.Property("Outpoint") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Key", "Outpoint") + .IsUnique(); + + b.ToTable("UTXOTags"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Wallet", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BIP39Seedphrase") + .HasColumnType("text"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("ImportedOutputDescriptor") + .HasColumnType("text"); + + b.Property("InternalWalletId") + .HasColumnType("integer"); + + b.Property("InternalWalletMasterFingerprint") + .HasColumnType("text"); + + b.Property("InternalWalletSubDerivationPath") + .HasColumnType("text"); + + b.Property("IsArchived") + .HasColumnType("boolean"); + + b.Property("IsBIP39Imported") + .HasColumnType("boolean"); + + b.Property("IsCompromised") + .HasColumnType("boolean"); + + b.Property("IsFinalised") + .HasColumnType("boolean"); + + b.Property("IsHotWallet") + .HasColumnType("boolean"); + + b.Property("IsUnSortedMultiSig") + .HasColumnType("boolean"); + + b.Property("Kind") + .HasColumnType("integer"); + + b.Property("MofN") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ReferenceId") + .HasColumnType("text"); + + b.Property("SparkAccount") + .HasColumnType("integer"); + + b.Property("SparkEncryptedMnemonic") + .HasColumnType("text"); + + b.Property("SparkIdentityPublicKey") + .HasColumnType("text"); + + b.Property("SparkMaxBalanceSats") + .HasColumnType("bigint"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("WalletAddressType") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("InternalWalletId"); + + b.HasIndex("InternalWalletSubDerivationPath", "InternalWalletMasterFingerprint") + .IsUnique(); + + b.ToTable("Wallets"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BumpingWalletWithdrawalRequestId") + .HasColumnType("integer"); + + b.Property("Changeless") + .HasColumnType("boolean"); + + b.Property("CoinSelectionStrategy") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("CustomFeeRate") + .HasColumnType("numeric"); + + b.Property("Description") + .IsRequired() + .HasColumnType("text"); + + b.Property("IsRbfCancellation") + .HasColumnType("boolean"); + + b.Property("MempoolRecommendedFeesType") + .HasColumnType("integer"); + + b.Property("ReferenceId") + .HasColumnType("text"); + + b.Property("RejectCancelDescription") + .HasColumnType("text"); + + b.Property("RequestMetadata") + .HasColumnType("text"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TxId") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserRequestorId") + .HasColumnType("text"); + + b.Property("WalletId") + .HasColumnType("integer"); + + b.Property("WithdrawAllFunds") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("BumpingWalletWithdrawalRequestId"); + + b.HasIndex("UserRequestorId"); + + b.HasIndex("WalletId"); + + b.HasIndex(new[] { "BumpingWalletWithdrawalRequestId" }, "IX_WalletWithdrawalRequests_LiveReplacement") + .IsUnique() + .HasFilter("\"BumpingWalletWithdrawalRequestId\" IS NOT NULL AND \"Status\" IN (0, 3, 4, 7)"); + + b.ToTable("WalletWithdrawalRequests"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequestDestination", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasColumnType("text"); + + b.Property("Amount") + .HasColumnType("numeric"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("WalletWithdrawalRequestId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("WalletWithdrawalRequestId"); + + b.ToTable("WalletWithdrawalRequestDestinations"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequestPSBT", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("IsFinalisedPSBT") + .HasColumnType("boolean"); + + b.Property("IsInternalWalletPSBT") + .HasColumnType("boolean"); + + b.Property("IsTemplatePSBT") + .HasColumnType("boolean"); + + b.Property("PSBT") + .IsRequired() + .HasColumnType("text"); + + b.Property("SignerId") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("WalletWithdrawalRequestId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("SignerId"); + + b.HasIndex("WalletWithdrawalRequestId"); + + b.HasIndex(new[] { "WalletWithdrawalRequestId" }, "IX_WalletWithdrawalRequestPSBTs_Template") + .IsUnique() + .HasFilter("\"IsTemplatePSBT\""); + + b.ToTable("WalletWithdrawalRequestPSBTs"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ApplicationUser", b => + { + b.HasBaseType("Microsoft.AspNetCore.Identity.IdentityUser"); + + b.HasDiscriminator().HasValue("ApplicationUser"); + }); + + modelBuilder.Entity("ApplicationUserNode", b => + { + b.HasOne("NodeGuard.Data.Models.Node", null) + .WithMany() + .HasForeignKey("NodesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", null) + .WithMany() + .HasForeignKey("UsersId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ChannelOperationRequestFMUTXO", b => + { + b.HasOne("NodeGuard.Data.Models.ChannelOperationRequest", null) + .WithMany() + .HasForeignKey("ChannelOperationRequestsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.FMUTXO", null) + .WithMany() + .HasForeignKey("UtxosId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("FMUTXOWalletWithdrawalRequest", b => + { + b.HasOne("NodeGuard.Data.Models.FMUTXO", null) + .WithMany() + .HasForeignKey("UTXOsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.WalletWithdrawalRequest", null) + .WithMany() + .HasForeignKey("WalletWithdrawalRequestsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("KeyWallet", b => + { + b.HasOne("NodeGuard.Data.Models.Key", null) + .WithMany() + .HasForeignKey("KeysId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Wallet", null) + .WithMany() + .HasForeignKey("WalletsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.APIToken", b => + { + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "Creator") + .WithMany() + .HasForeignKey("CreatorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Creator"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Channel", b => + { + b.HasOne("NodeGuard.Data.Models.Node", "DestinationNode") + .WithMany() + .HasForeignKey("DestinationNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Node", "SourceNode") + .WithMany() + .HasForeignKey("SourceNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DestinationNode"); + + b.Navigation("SourceNode"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelFeeState", b => + { + b.HasOne("NodeGuard.Data.Models.Channel", "Channel") + .WithMany() + .HasForeignKey("ChannelId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Channel"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOperationRequest", b => + { + b.HasOne("NodeGuard.Data.Models.Channel", "Channel") + .WithMany("ChannelOperationRequests") + .HasForeignKey("ChannelId"); + + b.HasOne("NodeGuard.Data.Models.Node", "DestNode") + .WithMany("ChannelOperationRequestsAsDestination") + .HasForeignKey("DestNodeId"); + + b.HasOne("NodeGuard.Data.Models.Node", "SourceNode") + .WithMany("ChannelOperationRequestsAsSource") + .HasForeignKey("SourceNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "User") + .WithMany("ChannelOperationRequests") + .HasForeignKey("UserId"); + + b.HasOne("NodeGuard.Data.Models.Wallet", "Wallet") + .WithMany("ChannelOperationRequestsAsSource") + .HasForeignKey("WalletId"); + + b.Navigation("Channel"); + + b.Navigation("DestNode"); + + b.Navigation("SourceNode"); + + b.Navigation("User"); + + b.Navigation("Wallet"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOperationRequestPSBT", b => + { + b.HasOne("NodeGuard.Data.Models.ChannelOperationRequest", "ChannelOperationRequest") + .WithMany("ChannelOperationRequestPsbts") + .HasForeignKey("ChannelOperationRequestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "UserSigner") + .WithMany() + .HasForeignKey("UserSignerId"); + + b.Navigation("ChannelOperationRequest"); + + b.Navigation("UserSigner"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelRoutingState", b => + { + b.HasOne("NodeGuard.Data.Models.Channel", "Channel") + .WithMany() + .HasForeignKey("ChannelId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Channel"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Key", b => + { + b.HasOne("NodeGuard.Data.Models.InternalWallet", "InternalWallet") + .WithMany() + .HasForeignKey("InternalWalletId"); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "User") + .WithMany("Keys") + .HasForeignKey("UserId"); + + b.Navigation("InternalWallet"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.LiquidityRule", b => + { + b.HasOne("NodeGuard.Data.Models.Channel", "Channel") + .WithMany("LiquidityRules") + .HasForeignKey("ChannelId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Node", "Node") + .WithMany() + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Wallet", "ReverseSwapWallet") + .WithMany("LiquidityRulesAsReverseSwapWallet") + .HasForeignKey("ReverseSwapWalletId"); + + b.HasOne("NodeGuard.Data.Models.Wallet", "SwapWallet") + .WithMany("LiquidityRulesAsSwapWallet") + .HasForeignKey("SwapWalletId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Channel"); + + b.Navigation("Node"); + + b.Navigation("ReverseSwapWallet"); + + b.Navigation("SwapWallet"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Node", b => + { + b.HasOne("NodeGuard.Data.Models.Wallet", "FundsDestinationWallet") + .WithMany() + .HasForeignKey("FundsDestinationWalletId"); + + b.HasOne("NodeGuard.Data.Models.Wallet", null) + .WithMany() + .HasForeignKey("SparkWalletId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("FundsDestinationWallet"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Rebalance", b => + { + b.HasOne("NodeGuard.Data.Models.Node", "Node") + .WithMany() + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Channel", "SourceChannel") + .WithMany() + .HasForeignKey("SourceChannelId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "UserRequestor") + .WithMany() + .HasForeignKey("UserRequestorId"); + + b.Navigation("Node"); + + b.Navigation("SourceChannel"); + + b.Navigation("UserRequestor"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.SwapOut", b => + { + b.HasOne("NodeGuard.Data.Models.Wallet", "DestinationWallet") + .WithMany("SwapOuts") + .HasForeignKey("DestinationWalletId"); + + b.HasOne("NodeGuard.Data.Models.Node", "Node") + .WithMany("SwapOuts") + .HasForeignKey("NodeId"); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "UserRequestor") + .WithMany() + .HasForeignKey("UserRequestorId"); + + b.Navigation("DestinationWallet"); + + b.Navigation("Node"); + + b.Navigation("UserRequestor"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Wallet", b => + { + b.HasOne("NodeGuard.Data.Models.InternalWallet", "InternalWallet") + .WithMany() + .HasForeignKey("InternalWalletId"); + + b.Navigation("InternalWallet"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequest", b => + { + b.HasOne("NodeGuard.Data.Models.WalletWithdrawalRequest", "BumpingWalletWithdrawalRequest") + .WithMany("Replacements") + .HasForeignKey("BumpingWalletWithdrawalRequestId"); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "UserRequestor") + .WithMany("WalletWithdrawalRequests") + .HasForeignKey("UserRequestorId"); + + b.HasOne("NodeGuard.Data.Models.Wallet", "Wallet") + .WithMany() + .HasForeignKey("WalletId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("BumpingWalletWithdrawalRequest"); + + b.Navigation("UserRequestor"); + + b.Navigation("Wallet"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequestDestination", b => + { + b.HasOne("NodeGuard.Data.Models.WalletWithdrawalRequest", "WalletWithdrawalRequest") + .WithMany("WalletWithdrawalRequestDestinations") + .HasForeignKey("WalletWithdrawalRequestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("WalletWithdrawalRequest"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequestPSBT", b => + { + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "Signer") + .WithMany() + .HasForeignKey("SignerId"); + + b.HasOne("NodeGuard.Data.Models.WalletWithdrawalRequest", "WalletWithdrawalRequest") + .WithMany("WalletWithdrawalRequestPSBTs") + .HasForeignKey("WalletWithdrawalRequestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Signer"); + + b.Navigation("WalletWithdrawalRequest"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Channel", b => + { + b.Navigation("ChannelOperationRequests"); + + b.Navigation("LiquidityRules"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOperationRequest", b => + { + b.Navigation("ChannelOperationRequestPsbts"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Node", b => + { + b.Navigation("ChannelOperationRequestsAsDestination"); + + b.Navigation("ChannelOperationRequestsAsSource"); + + b.Navigation("SwapOuts"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Wallet", b => + { + b.Navigation("ChannelOperationRequestsAsSource"); + + b.Navigation("LiquidityRulesAsReverseSwapWallet"); + + b.Navigation("LiquidityRulesAsSwapWallet"); + + b.Navigation("SwapOuts"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequest", b => + { + b.Navigation("Replacements"); + + b.Navigation("WalletWithdrawalRequestDestinations"); + + b.Navigation("WalletWithdrawalRequestPSBTs"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ApplicationUser", b => + { + b.Navigation("ChannelOperationRequests"); + + b.Navigation("Keys"); + + b.Navigation("WalletWithdrawalRequests"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Migrations/20261019133733_BumpedIsTerminalOnly.cs b/src/Migrations/20261019133733_BumpedIsTerminalOnly.cs new file mode 100644 index 000000000..a3f63f751 --- /dev/null +++ b/src/Migrations/20261019133733_BumpedIsTerminalOnly.cs @@ -0,0 +1,89 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace NodeGuard.Migrations +{ + /// + /// Bumped becomes terminal: a withdrawal request's status describes only its own transaction. + /// + /// Until now a request was marked Bumped (or Cancelled with a "Cancelled by RBF replacement request N" reason) as + /// soon as its RBF replacement was executed, and reverted if the replacement was abandoned. From now on nothing + /// writes the replaced request while the replacement is in flight: the API derives what it reports from the + /// replacement, and the monitor stores Bumped / Cancelled only once a replacement confirms, or settles the + /// request itself when it was mined instead. + /// + /// + /// Existing rows are repaired here, in SQL. A Bumped or RBF-cancelled request none of whose replacements (direct + /// or through further replacements) confirmed goes back to OnChainConfirmationPending: its own transaction is + /// still the live candidate, so the monitor polls it again and the UI offers to replace it again. Rows whose + /// replacement confirmed are already in their final status and are left alone. + /// + /// + /// Then a partial unique index guarantees at most one live replacement per request. The migration raises a + /// readable error when existing data violates that, instead of a bare unique-constraint failure. + /// + /// + public partial class BumpedIsTerminalOnly : Migration + { + // WalletWithdrawalRequestStatus: Pending = 0, Cancelled = 1, PSBTSignaturesPending = 3, + // OnChainConfirmationPending = 4, OnChainConfirmed = 5, FinalizingPSBT = 7, Bumped = 8 + private const string Repair = @" +WITH RECURSIVE roots AS ( + SELECT ""Id"" FROM ""WalletWithdrawalRequests"" + WHERE ""Status"" = 8 + OR (""Status"" = 1 AND ""RejectCancelDescription"" LIKE 'Cancelled by RBF replacement request%') +), descendants AS ( + SELECT r.""Id"" AS root_id, r.""Id"" AS node_id FROM roots r + UNION + SELECT d.root_id, c.""Id"" FROM descendants d + JOIN ""WalletWithdrawalRequests"" c ON c.""BumpingWalletWithdrawalRequestId"" = d.node_id +), settled AS ( + SELECT DISTINCT d.root_id FROM descendants d + JOIN ""WalletWithdrawalRequests"" n ON n.""Id"" = d.node_id + WHERE n.""Id"" <> d.root_id AND n.""Status"" = 5 +) +UPDATE ""WalletWithdrawalRequests"" w +SET ""Status"" = 4, + ""RejectCancelDescription"" = CASE WHEN w.""Status"" = 1 THEN NULL ELSE w.""RejectCancelDescription"" END, + ""UpdateDatetime"" = now() +WHERE w.""Id"" IN (SELECT ""Id"" FROM roots) AND w.""Id"" NOT IN (SELECT root_id FROM settled);"; + + private const string Guard = @" +DO $$ +DECLARE v text; +BEGIN + SELECT string_agg(format('%s -> {%s}', orig, reps), '; ') INTO v FROM ( + SELECT ""BumpingWalletWithdrawalRequestId"" AS orig, string_agg(""Id""::text, ',' ORDER BY ""Id"") AS reps + FROM ""WalletWithdrawalRequests"" + WHERE ""BumpingWalletWithdrawalRequestId"" IS NOT NULL AND ""Status"" IN (0, 3, 4, 7) + GROUP BY 1 HAVING count(*) > 1) x; + IF v IS NOT NULL THEN + RAISE EXCEPTION 'Withdrawal requests with more than one live RBF replacement, resolve them by hand before migrating: %', v; + END IF; +END $$;"; + + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.Sql(Repair); + migrationBuilder.Sql(Guard); + + migrationBuilder.CreateIndex( + name: "IX_WalletWithdrawalRequests_LiveReplacement", + table: "WalletWithdrawalRequests", + column: "BumpingWalletWithdrawalRequestId", + unique: true, + filter: "\"BumpingWalletWithdrawalRequestId\" IS NOT NULL AND \"Status\" IN (0, 3, 4, 7)"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + // The data repair is not reversed: the revived rows are pending confirmation, which is what they are. + migrationBuilder.DropIndex( + name: "IX_WalletWithdrawalRequests_LiveReplacement", + table: "WalletWithdrawalRequests"); + } + } +} diff --git a/src/Migrations/ApplicationDbContextModelSnapshot.cs b/src/Migrations/ApplicationDbContextModelSnapshot.cs index 2f7cb187b..cbf5b6af5 100644 --- a/src/Migrations/ApplicationDbContextModelSnapshot.cs +++ b/src/Migrations/ApplicationDbContextModelSnapshot.cs @@ -1475,6 +1475,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasIndex("WalletId"); + b.HasIndex(new[] { "BumpingWalletWithdrawalRequestId" }, "IX_WalletWithdrawalRequests_LiveReplacement") + .IsUnique() + .HasFilter("\"BumpingWalletWithdrawalRequestId\" IS NOT NULL AND \"Status\" IN (0, 3, 4, 7)"); + b.ToTable("WalletWithdrawalRequests"); }); @@ -1896,7 +1900,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequest", b => { b.HasOne("NodeGuard.Data.Models.WalletWithdrawalRequest", "BumpingWalletWithdrawalRequest") - .WithMany() + .WithMany("Replacements") .HasForeignKey("BumpingWalletWithdrawalRequestId"); b.HasOne("NodeGuard.Data.Models.ApplicationUser", "UserRequestor") @@ -1978,6 +1982,8 @@ protected override void BuildModel(ModelBuilder modelBuilder) modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequest", b => { + b.Navigation("Replacements"); + b.Navigation("WalletWithdrawalRequestDestinations"); b.Navigation("WalletWithdrawalRequestPSBTs"); diff --git a/src/Pages/Withdrawals.razor b/src/Pages/Withdrawals.razor index a7a98c9b0..c75f9e0ba 100644 --- a/src/Pages/Withdrawals.razor +++ b/src/Pages/Withdrawals.razor @@ -416,8 +416,12 @@ - - @context?.Status.Humanize() + @{ + // A replaced request keeps its own stored status; the UI shows what the API reports. + var (effectiveStatus, effectiveReason, replacedById) = context.EffectiveStatus(); + } + + @effectiveStatus.Humanize()@(replacedById is { } replacedBy ? $" · replaced by #{replacedBy}" : "") @@ -441,7 +445,7 @@ - @if (_isFinanceManager && context.Status == WalletWithdrawalRequestStatus.OnChainConfirmationPending) + @if (_isFinanceManager && context.Status == WalletWithdrawalRequestStatus.OnChainConfirmationPending && context.LiveReplacement == null) { @@ -985,7 +989,14 @@ await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, request, "Bump requested for withdrawal not pending on-chain confirmation."); return; } - + + if (request.LiveReplacement is { } liveReplacement) + { + ToastService.ShowError($"This withdrawal is already being replaced by request {liveReplacement.Id}. Bump or cancel that request instead."); + await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, request, $"Bump requested for withdrawal already replaced by request {liveReplacement.Id}."); + return; + } + ulong confirmations = 0; if (!string.IsNullOrEmpty(request.TxId)) { @@ -1072,14 +1083,7 @@ _selectedRequest = await WalletWithdrawalRequestRepository.GetById(_selectedRequest.Id); if (_selectedRequest != null) { - // Mark the replaced request before the job runs, so a failed broadcast's revert has the last word. - await WithdrawalRequestService.MarkOriginalAsReplacedAsync(_selectedRequest); await CreateJob(); - // CreateJob reports a scheduling failure by failing the request. - if (_selectedRequest?.Status == WalletWithdrawalRequestStatus.Failed) - { - await WithdrawalRequestService.RevertOriginalAsync(_selectedRequest); - } } } catch (Exception ex) @@ -1192,9 +1196,6 @@ await LogWithdrawalAuditAsync(successAction, AuditEventType.Success, _selectedRequest, successMessage); } - // In case that is a bump, we return the old request status to pending confirmation. - await WithdrawalRequestService.RevertOriginalAsync(_selectedRequest); - await HideRejectCancelModal(); } } @@ -1340,7 +1341,7 @@ await LogWithdrawalAuditAsync(AuditActionType.Create, AuditEventType.Success, _selectedRequest, "Withdrawal request created."); // Moves the request to PSBTSignaturesPending (the status PerformWithdrawal requires), generates the template - // PSBT, marks a replaced request as Bumped and schedules PerformWithdrawalJob to sign and broadcast. + // PSBT and schedules PerformWithdrawalJob to sign and broadcast. await WithdrawalRequestService.ScheduleHotWalletWithdrawalAsync(_selectedRequest.Id); ToastService.ShowSuccess("Withdrawal scheduled for signing and broadcast"); diff --git a/src/Proto/nodeguard.proto b/src/Proto/nodeguard.proto index b34e7ff91..6cfe4587e 100644 --- a/src/Proto/nodeguard.proto +++ b/src/Proto/nodeguard.proto @@ -24,8 +24,12 @@ service NodeGuardService { /* Replaces a withdrawal that is still waiting for on-chain confirmation with a higher-fee version of the same transaction (RBF): same inputs, same destinations, the extra fee is taken from the change. Cold wallets get a new - request that waits for approvals like RequestWithdrawal; hot wallets sign and broadcast it asynchronously and the - replaced request moves to WITHDRAWAL_BUMPED. + request that waits for approvals like RequestWithdrawal; hot wallets sign and broadcast it asynchronously. + The replaced request keeps its own status. While the replacement's transaction is in the mempool it is reported as + WITHDRAWAL_BUMPED with replaced_by_request_id set, and that becomes its stored status once the replacement settles. + If the replaced transaction is mined instead, it settles and the replacement fails. If the replacement is abandoned + (cancelled, rejected, failed) the replaced request reports WITHDRAWAL_PENDING_CONFIRMATION again. + Fails with FAILED_PRECONDITION when the request is not pending confirmation or already has a live replacement. */ rpc BumpWithdrawal(BumpWithdrawalRequest) returns (BumpWithdrawalResponse); @@ -33,7 +37,8 @@ service NodeGuardService { Cancels a withdrawal that is still waiting for on-chain confirmation by replacing its transaction (RBF) with one that spends the same inputs and returns the funds, minus a higher fee, to a fresh address of the wallet, so the original payment never confirms. Cold wallets get a new request that waits for approvals like RequestWithdrawal; - hot wallets sign and broadcast it asynchronously and the replaced request moves to WITHDRAWAL_CANCELLED. + hot wallets sign and broadcast it asynchronously. Same status rules as BumpWithdrawal, with the replaced request + reported and then stored as WITHDRAWAL_CANCELLED instead of WITHDRAWAL_BUMPED. */ rpc CancelWithdrawal(CancelWithdrawalRequest) returns (CancelWithdrawalResponse); /* @@ -92,7 +97,9 @@ service NodeGuardService { rpc GetWithdrawalsRequestStatus(GetWithdrawalsRequestStatusRequest) returns (GetWithdrawalsRequestStatusResponse); /* - Gets the status for the provided withdrawals request reference ids + Gets the status of every withdrawal request carrying one of the provided reference ids, oldest first. RBF + replacements inherit the reference id of the request they replace, so a reference id returns the whole chain: the + original and each of its bumps or cancellations, each with its own status and replaced_by_request_id. */ rpc GetWithdrawalsRequestStatusByReferenceIds(GetWithdrawalsRequestStatusByReferenceIdsRequest) returns (GetWithdrawalsRequestStatusResponse); @@ -518,6 +525,8 @@ enum WITHDRAWAL_REQUEST_STATUS { WITHDRAWAL_REJECTED = 3; WITHDRAWAL_PENDING_CONFIRMATION = 4; WITHDRAWAL_FAILED = 5; + // Superseded by an RBF replacement (see BumpWithdrawal): reported while the replacement's transaction is in the + // mempool, stored once it settles. The payment happened through the request in replaced_by_request_id. WITHDRAWAL_BUMPED = 6; } @@ -534,6 +543,9 @@ message WithdrawalRequest { optional string tx_id = 6; // in JSON format optional string request_metadata = 7; + // Newest RBF replacement of this request that was not abandoned, set as soon as it exists, even while it is still + // awaiting approval. Follow it to find the transaction that superseded (or will supersede) this one. + optional int32 replaced_by_request_id = 8; } message GetWithdrawalsRequestStatusResponse { diff --git a/src/Rpc/NodeGuardService.cs b/src/Rpc/NodeGuardService.cs index ed79302bb..df9182b91 100644 --- a/src/Rpc/NodeGuardService.cs +++ b/src/Rpc/NodeGuardService.cs @@ -1349,16 +1349,21 @@ private async Task GetWithdrawalsRequestSta confirmations = (ulong)(nbxplorerStatus?.Confirmations ?? 0); } - withdrawalsResponses.Add(new WithdrawalRequest + // A replaced request keeps its own stored status; what the client sees is derived from its replacements. + var (status, reason, replacedById) = withdrawalRequest.EffectiveStatus(confirmations); + var response = new WithdrawalRequest { RequestId = withdrawalRequest.Id, - Status = GetStatus(withdrawalRequest.Status), - RejectOrCancelReason = withdrawalRequest.RejectCancelDescription ?? "", + Status = GetStatus(status), + RejectOrCancelReason = reason ?? "", ReferenceId = withdrawalRequest.ReferenceId ?? "", Confirmations = confirmations, TxId = withdrawalRequest.TxId ?? "", RequestMetadata = withdrawalRequest.RequestMetadata ?? "", - }); + }; + if (replacedById is { } id) response.ReplacedByRequestId = id; + + withdrawalsResponses.Add(response); } return new GetWithdrawalsRequestStatusResponse() diff --git a/src/Services/WithdrawalRequestService.cs b/src/Services/WithdrawalRequestService.cs index d5e271b6d..70f70a168 100644 --- a/src/Services/WithdrawalRequestService.cs +++ b/src/Services/WithdrawalRequestService.cs @@ -34,6 +34,11 @@ namespace NodeGuard.Services; /// Keeping the orchestration here, rather than in BumpfeeModal.razor / Withdrawals.razor, lets the gRPC API expose it and the /// E2E suite exercise the same code the pages run. Hot-wallet requests are moved to PSBTSignaturesPending explicitly: it is /// the status PerformWithdrawal requires, and a hot wallet has no approvers whose signatures would get it there. +/// +/// RBF rule: a request's status only ever describes its own transaction. Creating, executing or abandoning a +/// replacement never writes the request it replaces; "replaced" is derived from the replacement +/// (), and the replaced request gets its final status +/// (Bumped, Cancelled, or OnChainConfirmed when it won the race) from . /// public interface IWithdrawalRequestService { @@ -50,41 +55,29 @@ Task CreateBumpRequestAsync(int originalRequestId, Memp /// /// Validates and creates the RBF CANCELLATION of a withdrawal that is waiting for on-chain confirmation: the same /// locked UTXOs, a higher fee rate, and a single output that returns the funds to a fresh address of the wallet, so - /// the original payment never confirms. Same status rules as ; once executed the - /// replaced request ends up Cancelled instead of Bumped. + /// the original payment never confirms. Same status rules as ; once the + /// cancellation confirms the replaced request ends up Cancelled instead of Bumped. /// Task CreateCancelRequestAsync(int originalRequestId, MempoolRecommendedFeesType feeType, decimal? customFeeRate); /// - /// Executes a hot-wallet request (fresh or bump): moves it to PSBTSignaturesPending, generates and persists the - /// template PSBT, marks the request it replaces (if any) as Bumped and schedules , - /// which signs and broadcasts. On failure the replaced request is put back to OnChainConfirmationPending and the - /// exception is rethrown; the caller decides what happens to the request itself. + /// Executes a hot-wallet request (fresh or replacement): moves it to PSBTSignaturesPending, generates and persists + /// the template PSBT and schedules , which signs and broadcasts. On failure the + /// exception is rethrown and the caller decides what happens to the request; the request it replaces, if any, is + /// never touched. /// /// The template PSBT; its global transaction hash is the txid that will be broadcast. Task ScheduleHotWalletWithdrawalAsync(int requestId); /// - /// Marks the request replaced by as Bumped (fee bump) or Cancelled (RBF cancellation). - /// Cold-wallet flow: called when the last human signature lands, before the withdrawal job is scheduled. No-op when - /// the request is not a replacement or the replaced request is no longer pending confirmation. - /// - Task MarkOriginalAsReplacedAsync(WalletWithdrawalRequest replacement); - - /// - /// Puts the request replaced by back to OnChainConfirmationPending when the replacement - /// is abandoned (cancelled, rejected or failed) and the original had already been marked Bumped / Cancelled by it. - /// No-op otherwise. + /// Gives every live request linked by RBF its final status once its chain holds a confirmed transaction, from the + /// database alone. A request whose original (direct or through earlier replacements) confirmed fails: RBF does + /// not guarantee the replacement wins. A request one of whose replacements confirmed becomes Bumped, or + /// Cancelled when the confirmed replacement cancels it. Each request writes only its own row, so a failed write + /// is simply retried on the next run. Run by after it settles confirmations. /// - Task RevertOriginalAsync(WalletWithdrawalRequest replacement); - - /// - /// RBF does not guarantee the replacement wins: a miner can still mine a transaction it replaced. When a request - /// replaced, directly or through earlier replacements, has a transaction with the - /// settlement confirmations, that request is settled and the replacement fails. Returns whether that happened. - /// - Task SettleMinedOriginalAsync(WalletWithdrawalRequest replacement); + Task ReconcileReplacementChainsAsync(); } public class WithdrawalRequestService : IWithdrawalRequestService @@ -143,6 +136,13 @@ private async Task CreateReplacementAsync(int originalR BumpingErrorReason.InvalidState); } + if (original.LiveReplacement is { } live) + { + throw new BumpingException( + $"Withdrawal request {original.Id} is already being replaced by request {live.Id}; replace that request instead.", + BumpingErrorReason.InvalidState); + } + if (string.IsNullOrEmpty(original.TxId)) { throw new BumpingException("The withdrawal request has no transaction to replace.", @@ -268,6 +268,14 @@ private async Task CreateReplacementAsync(int originalR var (added, addError) = await _walletWithdrawalRequestRepository.AddAsync(replacement); if (!added) { + // The database lets one live replacement per request through; a concurrent one lands here. + if (await _walletWithdrawalRequestRepository.HasLiveReplacementAsync(original.Id)) + { + throw new BumpingException( + $"Withdrawal request {original.Id} is already being replaced by another request.", + BumpingErrorReason.InvalidState); + } + _logger.LogError("Error creating the replacement of withdrawal request {RequestId}: {Error}", original.Id, addError); throw new BumpingException(addError ?? "Could not create the replacement request", BumpingErrorReason.PersistenceError); @@ -335,11 +343,6 @@ public async Task ScheduleHotWalletWithdrawalAsync(int requestId) { var templatePsbt = await _bitcoinService.GenerateTemplatePSBT(request); - if (request.BumpingWalletWithdrawalRequestId != null) - { - await MarkOriginalAsReplacedAsync(request); - } - var scheduler = await _schedulerFactory.GetScheduler(); var map = new JobDataMap(); map.Put("withdrawalRequestId", request.Id); @@ -351,121 +354,103 @@ public async Task ScheduleHotWalletWithdrawalAsync(int requestId) catch (Exception e) { _logger.LogError(e, "Error executing withdrawal request {RequestId}", request.Id); - await RevertOriginalAsync(request); throw; } } - public async Task MarkOriginalAsReplacedAsync(WalletWithdrawalRequest replacement) + public async Task ReconcileReplacementChainsAsync() { - if (replacement.BumpingWalletWithdrawalRequestId is not { } originalId) return; - - var original = await _walletWithdrawalRequestRepository.GetById(originalId) - ?? throw new BumpingException("Could not find the replaced withdrawal request", - BumpingErrorReason.RequestNotFound); - - var targetStatus = replacement.IsRbfCancellation - ? WalletWithdrawalRequestStatus.Cancelled - : WalletWithdrawalRequestStatus.Bumped; - if (original.Status == targetStatus) return; - - if (original.Status != WalletWithdrawalRequestStatus.OnChainConfirmationPending) - { - // E.g. the original was mined and settled while a cold-wallet replacement was collecting signatures. - _logger.LogWarning("Not marking withdrawal request {RequestId} as {TargetStatus}: it is {Status}", - originalId, targetStatus, original.Status); - return; - } - - original.Status = targetStatus; - if (replacement.IsRbfCancellation) - { - original.RejectCancelDescription = CancellationReason(replacement.Id); - } + var liveRequests = await _walletWithdrawalRequestRepository.GetLiveRbfLinkedRequestsAsync(); + var chains = new Dictionary>(); - var (updated, error) = _walletWithdrawalRequestRepository.Update(original); - if (!updated) + foreach (var liveRequest in liveRequests) { - throw new BumpingException($"Could not mark withdrawal request {originalId} as {targetStatus}: {error}", - BumpingErrorReason.PersistenceError); - } - } - - public async Task RevertOriginalAsync(WalletWithdrawalRequest replacement) - { - if (replacement.BumpingWalletWithdrawalRequestId is not { } originalId) return; + try + { + if (!chains.TryGetValue(liveRequest.Id, out var chain)) + { + chain = await _walletWithdrawalRequestRepository.GetRbfChainAsync(liveRequest.Id); + foreach (var member in chain) chains[member.Id] = chain; + } - var original = await _walletWithdrawalRequestRepository.GetById(originalId); - if (original == null) return; + // The chain is the fresher read; a row that moved on in between is left to the next run. + var request = chain.FirstOrDefault(member => member.Id == liveRequest.Id); + if (request == null || !request.IsLive || request.Status == WalletWithdrawalRequestStatus.FinalizingPSBT) continue; - var markedByThisReplacement = original.Status == WalletWithdrawalRequestStatus.Bumped - || (replacement.IsRbfCancellation - && original.Status == WalletWithdrawalRequestStatus.Cancelled - && original.RejectCancelDescription == CancellationReason(replacement.Id)); - if (!markedByThisReplacement) return; + if (FinalStatusFromChain(request, chain) is not var (status, reason)) continue; - original.Status = WalletWithdrawalRequestStatus.OnChainConfirmationPending; - original.RejectCancelDescription = null; - var (updated, error) = _walletWithdrawalRequestRepository.Update(original); - if (!updated) - { - _logger.LogError("Could not put withdrawal request {RequestId} back to OnChainConfirmationPending: {Error}", - originalId, error); + request.Status = status; + request.RejectCancelDescription = reason; + var (updated, error) = _walletWithdrawalRequestRepository.Update(request); + if (updated) + { + _logger.LogInformation("Withdrawal request {RequestId} is {Status}: {Reason}", request.Id, status, reason); + } + else + { + _logger.LogError("Could not mark withdrawal request {RequestId} as {Status}: {Error}", request.Id, status, error); + } + } + catch (Exception e) + { + _logger.LogError(e, "Error reconciling withdrawal request {RequestId} against its RBF chain", liveRequest.Id); + } } } - public async Task SettleMinedOriginalAsync(WalletWithdrawalRequest replacement) + /// + /// What a live request becomes once its chain holds a confirmed transaction, or null while it does not. A + /// confirmed ancestor wins over a confirmed descendant: the payment happened, so the request is spent anyway. + /// + private static (WalletWithdrawalRequestStatus Status, string Reason)? FinalStatusFromChain( + WalletWithdrawalRequest request, List chain) { - // An unset TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS is 0, and an unconfirmed original was never mined. - var minimumConfirmations = Math.Max(1, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS); - var visited = new HashSet { replacement.Id }; - var originalId = replacement.BumpingWalletWithdrawalRequestId; + var byId = chain.ToDictionary(member => member.Id); - while (originalId is { } id && visited.Add(id)) + var visited = new HashSet { request.Id }; + var ancestorId = request.BumpingWalletWithdrawalRequestId; + while (ancestorId is { } id && visited.Add(id) && byId.TryGetValue(id, out var ancestor)) { - var original = await _walletWithdrawalRequestRepository.GetById(id); - if (original == null) return false; - - if (!string.IsNullOrEmpty(original.TxId)) + if (ancestor.Status == WalletWithdrawalRequestStatus.OnChainConfirmed) { - var originalTx = await _nbXplorerService.GetTransactionAsync(uint256.Parse(original.TxId)); - if (originalTx != null && originalTx.Confirmations >= minimumConfirmations) - { - return SettleOriginalAndFailReplacement(original, replacement); - } + return (WalletWithdrawalRequestStatus.Failed, + $"Withdrawal request {ancestor.Id} was mined instead (tx {ancestor.TxId})"); } - originalId = original.BumpingWalletWithdrawalRequestId; + ancestorId = ancestor.BumpingWalletWithdrawalRequestId; + } + + foreach (var confirmed in chain.Where(member => member.Status == WalletWithdrawalRequestStatus.OnChainConfirmed)) + { + var path = PathUpTo(confirmed, request.Id, byId); + if (path == null) continue; + + // Cancelled iff a cancellation sits on the way: a bump of a cancellation still returns the funds, while a + // cancellation of a bump still means this request's destinations were never paid. + return path.Any(member => member.IsRbfCancellation) + ? (WalletWithdrawalRequestStatus.Cancelled, WalletWithdrawalRequest.RbfCancellationReason(confirmed.Id, confirmed.TxId)) + : (WalletWithdrawalRequestStatus.Bumped, WalletWithdrawalRequest.ReplacedReason(confirmed.Id, confirmed.TxId)); } - return false; + return null; } - private bool SettleOriginalAndFailReplacement(WalletWithdrawalRequest original, WalletWithdrawalRequest replacement) + /// The requests from up to, excluding, ; null if it is not an ancestor. + private static List? PathUpTo(WalletWithdrawalRequest from, int targetId, + Dictionary byId) { - original.Status = WalletWithdrawalRequestStatus.OnChainConfirmed; - original.RejectCancelDescription = null; - var (originalUpdated, originalUpdateError) = _walletWithdrawalRequestRepository.Update(original); - if (!originalUpdated) + var path = new List(); + var visited = new HashSet(); + var current = from; + while (current != null && visited.Add(current.Id)) { - // The replacement stays pending so the next monitoring run retries both. - _logger.LogError("Could not settle withdrawal request {RequestId}, mined instead of its replacement {ReplacementId}: {Error}", - original.Id, replacement.Id, originalUpdateError); - return false; - } + path.Add(current); + if (current.BumpingWalletWithdrawalRequestId == targetId) return path; - replacement.Status = WalletWithdrawalRequestStatus.Failed; - replacement.RejectCancelDescription = $"Withdrawal request {original.Id} was mined instead (tx {original.TxId})"; - var (replacementUpdated, replacementUpdateError) = _walletWithdrawalRequestRepository.Update(replacement); - if (!replacementUpdated) - { - _logger.LogError("Could not mark replacement withdrawal request {RequestId} as failed: {Error}", - replacement.Id, replacementUpdateError); + current = current.BumpingWalletWithdrawalRequestId is { } id ? byId.GetValueOrDefault(id) : null; } - _logger.LogInformation("Withdrawal request {RequestId} was mined instead of its replacement {ReplacementId}", - original.Id, replacement.Id); - return true; + return null; } private async Task ResolveFeeRateAsync(MempoolRecommendedFeesType feeType, decimal? customFeeRate) @@ -491,8 +476,6 @@ private async Task ResolveFeeRateAsync(MempoolRecommendedFeesType feeTy return recommended.Value; } - private static string CancellationReason(int replacementId) => $"Cancelled by RBF replacement request {replacementId}"; - /// /// Replacements of replacements keep a single "Bump of request N:" / "Cancel of request N:" prefix, pointing at the /// request being replaced. diff --git a/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestRepositoryTests.cs b/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestRepositoryTests.cs index cf296ef24..9c128f01b 100644 --- a/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestRepositoryTests.cs +++ b/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestRepositoryTests.cs @@ -28,9 +28,10 @@ namespace NodeGuard.Data.Repositories; /// -/// GetByReferenceIds answers "what happened to this external withdrawal". RBF replacements inherit the reference id of -/// the request they replace, so it has to pick the request of the chain that tells the truth: the latest one, unless a -/// request it replaced was mined instead. +/// RBF replacements point at the request they replace through BumpingWalletWithdrawalRequestId, and a request's status +/// only describes its own transaction. These reads answer the questions built on that link: every request a reference +/// id maps to (the whole chain, each reporting its own status), whether a request already has a live replacement, and +/// which rows the monitor's reconciliation has to look at. /// public class WalletWithdrawalRequestRepositoryTests { @@ -59,9 +60,9 @@ private static WalletWithdrawalRequestRepository CreateRepository(Mock().Object); - private static async Task SeedAsync( - Mock> factory, params WalletWithdrawalRequest[] requests) + private async Task SeedAsync(params WalletWithdrawalRequest[] requests) { + var factory = SetupDbContextFactory(); await using var context = await factory.Object.CreateDbContextAsync(); await context.WalletWithdrawalRequests.AddRangeAsync(requests); await context.SaveChangesAsync(); @@ -78,79 +79,145 @@ private static WalletWithdrawalRequest Request(int id, WalletWithdrawalRequestSt BumpingWalletWithdrawalRequestId = replaces, }; + // ---- GetByReferenceIds --------------------------------------------------------------------------------------- + [Fact] - public async Task GetByReferenceIds_ReplacementInFlight_ReturnsTheLatestRequest() + public async Task GetByReferenceIds_ReturnsEveryRequestOfTheChainOldestFirst() { - var repository = await SeedAsync(SetupDbContextFactory(), - Request(1, WalletWithdrawalRequestStatus.Bumped), - Request(2, WalletWithdrawalRequestStatus.OnChainConfirmationPending, replaces: 1)); + var repository = await SeedAsync( + Request(3, WalletWithdrawalRequestStatus.Failed, replaces: 2), + Request(1, WalletWithdrawalRequestStatus.OnChainConfirmed), + Request(2, WalletWithdrawalRequestStatus.Failed, replaces: 1), + Request(4, WalletWithdrawalRequestStatus.OnChainConfirmationPending, reference: "other")); var result = await repository.GetByReferenceIds(new List { Reference }); - result.Should().ContainSingle().Which.Id.Should().Be(2); + result.Select(r => r.Id).Should().Equal(new[] { 1, 2, 3 }, + "the original and each of its replacements carry the reference id; the caller sees what happened to each"); } [Fact] - public async Task GetByReferenceIds_ReplacementConfirmed_ReturnsTheReplacement() + public async Task GetByReferenceIds_SeveralReferences_ReturnsAllOfEach() { - var repository = await SeedAsync(SetupDbContextFactory(), - Request(1, WalletWithdrawalRequestStatus.Bumped), - Request(2, WalletWithdrawalRequestStatus.OnChainConfirmed, replaces: 1)); + var repository = await SeedAsync( + Request(1, WalletWithdrawalRequestStatus.OnChainConfirmed, reference: "a"), + Request(2, WalletWithdrawalRequestStatus.Failed, replaces: 1, reference: "a"), + Request(3, WalletWithdrawalRequestStatus.OnChainConfirmationPending, reference: "b"), + Request(4, WalletWithdrawalRequestStatus.Pending, reference: "c")); - var result = await repository.GetByReferenceIds(new List { Reference }); + var result = await repository.GetByReferenceIds(new List { "a", "b" }); - result.Should().ContainSingle().Which.Id.Should().Be(2); + result.Select(r => r.Id).Should().Equal(new[] { 1, 2, 3 }); } [Fact] - public async Task GetByReferenceIds_OriginalMinedInstead_ReturnsTheSettledOriginal() + public async Task GetByReferenceIds_UnknownReference_ReturnsNothing() { - var repository = await SeedAsync(SetupDbContextFactory(), - Request(1, WalletWithdrawalRequestStatus.OnChainConfirmed), - Request(2, WalletWithdrawalRequestStatus.Failed, replaces: 1)); + var repository = await SeedAsync(Request(1, WalletWithdrawalRequestStatus.OnChainConfirmed)); - var result = await repository.GetByReferenceIds(new List { Reference }); + var result = await repository.GetByReferenceIds(new List { "missing" }); - result.Should().ContainSingle().Which.Id.Should().Be(1, - "the failed replacement lost the race: reporting it would tell the caller a paid withdrawal failed"); + result.Should().BeEmpty(); } [Fact] - public async Task GetByReferenceIds_BumpOfABumpWithTheFirstMined_ReturnsTheFirstRequest() + public async Task GetByReferenceIds_LoadsTheReplacements() { - var repository = await SeedAsync(SetupDbContextFactory(), - Request(1, WalletWithdrawalRequestStatus.OnChainConfirmed), - Request(2, WalletWithdrawalRequestStatus.Bumped, replaces: 1), - Request(3, WalletWithdrawalRequestStatus.Failed, replaces: 2)); + var repository = await SeedAsync( + Request(1, WalletWithdrawalRequestStatus.OnChainConfirmationPending), + Request(2, WalletWithdrawalRequestStatus.OnChainConfirmationPending, replaces: 1)); var result = await repository.GetByReferenceIds(new List { Reference }); - result.Should().ContainSingle().Which.Id.Should().Be(1); + result.First().Replacements.Select(r => r.Id).Should().Equal(new[] { 2 }, + "the API derives the reported status of a replaced request from them"); } + // ---- replacement lookups -------------------------------------------------------------------------------------- + [Fact] - public async Task GetByReferenceIds_ReusedReferenceId_DoesNotReportAnUnrelatedEarlierWithdrawal() + public async Task GetByIds_LoadsTheReplacements() { - var repository = await SeedAsync(SetupDbContextFactory(), - Request(1, WalletWithdrawalRequestStatus.OnChainConfirmed), - Request(2, WalletWithdrawalRequestStatus.Failed)); + var repository = await SeedAsync( + Request(1, WalletWithdrawalRequestStatus.OnChainConfirmationPending), + Request(2, WalletWithdrawalRequestStatus.OnChainConfirmationPending, replaces: 1)); - var result = await repository.GetByReferenceIds(new List { Reference }); + var result = await repository.GetByIds(new List { 1 }); + + result.Single().Replacements.Select(r => r.Id).Should().Equal(new[] { 2 }); + } + + [Theory] + [InlineData(WalletWithdrawalRequestStatus.Pending, true)] + [InlineData(WalletWithdrawalRequestStatus.PSBTSignaturesPending, true)] + [InlineData(WalletWithdrawalRequestStatus.FinalizingPSBT, true)] + [InlineData(WalletWithdrawalRequestStatus.OnChainConfirmationPending, true)] + [InlineData(WalletWithdrawalRequestStatus.OnChainConfirmed, false)] + [InlineData(WalletWithdrawalRequestStatus.Failed, false)] + [InlineData(WalletWithdrawalRequestStatus.Cancelled, false)] + [InlineData(WalletWithdrawalRequestStatus.Rejected, false)] + [InlineData(WalletWithdrawalRequestStatus.Bumped, false)] + public async Task HasLiveReplacementAsync_CountsOnlyLiveStatuses(WalletWithdrawalRequestStatus replacementStatus, bool expected) + { + var repository = await SeedAsync( + Request(1, WalletWithdrawalRequestStatus.OnChainConfirmationPending), + Request(2, replacementStatus, replaces: 1)); - result.Should().ContainSingle().Which.Id.Should().Be(2, - "reference ids are not unique: only requests the latest one replaced can stand in for it"); + (await repository.HasLiveReplacementAsync(1)).Should().Be(expected); } [Fact] - public async Task GetByReferenceIds_SeveralReferences_ResolvesEachOnItsOwn() + public async Task HasLiveReplacementAsync_UnrelatedLiveRequest_DoesNotCount() { - var repository = await SeedAsync(SetupDbContextFactory(), - Request(1, WalletWithdrawalRequestStatus.OnChainConfirmed, reference: "a"), - Request(2, WalletWithdrawalRequestStatus.Failed, replaces: 1, reference: "a"), - Request(3, WalletWithdrawalRequestStatus.OnChainConfirmationPending, reference: "b")); + var repository = await SeedAsync( + Request(1, WalletWithdrawalRequestStatus.OnChainConfirmationPending), + Request(2, WalletWithdrawalRequestStatus.OnChainConfirmationPending)); - var result = await repository.GetByReferenceIds(new List { "a", "b" }); + (await repository.HasLiveReplacementAsync(1)).Should().BeFalse(); + } + + [Fact] + public async Task GetRbfChainAsync_ReturnsTheWholeChainFromAnyMember() + { + var repository = await SeedAsync( + Request(1, WalletWithdrawalRequestStatus.OnChainConfirmationPending), + Request(2, WalletWithdrawalRequestStatus.OnChainConfirmationPending, replaces: 1), + Request(3, WalletWithdrawalRequestStatus.OnChainConfirmationPending, replaces: 2), + Request(4, WalletWithdrawalRequestStatus.Failed, replaces: 1), + Request(5, WalletWithdrawalRequestStatus.OnChainConfirmationPending)); + + var chain = await repository.GetRbfChainAsync(2); + + chain.Select(r => r.Id).Should().Equal(new[] { 1, 2, 3, 4 }, + "walking up finds what 2 replaced, walking down finds every replacement, including the abandoned sibling"); + } + + [Fact] + public async Task GetRbfChainAsync_UnlinkedRequest_ReturnsItself() + { + var repository = await SeedAsync( + Request(1, WalletWithdrawalRequestStatus.OnChainConfirmationPending), + Request(2, WalletWithdrawalRequestStatus.OnChainConfirmationPending)); + + var chain = await repository.GetRbfChainAsync(1); - result.Select(r => r.Id).Should().BeEquivalentTo(new[] { 1, 3 }); + chain.Select(r => r.Id).Should().Equal(new[] { 1 }); + } + + [Fact] + public async Task GetLiveRbfLinkedRequestsAsync_ReturnsLiveRowsWithALinkOrReplacements_NotFinalizing() + { + var repository = await SeedAsync( + Request(1, WalletWithdrawalRequestStatus.OnChainConfirmationPending), + Request(2, WalletWithdrawalRequestStatus.FinalizingPSBT, replaces: 1), + Request(3, WalletWithdrawalRequestStatus.Pending), + Request(4, WalletWithdrawalRequestStatus.Failed, replaces: 1), + Request(5, WalletWithdrawalRequestStatus.OnChainConfirmed), + Request(6, WalletWithdrawalRequestStatus.PSBTSignaturesPending, replaces: 5)); + + var rows = await repository.GetLiveRbfLinkedRequestsAsync(); + + rows.Select(r => r.Id).Should().BeEquivalentTo(new[] { 1, 6 }, + "1 is replaced, 6 replaces; 2 is being broadcast, 3 is unlinked, 4 and 5 are not live"); } } diff --git a/test/NodeGuard.Tests/E2E/WithdrawalRbfBumpE2ETests.cs b/test/NodeGuard.Tests/E2E/WithdrawalRbfBumpE2ETests.cs index 3f775c827..7ba32b58b 100644 --- a/test/NodeGuard.Tests/E2E/WithdrawalRbfBumpE2ETests.cs +++ b/test/NodeGuard.Tests/E2E/WithdrawalRbfBumpE2ETests.cs @@ -29,12 +29,13 @@ namespace NodeGuard.Tests.E2E; /// /// End-to-end coverage for the RBF replacements of a hot-wallet withdrawal against a LIVE NodeGuard + bitcoind, driven /// over gRPC. Fee bump: RequestWithdrawal broadcasts an RBF-signalling transaction, BumpWithdrawal replaces it with a -/// higher-fee version of the same payment, bitcoind evicts the original, NodeGuard marks it WITHDRAWAL_BUMPED and, once -/// mined, settles the replacement. Cancellation: CancelWithdrawal replaces it with a transaction that returns the funds to -/// the wallet, the destination is never paid and the original ends up WITHDRAWAL_CANCELLED. Mined original: either -/// replacement loses the race to the original, which NodeGuard must then settle while failing the replacement, also when -/// the original was bumped twice. The UI and the RPCs share WithdrawalRequestService, so these scenarios exercise the -/// same orchestration the Withdrawals page runs. +/// higher-fee version of the same payment, bitcoind evicts the original, NodeGuard reports it WITHDRAWAL_BUMPED while +/// the replacement is in the mempool and stores that once the replacement is mined and settled. Cancellation: +/// CancelWithdrawal replaces it with a transaction that returns the funds to the wallet, the destination is never paid +/// and the original ends up WITHDRAWAL_CANCELLED. Mined original: either replacement loses the race to the original, +/// which NodeGuard must then settle while failing every replacement, also when the original was bumped twice. The UI +/// and the RPCs share WithdrawalRequestService, so these scenarios exercise the same orchestration the Withdrawals +/// page runs. /// /// Shared plumbing in ; gated by . Env: see /// . Never mine between the withdrawal and its replacement — the original must @@ -114,6 +115,7 @@ await PollAsync(() => GetStatusesAsync(client, headers, withdrawal.RequestId), && s[withdrawal.RequestId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalBumped, attempts: 30, delay: TimeSpan.FromSeconds(2), what: "bump pending confirmation, original bumped"); statuses[bump.RequestId].TxId.Should().Be(bump.Txid); + statuses[withdrawal.RequestId].ReplacedByRequestId.Should().Be(bump.RequestId, "clients follow the chain by id"); // 4. Guards: a bumped request cannot be bumped again, a bump must raise the fee rate, and an unknown txid is not found. var bumpAgain = () => client.BumpWithdrawalAsync(new BumpWithdrawalRequest @@ -123,7 +125,7 @@ await PollAsync(() => GetStatusesAsync(client, headers, withdrawal.RequestId), CustomFeeRate = BumpedFeeRateSatPerVb + 5, }, headers).ResponseAsync; (await bumpAgain.Should().ThrowAsync()).Which.StatusCode.Should().Be(StatusCode.FailedPrecondition, - "the original is WITHDRAWAL_BUMPED, not pending confirmation"); + "the original already has a live replacement"); var bumpLower = () => client.BumpWithdrawalAsync(new BumpWithdrawalRequest { @@ -155,7 +157,8 @@ await PollAsync(() => GetStatusesAsync(client, headers, withdrawal.RequestId), s => s[bump.RequestId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalSettled, attempts: 40, delay: TimeSpan.FromSeconds(5), what: "bump settled by MonitorWithdrawalsJob"); settled[withdrawal.RequestId].Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalBumped, - "the replaced request stays bumped"); + "once the replacement settled, Bumped is the replaced request's stored, terminal status"); + settled[withdrawal.RequestId].RejectOrCancelReason.Should().Contain(bump.RequestId.ToString()); } [E2EFact] @@ -308,15 +311,15 @@ await PollAsync(() => GetStatusesAsync(client, headers, withdrawal.RequestId, re "the cancellation never took effect: the destination was paid"); } - await AssertReferenceResolvesToSettledAsync(client, headers, referenceId, withdrawal.RequestId); + await AssertReferenceReturnsTheChainAsync(client, headers, referenceId, withdrawal.RequestId, withdrawal.RequestId, replacementId); } /// /// The same race one bump deeper: A is bumped to B, B is bumped to C, and A is mined. NodeGuard must settle A and fail - /// C; B was replaced and never confirmed, so it stays bumped. + /// both B and C: each double-spends the confirmed transaction and can never confirm. /// [E2EFact] - public async Task BumpOfABump_WhenTheFirstTransactionIsMined_SettlesItAndFailsTheLastReplacement() + public async Task BumpOfABump_WhenTheFirstTransactionIsMined_SettlesItAndFailsBothReplacements() { var client = CreateClient(out var headers); var rpc = CreateBitcoindRpc(); @@ -367,23 +370,25 @@ await PollAsync(() => GetStatusesAsync(client, headers, first.RequestId, secondI (await rpc.GetRawTransactionAsync(secondTxId, throwIfNotFound: false)).Should().BeNull("B can never confirm"); (await rpc.GetRawTransactionAsync(thirdTxId, throwIfNotFound: false)).Should().BeNull("C can never confirm"); - // 5. NodeGuard's view must follow the chain: A settled, C failed, B still bumped. + // 5. NodeGuard's view must follow the chain: A settled, B and C failed. var settled = await PollAsync(() => GetStatusesAsync(client, headers, first.RequestId, secondId, thirdId), s => { _output.WriteLine($"A {s[first.RequestId].Status}, B {s[secondId].Status}, C {s[thirdId].Status}"); return s[first.RequestId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalSettled + && s[secondId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalFailed && s[thirdId].Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalFailed; }, - attempts: 40, delay: TimeSpan.FromSeconds(5), what: "first settled, second bump failed"); + attempts: 40, delay: TimeSpan.FromSeconds(5), what: "first settled, both bumps failed"); settled[first.RequestId].TxId.Should().Be(first.Txid, "A's own transaction is the one that confirmed"); settled[first.RequestId].Confirmations.Should().BeGreaterThan(0UL); - settled[secondId].Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalBumped, "B was replaced by C and never confirmed"); + settled[secondId].RejectOrCancelReason.Should().Contain(first.RequestId.ToString(), + "B double-spends the confirmed transaction; the failure names the request that was mined instead"); settled[thirdId].RejectOrCancelReason.Should().Contain(first.RequestId.ToString(), "the failure names the request that was mined instead"); - await AssertReferenceResolvesToSettledAsync(client, headers, referenceId, first.RequestId); + await AssertReferenceReturnsTheChainAsync(client, headers, referenceId, first.RequestId, first.RequestId, secondId, thirdId); } // ---- plumbing ------------------------------------------------------------------------------------------------ @@ -487,18 +492,23 @@ await RetryAsync(async () => } /// - /// What a caller tracking the withdrawal by reference id sees. Replacements share the reference id, and the - /// request that settled must win over the newer replacement that failed, or a paid withdrawal reads as failed. + /// What a caller tracking the withdrawal by reference id sees: every request of the chain, oldest first, each with + /// its own status. The one whose transaction confirmed reads as settled, and every replacement of it reads as + /// failed, so a paid withdrawal never reads as failed and the caller can tell which transaction paid it. /// - private static async Task AssertReferenceResolvesToSettledAsync(NodeGuardService.NodeGuardServiceClient client, - Metadata headers, string referenceId, int settledRequestId) + private static async Task AssertReferenceReturnsTheChainAsync(NodeGuardService.NodeGuardServiceClient client, + Metadata headers, string referenceId, int settledRequestId, params int[] chainRequestIds) { var response = await client.GetWithdrawalsRequestStatusByReferenceIdsAsync( new GetWithdrawalsRequestStatusByReferenceIdsRequest { ReferenceIds = { referenceId } }, headers); - var tracked = response.WithdrawalRequests.Should().ContainSingle().Subject; - tracked.RequestId.Should().Be(settledRequestId, "the request whose transaction confirmed is the payment that happened"); - tracked.Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalSettled); + response.WithdrawalRequests.Select(r => r.RequestId).Should().Equal(chainRequestIds, + "every request carrying the reference id is returned, oldest first"); + response.WithdrawalRequests.Single(r => r.RequestId == settledRequestId).Status + .Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalSettled, "the request whose transaction confirmed is the payment that happened"); + response.WithdrawalRequests.Where(r => r.RequestId != settledRequestId) + .Should().OnlyContain(r => r.Status == WITHDRAWAL_REQUEST_STATUS.WithdrawalFailed, + "every replacement double-spends the confirmed transaction"); } private static async Task> GetStatusesAsync( diff --git a/test/NodeGuard.Tests/Jobs/MonitorWithdrawalsJobTests.cs b/test/NodeGuard.Tests/Jobs/MonitorWithdrawalsJobTests.cs index ab2e56e7d..da44c062b 100644 --- a/test/NodeGuard.Tests/Jobs/MonitorWithdrawalsJobTests.cs +++ b/test/NodeGuard.Tests/Jobs/MonitorWithdrawalsJobTests.cs @@ -30,19 +30,26 @@ namespace NodeGuard.Jobs; /// -/// MonitorWithdrawalsJob settles withdrawals whose transaction reached the settlement depth, and asks -/// WithdrawalRequestService whether an RBF replacement lost the race to a transaction it replaced. That question only -/// makes sense while the replacement itself is unconfirmed: once it is mined, nothing it replaced can be. +/// MonitorWithdrawalsJob settles withdrawals whose transaction reached the settlement depth, one row at a time so a +/// bad row never stops the batch, and then hands over to WithdrawalRequestService.ReconcileReplacementChainsAsync, +/// which gives RBF-linked requests their final status from the database. The order matters: a request settled in this +/// run must drive its chain in this run. /// public class MonitorWithdrawalsJobTests { private readonly Mock _requests = new(); private readonly Mock _nbXplorer = new(); private readonly Mock _withdrawalRequestService = new(); + private readonly List _events = new(); public MonitorWithdrawalsJobTests() { - _requests.Setup(x => x.Update(It.IsAny())).Returns((true, (string?)null)); + _requests.Setup(x => x.Update(It.IsAny())) + .Callback(r => _events.Add($"settle:{r.Id}")) + .Returns((true, (string?)null)); + _withdrawalRequestService.Setup(x => x.ReconcileReplacementChainsAsync()) + .Callback(() => _events.Add("reconcile")) + .Returns(Task.CompletedTask); } private Task ExecuteAsync(params WalletWithdrawalRequest[] pending) @@ -57,19 +64,20 @@ private Task ExecuteAsync(params WalletWithdrawalRequest[] pending) /// A broadcast request waiting for confirmation whose transaction has . private WalletWithdrawalRequest Pending(int id, int confirmations, int? replaces = null) { - var txId = new uint256((ulong)id); - _nbXplorer.Setup(x => x.GetTransactionAsync(txId, It.IsAny())) + var request = PendingWithoutTransaction(id, replaces); + _nbXplorer.Setup(x => x.GetTransactionAsync(uint256.Parse(request.TxId!), It.IsAny())) .ReturnsAsync(new TransactionResult { Confirmations = confirmations }); - - return new WalletWithdrawalRequest - { - Id = id, - Status = WalletWithdrawalRequestStatus.OnChainConfirmationPending, - TxId = txId.ToString(), - BumpingWalletWithdrawalRequestId = replaces, - }; + return request; } + private static WalletWithdrawalRequest PendingWithoutTransaction(int id, int? replaces = null) => new() + { + Id = id, + Status = WalletWithdrawalRequestStatus.OnChainConfirmationPending, + TxId = new uint256((ulong)id).ToString(), + BumpingWalletWithdrawalRequestId = replaces, + }; + [Fact] public async Task Execute_WithdrawalAtTheSettlementDepth_IsSettled() { @@ -79,69 +87,104 @@ public async Task Execute_WithdrawalAtTheSettlementDepth_IsSettled() request.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed); _requests.Verify(x => x.Update(request), Times.Once); - _withdrawalRequestService.Verify(x => x.SettleMinedOriginalAsync(It.IsAny()), Times.Never); } [Fact] - public async Task Execute_ReplacementAtTheSettlementDepth_IsSettledWithoutLookingAtWhatItReplaced() + public async Task Execute_ReplacementAtTheSettlementDepth_IsSettled() { var replacement = Pending(2, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS, replaces: 1); await ExecuteAsync(replacement); - replacement.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed); - _withdrawalRequestService.Verify(x => x.SettleMinedOriginalAsync(It.IsAny()), Times.Never); + replacement.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed, + "what that means for the request it replaced is the reconciliation's job"); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + public async Task Execute_WithdrawalBelowTheSettlementDepth_IsLeftPending(int confirmations) + { + var request = Pending(1, confirmations, replaces: 1); + + await ExecuteAsync(request); + + request.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending); + _requests.Verify(x => x.Update(It.IsAny()), Times.Never); } [Fact] - public async Task Execute_UnconfirmedReplacement_ChecksWhetherWhatItReplacedWasMined() + public async Task Execute_TransactionUnknownToNbxplorer_LeavesTheRequestPendingAndContinues() { - var replacement = Pending(2, confirmations: 0, replaces: 1); + var unknown = PendingWithoutTransaction(1); + _nbXplorer.Setup(x => x.GetTransactionAsync(uint256.Parse(unknown.TxId!), It.IsAny())) + .ReturnsAsync((TransactionResult?)null); + var settling = Pending(2, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS); - await ExecuteAsync(replacement); + await ExecuteAsync(unknown, settling); - _withdrawalRequestService.Verify(x => x.SettleMinedOriginalAsync(replacement), Times.Once); - replacement.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending, - "settling the original and failing the replacement is the service's decision, not the job's"); + unknown.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending); + settling.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed); } [Fact] - public async Task Execute_ReplacementMinedButNotYetSettled_LeavesWhatItReplacedAlone() + public async Task Execute_NbxplorerFailureOnOneRequest_DoesNotAbortTheBatch() { - var replacement = Pending(2, confirmations: 1, replaces: 1); + var failing = PendingWithoutTransaction(1); + _nbXplorer.Setup(x => x.GetTransactionAsync(uint256.Parse(failing.TxId!), It.IsAny())) + .ThrowsAsync(new HttpRequestException("nbxplorer down")); + var settling = Pending(2, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS); - await ExecuteAsync(replacement); + var act = () => ExecuteAsync(failing, settling); - replacement.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending, "it is not deep enough yet"); - _withdrawalRequestService.Verify(x => x.SettleMinedOriginalAsync(It.IsAny()), Times.Never, - "the replacement is mined, so nothing it replaced can be"); - _requests.Verify(x => x.Update(It.IsAny()), Times.Never); + await act.Should().NotThrowAsync(); + settling.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed); + _events.Should().Contain("reconcile"); } [Fact] - public async Task Execute_UnconfirmedWithdrawalThatReplacesNothing_IsLeftPending() + public async Task Execute_RequestWithoutTransaction_IsSkipped() { - var request = Pending(1, confirmations: 0); + var request = PendingWithoutTransaction(1); + request.TxId = null; await ExecuteAsync(request); - request.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending); - _withdrawalRequestService.Verify(x => x.SettleMinedOriginalAsync(It.IsAny()), Times.Never); + _nbXplorer.Verify(x => x.GetTransactionAsync(It.IsAny(), It.IsAny()), Times.Never); _requests.Verify(x => x.Update(It.IsAny()), Times.Never); } [Fact] - public async Task Execute_MixedBatch_HandlesEachRequestOnItsOwn() + public async Task Execute_ReconcilesTheRbfChainsAfterSettling() { var settling = Pending(1, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS); - var lostRace = Pending(3, confirmations: 0, replaces: 2); - var inFlight = Pending(4, confirmations: 0); + var inFlight = Pending(2, confirmations: 0, replaces: 1); - await ExecuteAsync(settling, lostRace, inFlight); + await ExecuteAsync(settling, inFlight); - settling.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed); - _withdrawalRequestService.Verify(x => x.SettleMinedOriginalAsync(lostRace), Times.Once); - _withdrawalRequestService.Verify(x => x.SettleMinedOriginalAsync(It.IsAny()), Times.Once); - inFlight.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending); + _events.Should().Equal(new[] { "settle:1", "reconcile" }, + "a request settled in this run must drive its RBF chain in this run"); + inFlight.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending, + "failing it is the reconciliation's decision, not the job's"); + } + + [Fact] + public async Task Execute_NothingPending_StillReconciles() + { + await ExecuteAsync(); + + _withdrawalRequestService.Verify(x => x.ReconcileReplacementChainsAsync(), Times.Once, + "a cold replacement awaiting approval is not pending confirmation, yet its original may have confirmed"); + } + + [Fact] + public async Task Execute_ReconciliationThrowing_IsLoggedNotRethrown() + { + _withdrawalRequestService.Setup(x => x.ReconcileReplacementChainsAsync()) + .ThrowsAsync(new InvalidOperationException("db down")); + + var act = () => ExecuteAsync(); + + await act.Should().NotThrowAsync(); } } diff --git a/test/NodeGuard.Tests/Jobs/PerformWithdrawalJobTests.cs b/test/NodeGuard.Tests/Jobs/PerformWithdrawalJobTests.cs index 4a1ea098a..0f9103c78 100644 --- a/test/NodeGuard.Tests/Jobs/PerformWithdrawalJobTests.cs +++ b/test/NodeGuard.Tests/Jobs/PerformWithdrawalJobTests.cs @@ -27,10 +27,10 @@ namespace NodeGuard.Jobs; /// -/// When PerformWithdrawalJob cannot sign or broadcast, the request fails and, if it was an RBF replacement, the request -/// it replaced gets back its pending-confirmation status. That revert goes through WithdrawalRequestService, so it only -/// undoes what the replacement did: an original that settled meanwhile (the cold-wallet case, where approvals take -/// hours) is left settled, and a reverted cancellation loses its "Cancelled by RBF" reason. +/// When PerformWithdrawalJob cannot sign or broadcast, the request fails and nothing else happens: a request's status +/// only describes its own transaction, so the request an RBF replacement replaced never left pending confirmation and +/// needs no revert. Its inputs are still locked by it, and it is reported as pending again as soon as the replacement +/// is no longer live. /// public class PerformWithdrawalJobTests { @@ -49,12 +49,7 @@ public PerformWithdrawalJobTests() private Task ExecuteAsync(int requestId) { - // The real service: what happens to the replaced request is RevertOriginalAsync's behaviour. - var withdrawalRequestService = new WithdrawalRequestService(NullLogger.Instance, - _requests.Object, Mock.Of(), Mock.Of(), Mock.Of(), - _bitcoin.Object, Mock.Of()); - var job = new PerformWithdrawalJob(NullLogger.Instance, _bitcoin.Object, _requests.Object, - withdrawalRequestService); + var job = new PerformWithdrawalJob(NullLogger.Instance, _bitcoin.Object, _requests.Object); var context = new Mock(); context.Setup(x => x.JobDetail).Returns(JobBuilder.Create() @@ -78,31 +73,21 @@ private WalletWithdrawalRequest Stored(int id, WalletWithdrawalRequestStatus sta return request; } - [Fact] - public async Task Execute_FailedBump_RevertsTheBumpedOriginalAndFailsTheBump() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Execute_FailedReplacement_FailsOnlyTheReplacement(bool cancellation) { - var original = Stored(OriginalId, WalletWithdrawalRequestStatus.Bumped); - var bump = Stored(ReplacementId, WalletWithdrawalRequestStatus.FinalizingPSBT, replaces: OriginalId); + var original = Stored(OriginalId, WalletWithdrawalRequestStatus.OnChainConfirmationPending); + var replacement = Stored(ReplacementId, WalletWithdrawalRequestStatus.FinalizingPSBT, replaces: OriginalId, cancellation); await ExecuteAsync(ReplacementId); - bump.Status.Should().Be(WalletWithdrawalRequestStatus.Failed); + replacement.Status.Should().Be(WalletWithdrawalRequestStatus.Failed); original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending, - "the bump never went out, so the original transaction is still the one waiting to confirm"); - } - - [Fact] - public async Task Execute_FailedCancellation_RestoresTheOriginalAndClearsTheCancellationReason() - { - var original = Stored(OriginalId, WalletWithdrawalRequestStatus.Cancelled); - original.RejectCancelDescription = $"Cancelled by RBF replacement request {ReplacementId}"; - var cancel = Stored(ReplacementId, WalletWithdrawalRequestStatus.FinalizingPSBT, replaces: OriginalId, cancellation: true); - - await ExecuteAsync(ReplacementId); - - cancel.Status.Should().Be(WalletWithdrawalRequestStatus.Failed); - original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending); - original.RejectCancelDescription.Should().BeNull("the cancellation never went out"); + "the replacement never went out, so the original transaction is still the one waiting to confirm"); + _requests.Verify(x => x.Update(original), Times.Never, "a replacement never writes the request it replaces"); + _requests.Verify(x => x.Update(It.IsAny()), Times.Once); } [Fact] @@ -143,12 +128,13 @@ public async Task Execute_RequestGoneByTheTimeItFails_DoesNotThrow() public async Task Execute_SuccessfulBroadcast_LeavesTheReplacedRequestAsItWas() { _bitcoin.Setup(x => x.PerformWithdrawal(It.IsAny())).Returns(Task.CompletedTask); - var original = Stored(OriginalId, WalletWithdrawalRequestStatus.Bumped); + var original = Stored(OriginalId, WalletWithdrawalRequestStatus.OnChainConfirmationPending); Stored(ReplacementId, WalletWithdrawalRequestStatus.FinalizingPSBT, replaces: OriginalId); await ExecuteAsync(ReplacementId); - original.Status.Should().Be(WalletWithdrawalRequestStatus.Bumped); + original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending, + "whether it ends up Bumped or settled is for the monitor to decide once a transaction confirms"); _requests.Verify(x => x.Update(It.IsAny()), Times.Never); } } diff --git a/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs b/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs index 26421b2af..29e2e73ee 100644 --- a/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs +++ b/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs @@ -992,6 +992,161 @@ public async Task BumpWithdrawal_RefusedByTheService_MapsTheReasonToAStatusCode( exception.Status.Detail.Should().Be("refused", "the user-facing reason travels to the API caller"); } + // ---- GetWithdrawalsRequestStatus: a replaced request keeps its own status; the API derives what it reports ---- + + private const string OriginalTxId = "5f59c45bc3fa8362d5c38bce5c633bb901a57f268ec75e55548c00d2baec0d65"; + private const string ReplacementTxId = "3a9907ab1b965e1ad0024e7fe4466ddab0d3b1bf3bd15ab6416bf8f0c9032f84"; + + private static WalletWithdrawalRequest ReplacedRequest(WalletWithdrawalRequestStatus replacementStatus, bool cancellation = false) + { + var original = new WalletWithdrawalRequest + { + Id = 10, + Status = WalletWithdrawalRequestStatus.OnChainConfirmationPending, + TxId = OriginalTxId, + ReferenceId = "store-1", + Description = "pay rent", + }; + original.Replacements.Add(new WalletWithdrawalRequest + { + Id = 11, + Status = replacementStatus, + TxId = ReplacementTxId, + ReferenceId = "store-1", + Description = "bump", + BumpingWalletWithdrawalRequestId = 10, + IsRbfCancellation = cancellation, + }); + return original; + } + + private NodeGuardService StatusService(Mock walletWithdrawalRequestRepository, int confirmations) + { + var nbxplorerService = new Mock(); + nbxplorerService.Setup(x => x.GetTransactionAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(new NBXplorer.Models.TransactionResult { Confirmations = confirmations }); + + return CreateNodeGuardService( + walletWithdrawalRequestRepository: walletWithdrawalRequestRepository.Object, + nbXplorerService: nbxplorerService.Object); + } + + private async Task GetStatusAsync(WalletWithdrawalRequest request, int confirmations = 0) + { + var walletWithdrawalRequestRepository = new Mock(); + walletWithdrawalRequestRepository.Setup(x => x.GetByIds(It.IsAny>())) + .ReturnsAsync(new List { request }); + + var response = await StatusService(walletWithdrawalRequestRepository, confirmations).GetWithdrawalsRequestStatus( + new GetWithdrawalsRequestStatusRequest { RequestIds = { request.Id } }, TestServerCallContext.Create()); + return response.WithdrawalRequests.Single(); + } + + [Fact] + public async Task GetWithdrawalsRequestStatus_OriginalWithABroadcastReplacement_ReportsBumpedAndTheReplacementId() + { + var status = await GetStatusAsync(ReplacedRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending)); + + status.Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalBumped, + "the replacement's transaction competes with its own in the mempool"); + status.ReplacedByRequestId.Should().Be(11); + status.RejectOrCancelReason.Should().BeEmpty(); + } + + [Fact] + public async Task GetWithdrawalsRequestStatus_OriginalWithABroadcastCancellation_ReportsCancelledWithTheReason() + { + var status = await GetStatusAsync(ReplacedRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending, cancellation: true)); + + status.Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalCancelled); + status.RejectOrCancelReason.Should().Be($"Cancelled by RBF replacement request 11 (tx {ReplacementTxId})"); + status.ReplacedByRequestId.Should().Be(11); + } + + [Theory] + [InlineData(WalletWithdrawalRequestStatus.Pending)] + [InlineData(WalletWithdrawalRequestStatus.PSBTSignaturesPending)] + public async Task GetWithdrawalsRequestStatus_OriginalWithAReplacementAwaitingApproval_ReportsPendingConfirmation( + WalletWithdrawalRequestStatus replacementStatus) + { + var status = await GetStatusAsync(ReplacedRequest(replacementStatus)); + + status.Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingConfirmation, + "its own transaction is still the only candidate in the mempool and may well confirm"); + status.ReplacedByRequestId.Should().Be(11, "clients can already see the replacement being prepared"); + } + + [Theory] + [InlineData(WalletWithdrawalRequestStatus.Failed)] + [InlineData(WalletWithdrawalRequestStatus.Cancelled)] + [InlineData(WalletWithdrawalRequestStatus.Rejected)] + public async Task GetWithdrawalsRequestStatus_OriginalWithAnAbandonedReplacement_ReportsPendingConfirmation( + WalletWithdrawalRequestStatus replacementStatus) + { + var status = await GetStatusAsync(ReplacedRequest(replacementStatus)); + + status.Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingConfirmation); + status.HasReplacedByRequestId.Should().BeFalse(); + } + + [Fact] + public async Task GetWithdrawalsRequestStatus_OriginalWithOwnConfirmations_IsNotReportedAsBumped() + { + var status = await GetStatusAsync(ReplacedRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending), confirmations: 1); + + status.Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingConfirmation, + "it was mined: the replacement is the one that can never confirm"); + status.Confirmations.Should().Be(1UL); + } + + [Fact] + public async Task GetWithdrawalsRequestStatus_StoredBumpedRow_ReportsBumped() + { + var original = ReplacedRequest(WalletWithdrawalRequestStatus.OnChainConfirmed); + original.Status = WalletWithdrawalRequestStatus.Bumped; + original.RejectCancelDescription = WalletWithdrawalRequest.ReplacedReason(11, ReplacementTxId); + + var status = await GetStatusAsync(original); + + status.Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalBumped); + status.RejectOrCancelReason.Should().Be($"Replaced by request 11 (tx {ReplacementTxId})"); + status.ReplacedByRequestId.Should().Be(11); + } + + [Fact] + public async Task GetWithdrawalsRequestStatusByReferenceIds_ReturnsEveryRequestOfTheChain() + { + var original = ReplacedRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending); + var bump = original.Replacements.Single(); + var walletWithdrawalRequestRepository = new Mock(); + walletWithdrawalRequestRepository.Setup(x => x.GetByReferenceIds(It.Is>(l => l.Single() == "store-1"))) + .ReturnsAsync(new List { original, bump }); + + var response = await StatusService(walletWithdrawalRequestRepository, confirmations: 0).GetWithdrawalsRequestStatusByReferenceIds( + new GetWithdrawalsRequestStatusByReferenceIdsRequest { ReferenceIds = { "store-1" } }, TestServerCallContext.Create()); + + response.WithdrawalRequests.Select(r => (r.RequestId, r.Status)).Should().Equal( + (10, WITHDRAWAL_REQUEST_STATUS.WithdrawalBumped), + (11, WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingConfirmation)); + response.WithdrawalRequests[0].ReplacedByRequestId.Should().Be(11, "the caller can follow the chain"); + response.WithdrawalRequests[1].HasReplacedByRequestId.Should().BeFalse(); + } + + [Fact] + public void WalletWithdrawalRequestSelfMap_DropsTheReplacementNavigations() + { + var original = ReplacedRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending); + original.BumpingWalletWithdrawalRequestId = 9; + original.BumpingWalletWithdrawalRequest = new WalletWithdrawalRequest { Id = 9, Description = "older" }; + + var copy = _mockMapper.Map(original); + + copy.Replacements.Should().BeEmpty("Repository.Update attaches the mapped graph; a neighbour must never ride along"); + copy.BumpingWalletWithdrawalRequest.Should().BeNull(); + copy.BumpingWalletWithdrawalRequestId.Should().Be(9); + copy.Status.Should().Be(original.Status); + } + [Fact] public async Task BumpWithdrawal_SchedulingFails_CancelsTheBumpRequest() { diff --git a/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs b/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs index 0391ebe9d..a954e100a 100644 --- a/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs +++ b/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs @@ -395,48 +395,25 @@ public async Task ScheduleHotWalletWithdrawalAsync_RequestAlreadyPsbtSignaturesP _scheduler.Verify(x => x.ScheduleJob(It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); } - [Fact] - public async Task ScheduleHotWalletWithdrawalAsync_Bump_MarksTheReplacedRequestAsBumped() - { - var original = SetupOriginal(HotWallet()); - HotRequest(WalletWithdrawalRequestStatus.PSBTSignaturesPending, bumping: OriginalId); - - await CreateService().ScheduleHotWalletWithdrawalAsync(BumpId); - - original.Status.Should().Be(WalletWithdrawalRequestStatus.Bumped); - _requests.Verify(x => x.Update(It.Is(r => r.Id == OriginalId - && r.Status == WalletWithdrawalRequestStatus.Bumped)), Times.Once); - } - - [Fact] - public async Task ScheduleHotWalletWithdrawalAsync_Cancellation_MarksTheReplacedRequestCancelledWithAReason() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ScheduleHotWalletWithdrawalAsync_Replacement_NeverWritesTheReplacedRequest(bool cancellation) { var original = SetupOriginal(HotWallet()); - HotRequest(WalletWithdrawalRequestStatus.PSBTSignaturesPending, bumping: OriginalId, cancellation: true); + HotRequest(WalletWithdrawalRequestStatus.PSBTSignaturesPending, bumping: OriginalId, cancellation); await CreateService().ScheduleHotWalletWithdrawalAsync(BumpId); - original.Status.Should().Be(WalletWithdrawalRequestStatus.Cancelled, "the payment is not happening, it is not merely re-fed"); - original.RejectCancelDescription.Should().Contain("RBF").And.Contain(BumpId.ToString()); - } - - [Fact] - public async Task ScheduleHotWalletWithdrawalAsync_CancellationSchedulingFails_RestoresTheReplacedRequest() - { - var original = SetupOriginal(HotWallet()); - HotRequest(WalletWithdrawalRequestStatus.PSBTSignaturesPending, bumping: OriginalId, cancellation: true); - _scheduler.Setup(x => x.ScheduleJob(It.IsAny(), It.IsAny(), It.IsAny())) - .ThrowsAsync(new InvalidOperationException("quartz down")); - - var act = () => CreateService().ScheduleHotWalletWithdrawalAsync(BumpId); - - await act.Should().ThrowAsync(); - original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending); + original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending, + "its own transaction is still in the mempool; Bumped / Cancelled is derived from the replacement until it confirms"); original.RejectCancelDescription.Should().BeNull(); + _requests.Verify(x => x.Update(It.Is(r => r.Id == OriginalId)), Times.Never); + _scheduler.Verify(x => x.ScheduleJob(It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); } [Fact] - public async Task ScheduleHotWalletWithdrawalAsync_SchedulingFails_RevertsTheReplacedRequestAndRethrows() + public async Task ScheduleHotWalletWithdrawalAsync_SchedulingFails_RethrowsWithoutTouchingTheReplacedRequest() { var original = SetupOriginal(HotWallet()); HotRequest(WalletWithdrawalRequestStatus.PSBTSignaturesPending, bumping: OriginalId); @@ -446,8 +423,9 @@ public async Task ScheduleHotWalletWithdrawalAsync_SchedulingFails_RevertsTheRep var act = () => CreateService().ScheduleHotWalletWithdrawalAsync(BumpId); await act.Should().ThrowAsync().WithMessage("quartz down"); - original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending, - "an abandoned bump must give the replaced request back its pending-confirmation status"); + original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending); + _requests.Verify(x => x.Update(It.Is(r => r.Id == OriginalId)), Times.Never, + "nothing was written to it, so there is nothing to revert"); } [Fact] @@ -490,157 +468,296 @@ public async Task ScheduleHotWalletWithdrawalAsync_WrongStatus_IsRefused(WalletW await act.Should().ThrowAsync(); } - // ---- MarkOriginalAsBumpedAsync / RevertOriginalAsync ------------------------------------------------------- + // ---- one live replacement per request -------------------------------------------------------------------------- + + [Theory] + [InlineData(WalletWithdrawalRequestStatus.Pending)] + [InlineData(WalletWithdrawalRequestStatus.PSBTSignaturesPending)] + [InlineData(WalletWithdrawalRequestStatus.FinalizingPSBT)] + [InlineData(WalletWithdrawalRequestStatus.OnChainConfirmationPending)] + public async Task CreateBumpRequestAsync_OriginalWithALiveReplacement_IsRefused(WalletWithdrawalRequestStatus replacementStatus) + { + var original = SetupOriginal(HotWallet()); + original.Replacements.Add(Replacement(12, replacementStatus)); + + await AssertRefusedAsync(BumpingErrorReason.InvalidState, MempoolRecommendedFeesType.CustomFee, 10m); + } [Fact] - public async Task RevertOriginalAsync_OnlyRevertsARequestThatIsBumped() + public async Task CreateCancelRequestAsync_OriginalWithALiveReplacement_IsRefused() { - var original = SetupOriginal(HotWallet(), status: WalletWithdrawalRequestStatus.OnChainConfirmed); - var bump = HotRequest(WalletWithdrawalRequestStatus.Cancelled, bumping: OriginalId); + var original = SetupOriginal(HotWallet()); + original.Replacements.Add(Replacement(12, WalletWithdrawalRequestStatus.OnChainConfirmationPending)); - await CreateService().RevertOriginalAsync(bump); + await AssertRefusedAsync(BumpingErrorReason.InvalidState, MempoolRecommendedFeesType.CustomFee, 10m, cancellation: true); + } - original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed, - "a request that was never marked Bumped (or already confirmed) must not be pushed back to pending"); - _requests.Verify(x => x.Update(It.IsAny()), Times.Never); + [Theory] + [InlineData(WalletWithdrawalRequestStatus.Failed)] + [InlineData(WalletWithdrawalRequestStatus.Cancelled)] + [InlineData(WalletWithdrawalRequestStatus.Rejected)] + public async Task CreateBumpRequestAsync_OriginalWithOnlyAbandonedReplacements_IsAllowed(WalletWithdrawalRequestStatus replacementStatus) + { + var original = SetupOriginal(HotWallet()); + original.Replacements.Add(Replacement(12, replacementStatus)); + + var bump = await CreateService().CreateBumpRequestAsync(OriginalId, MempoolRecommendedFeesType.CustomFee, 10m); + + bump.BumpingWalletWithdrawalRequestId.Should().Be(OriginalId, + "an abandoned replacement left the original's transaction in the mempool, so it can be replaced again"); } [Fact] - public async Task RevertOriginalAsync_CancellationByAnotherReplacement_IsLeftAlone() + public async Task CreateBumpRequestAsync_InsertLosesTheRaceToAnotherReplacement_IsRefusedAsInvalidState() { - var original = SetupOriginal(HotWallet(), status: WalletWithdrawalRequestStatus.Cancelled); - original.RejectCancelDescription = "Cancelled by RBF replacement request 99"; - var cancel = HotRequest(WalletWithdrawalRequestStatus.Failed, bumping: OriginalId, cancellation: true); + SetupOriginal(HotWallet()); + _requests.Setup(x => x.AddAsync(It.IsAny())) + .ReturnsAsync((false, "duplicate key value violates unique constraint")); + _requests.Setup(x => x.HasLiveReplacementAsync(OriginalId)).ReturnsAsync(true); - await CreateService().RevertOriginalAsync(cancel); + var act = () => CreateService().CreateBumpRequestAsync(OriginalId, MempoolRecommendedFeesType.CustomFee, 10m); - original.Status.Should().Be(WalletWithdrawalRequestStatus.Cancelled); - _requests.Verify(x => x.Update(It.IsAny()), Times.Never); + (await act.Should().ThrowAsync()).Which.Reason.Should().Be(BumpingErrorReason.InvalidState, + "the database lets one live replacement through; the loser is told so, not 'internal error'"); + _coinSelection.Verify(x => x.LockUTXOs(It.IsAny>(), It.IsAny(), It.IsAny()), Times.Never); } [Fact] - public async Task MarkOriginalAsReplacedAsync_NotAReplacement_IsANoOp() + public async Task CreateBumpRequestAsync_InsertFailsForAnotherReason_IsAPersistenceError() { - var request = HotRequest(WalletWithdrawalRequestStatus.PSBTSignaturesPending); + SetupOriginal(HotWallet()); + _requests.Setup(x => x.AddAsync(It.IsAny())).ReturnsAsync((false, "db down")); + _requests.Setup(x => x.HasLiveReplacementAsync(OriginalId)).ReturnsAsync(false); - await CreateService().MarkOriginalAsReplacedAsync(request); + var act = () => CreateService().CreateBumpRequestAsync(OriginalId, MempoolRecommendedFeesType.CustomFee, 10m); - _requests.Verify(x => x.Update(It.IsAny()), Times.Never); + (await act.Should().ThrowAsync()).Which.Reason.Should().Be(BumpingErrorReason.PersistenceError); } + // ---- ReconcileReplacementChainsAsync --------------------------------------------------------------------------- + [Fact] - public async Task MarkOriginalAsReplacedAsync_OriginalAlreadySettled_IsLeftAlone() + public async Task ReconcileReplacementChainsAsync_ReplacementConfirmed_MarksTheOriginalBumped() { - var original = SetupOriginal(ColdWallet(), status: WalletWithdrawalRequestStatus.OnChainConfirmed, confirmations: SettledDepth); - var bump = HotRequest(WalletWithdrawalRequestStatus.PSBTSignaturesPending, bumping: OriginalId); + var original = Row(10, WalletWithdrawalRequestStatus.OnChainConfirmationPending); + var bump = Row(11, WalletWithdrawalRequestStatus.OnChainConfirmed, replaces: 10); + Chain(original, bump); - await CreateService().MarkOriginalAsReplacedAsync(bump); + await CreateService().ReconcileReplacementChainsAsync(); - original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed, - "it was mined while the cold-wallet replacement was collecting signatures"); - _requests.Verify(x => x.Update(It.IsAny()), Times.Never); + original.Status.Should().Be(WalletWithdrawalRequestStatus.Bumped); + original.RejectCancelDescription.Should().Be($"Replaced by request 11 (tx {bump.TxId})"); + _requests.Verify(x => x.Update(original), Times.Once); + _requests.Verify(x => x.Update(It.IsAny()), Times.Once, "the confirmed replacement is left as it is"); } - // ---- SettleMinedOriginalAsync ----------------------------------------------------------------------------- + [Fact] + public async Task ReconcileReplacementChainsAsync_CancellationConfirmed_MarksTheOriginalCancelledWithTheReason() + { + var original = Row(10, WalletWithdrawalRequestStatus.OnChainConfirmationPending); + var cancel = Row(11, WalletWithdrawalRequestStatus.OnChainConfirmed, replaces: 10, cancellation: true); + Chain(original, cancel); + + await CreateService().ReconcileReplacementChainsAsync(); + + original.Status.Should().Be(WalletWithdrawalRequestStatus.Cancelled, "the destination was never paid"); + original.RejectCancelDescription.Should().Be($"Cancelled by RBF replacement request 11 (tx {cancel.TxId})"); + } [Fact] - public async Task SettleMinedOriginalAsync_OriginalMined_SettlesItAndFailsTheReplacement() + public async Task ReconcileReplacementChainsAsync_BumpOfABumpConfirmed_MarksBothAncestorsBumped() { - var original = SetupOriginal(HotWallet(), status: WalletWithdrawalRequestStatus.Bumped, confirmations: SettledDepth); - var bump = HotRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending, bumping: OriginalId); + var first = Row(10, WalletWithdrawalRequestStatus.OnChainConfirmationPending); + var second = Row(11, WalletWithdrawalRequestStatus.OnChainConfirmationPending, replaces: 10); + var third = Row(12, WalletWithdrawalRequestStatus.OnChainConfirmed, replaces: 11); + Chain(first, second, third); - var settled = await CreateService().SettleMinedOriginalAsync(bump); + await CreateService().ReconcileReplacementChainsAsync(); - settled.Should().BeTrue(); - original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed, "its transaction is the one that confirmed"); - bump.Status.Should().Be(WalletWithdrawalRequestStatus.Failed, "it double-spends a confirmed transaction"); - bump.RejectCancelDescription.Should().Contain(OriginalId.ToString()).And.Contain(_originalTxId.ToString()); + first.Status.Should().Be(WalletWithdrawalRequestStatus.Bumped); + first.RejectCancelDescription.Should().Contain("12", "the reason names the transaction that confirmed, not the next hop"); + second.Status.Should().Be(WalletWithdrawalRequestStatus.Bumped); + _requests.Verify(x => x.Update(third), Times.Never); } [Fact] - public async Task SettleMinedOriginalAsync_CancelledOriginalMined_ClearsTheCancellationReason() + public async Task ReconcileReplacementChainsAsync_BumpOfACancellationConfirmed_MarksTheFirstOriginalCancelled() { - var original = SetupOriginal(HotWallet(), status: WalletWithdrawalRequestStatus.Cancelled, confirmations: SettledDepth); - original.RejectCancelDescription = $"Cancelled by RBF replacement request {BumpId}"; - var cancel = HotRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending, bumping: OriginalId, cancellation: true); + var first = Row(10, WalletWithdrawalRequestStatus.OnChainConfirmationPending); + var cancel = Row(11, WalletWithdrawalRequestStatus.OnChainConfirmationPending, replaces: 10, cancellation: true); + var bumpOfCancel = Row(12, WalletWithdrawalRequestStatus.OnChainConfirmed, replaces: 11); + Chain(first, cancel, bumpOfCancel); - await CreateService().SettleMinedOriginalAsync(cancel); + await CreateService().ReconcileReplacementChainsAsync(); - original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed); - original.RejectCancelDescription.Should().BeNull("the cancellation never took effect: the destination was paid"); - cancel.Status.Should().Be(WalletWithdrawalRequestStatus.Failed); + first.Status.Should().Be(WalletWithdrawalRequestStatus.Cancelled, + "a bump of a cancellation still returns the funds: the first destination was never paid"); + first.RejectCancelDescription.Should().Contain("12"); + cancel.Status.Should().Be(WalletWithdrawalRequestStatus.Bumped, "its own transaction was merely re-fed"); } [Fact] - public async Task SettleMinedOriginalAsync_OriginalUnconfirmed_LeavesBothAlone() + public async Task ReconcileReplacementChainsAsync_CancellationOfABumpConfirmed_CancelsBoth() { - var original = SetupOriginal(HotWallet(), status: WalletWithdrawalRequestStatus.Bumped, confirmations: 0); - var bump = HotRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending, bumping: OriginalId); + var first = Row(10, WalletWithdrawalRequestStatus.OnChainConfirmationPending); + var bump = Row(11, WalletWithdrawalRequestStatus.OnChainConfirmationPending, replaces: 10); + var cancelOfBump = Row(12, WalletWithdrawalRequestStatus.OnChainConfirmed, replaces: 11, cancellation: true); + Chain(first, bump, cancelOfBump); - var settled = await CreateService().SettleMinedOriginalAsync(bump); + await CreateService().ReconcileReplacementChainsAsync(); - settled.Should().BeFalse(); - original.Status.Should().Be(WalletWithdrawalRequestStatus.Bumped); - bump.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending); + first.Status.Should().Be(WalletWithdrawalRequestStatus.Cancelled); + bump.Status.Should().Be(WalletWithdrawalRequestStatus.Cancelled); + } + + [Fact] + public async Task ReconcileReplacementChainsAsync_OriginalConfirmed_FailsEveryLiveDescendant() + { + var original = Row(10, WalletWithdrawalRequestStatus.OnChainConfirmed); + var broadcast = Row(11, WalletWithdrawalRequestStatus.OnChainConfirmationPending, replaces: 10); + var awaitingApproval = Row(12, WalletWithdrawalRequestStatus.Pending, replaces: 11); + Chain(original, broadcast, awaitingApproval); + + await CreateService().ReconcileReplacementChainsAsync(); + + broadcast.Status.Should().Be(WalletWithdrawalRequestStatus.Failed, "it double-spends a confirmed transaction"); + broadcast.RejectCancelDescription.Should().Be($"Withdrawal request 10 was mined instead (tx {original.TxId})"); + awaitingApproval.Status.Should().Be(WalletWithdrawalRequestStatus.Failed, + "a cold replacement awaiting approval can never be broadcast either, and must leave the approvers' grid"); + awaitingApproval.RejectCancelDescription.Should().Contain("10"); + _requests.Verify(x => x.Update(original), Times.Never); + } + + [Fact] + public async Task ReconcileReplacementChainsAsync_OriginalConfirmed_SkipsAFinalizingDescendant() + { + var original = Row(10, WalletWithdrawalRequestStatus.OnChainConfirmed); + var finalizing = Row(11, WalletWithdrawalRequestStatus.FinalizingPSBT, replaces: 10); + Chain(original, finalizing); + + await CreateService().ReconcileReplacementChainsAsync(); + + finalizing.Status.Should().Be(WalletWithdrawalRequestStatus.FinalizingPSBT, + "PerformWithdrawal writes that row whole when it broadcasts; the next run decides"); _requests.Verify(x => x.Update(It.IsAny()), Times.Never); } [Fact] - public async Task SettleMinedOriginalAsync_BumpOfABump_SettlesTheMinedRequestAndLeavesTheMiddleOneBumped() + public async Task ReconcileReplacementChainsAsync_BothDirectionsConfirmed_ThePaymentWins() { - const int middleId = 12; - var middleTxId = new uint256(2); - var first = SetupOriginal(HotWallet(), status: WalletWithdrawalRequestStatus.Bumped, confirmations: SettledDepth); - var middle = new WalletWithdrawalRequest - { - Id = middleId, - Status = WalletWithdrawalRequestStatus.Bumped, - TxId = middleTxId.ToString(), - BumpingWalletWithdrawalRequestId = OriginalId, - }; - _requests.Setup(x => x.GetById(middleId)).ReturnsAsync(middle); - _nbXplorer.Setup(x => x.GetTransactionAsync(middleTxId, It.IsAny())) - .ReturnsAsync(new TransactionResult { Confirmations = 0 }); - var last = HotRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending, bumping: middleId); + var original = Row(10, WalletWithdrawalRequestStatus.OnChainConfirmed); + var middle = Row(11, WalletWithdrawalRequestStatus.OnChainConfirmationPending, replaces: 10); + var last = Row(12, WalletWithdrawalRequestStatus.OnChainConfirmed, replaces: 11); + Chain(original, middle, last); - var settled = await CreateService().SettleMinedOriginalAsync(last); + await CreateService().ReconcileReplacementChainsAsync(); - settled.Should().BeTrue(); - first.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed); - middle.Status.Should().Be(WalletWithdrawalRequestStatus.Bumped, "it was replaced and never confirmed"); - last.Status.Should().Be(WalletWithdrawalRequestStatus.Failed); + middle.Status.Should().Be(WalletWithdrawalRequestStatus.Failed, "a confirmed ancestor means the payment happened"); + middle.RejectCancelDescription.Should().Contain("10"); } [Fact] - public async Task SettleMinedOriginalAsync_NotAReplacement_IsANoOp() + public async Task ReconcileReplacementChainsAsync_NothingConfirmed_WritesNothing() { - var request = HotRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending); + var original = Row(10, WalletWithdrawalRequestStatus.OnChainConfirmationPending); + var bump = Row(11, WalletWithdrawalRequestStatus.OnChainConfirmationPending, replaces: 10); + Chain(original, bump); - var settled = await CreateService().SettleMinedOriginalAsync(request); + await CreateService().ReconcileReplacementChainsAsync(); - settled.Should().BeFalse(); + original.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending); + bump.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending); _requests.Verify(x => x.Update(It.IsAny()), Times.Never); - _nbXplorer.Verify(x => x.GetTransactionAsync(It.IsAny(), It.IsAny()), Times.Never); } [Fact] - public async Task SettleMinedOriginalAsync_SettlingTheOriginalFails_LeavesTheReplacementPending() + public async Task ReconcileReplacementChainsAsync_AbandonedSiblingReplacement_IsIgnored() + { + var original = Row(10, WalletWithdrawalRequestStatus.OnChainConfirmationPending); + var abandoned = Row(11, WalletWithdrawalRequestStatus.Failed, replaces: 10); + var confirmed = Row(12, WalletWithdrawalRequestStatus.OnChainConfirmed, replaces: 10); + Chain(original, abandoned, confirmed); + + await CreateService().ReconcileReplacementChainsAsync(); + + original.Status.Should().Be(WalletWithdrawalRequestStatus.Bumped); + original.RejectCancelDescription.Should().Contain("12"); + _requests.Verify(x => x.Update(abandoned), Times.Never); + } + + [Fact] + public async Task ReconcileReplacementChainsAsync_OneChainThrowing_DoesNotStopTheOthers() + { + var broken = Row(10, WalletWithdrawalRequestStatus.OnChainConfirmationPending, replaces: 9); + Live(broken); + _requests.Setup(x => x.GetRbfChainAsync(10)).ThrowsAsync(new InvalidOperationException("db down")); + var original = Row(20, WalletWithdrawalRequestStatus.OnChainConfirmationPending); + var bump = Row(21, WalletWithdrawalRequestStatus.OnChainConfirmed, replaces: 20); + Chain(original, bump); + + var act = () => CreateService().ReconcileReplacementChainsAsync(); + + await act.Should().NotThrowAsync(); + original.Status.Should().Be(WalletWithdrawalRequestStatus.Bumped); + } + + [Fact] + public async Task ReconcileReplacementChainsAsync_UpdateFails_IsOnlyLogged() { - SetupOriginal(HotWallet(), status: WalletWithdrawalRequestStatus.Bumped, confirmations: SettledDepth); - var bump = HotRequest(WalletWithdrawalRequestStatus.OnChainConfirmationPending, bumping: OriginalId); - _requests.Setup(x => x.Update(It.Is(r => r.Id == OriginalId))).Returns((false, "db down")); + var original = Row(10, WalletWithdrawalRequestStatus.OnChainConfirmationPending); + var bump = Row(11, WalletWithdrawalRequestStatus.OnChainConfirmed, replaces: 10); + Chain(original, bump); + _requests.Setup(x => x.Update(It.IsAny())).Returns((false, "db down")); - var settled = await CreateService().SettleMinedOriginalAsync(bump); + var act = () => CreateService().ReconcileReplacementChainsAsync(); - settled.Should().BeFalse(); - bump.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending, "the next monitoring run retries both"); - _requests.Verify(x => x.Update(It.Is(r => r.Id == BumpId)), Times.Never); + await act.Should().NotThrowAsync("the next run retries; nothing else was written"); } // ---- fixtures --------------------------------------------------------------------------------------------- - /// Confirmations at which the monitor settles a withdrawal (the constant is 0 when its env var is unset). - private static int SettledDepth => Math.Max(1, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS); + private readonly List _liveLinked = new(); + + private static WalletWithdrawalRequest Replacement(int id, WalletWithdrawalRequestStatus status) => new() + { + Id = id, + Status = status, + Description = "replacement", + BumpingWalletWithdrawalRequestId = OriginalId, + }; + + /// A broadcast-or-later request of an RBF chain; its txid is derived from its id. + private static WalletWithdrawalRequest Row(int id, WalletWithdrawalRequestStatus status, int? replaces = null, + bool cancellation = false) => new() + { + Id = id, + Status = status, + Description = "chain", + TxId = new uint256((ulong)id).ToString(), + BumpingWalletWithdrawalRequestId = replaces, + IsRbfCancellation = cancellation, + }; + + /// + /// Wires a chain the way the repository returns it: every member resolves to the whole chain, and the live ones + /// are what the reconciliation iterates (FinalizingPSBT included, to exercise the service's own guard). + /// + private void Chain(params WalletWithdrawalRequest[] members) + { + var chain = members.ToList(); + foreach (var member in members) + { + _requests.Setup(x => x.GetRbfChainAsync(member.Id)).ReturnsAsync(chain); + } + + Live(members.Where(m => m.IsLive).ToArray()); + } + + private void Live(params WalletWithdrawalRequest[] rows) + { + _liveLinked.AddRange(rows); + _requests.Setup(x => x.GetLiveRbfLinkedRequestsAsync()).ReturnsAsync(_liveLinked.ToList()); + } private async Task AssertRefusedAsync(BumpingErrorReason reason, MempoolRecommendedFeesType feeType, decimal? customFeeRate, bool cancellation = false) From e51cc241694ad8d9d8d21a975bb48e6f8ba1c874 Mon Sep 17 00:00:00 2001 From: Marcos Date: Mon, 19 Oct 2026 18:15:08 +0200 Subject: [PATCH 3/3] Simplify the RBF chain reconciliation and its lookups - One Ancestors iterator replaces the two hand-rolled upward walks; the chain is cached as a dictionary and the live rows are fetched as ids - One "live" status set: the repository and the index filter derive from WalletWithdrawalRequest.LiveStatuses; the FinalizingPSBT skip lives in the service only - SupersededBy gives the derived and the stored Bumped / Cancelled the same (status, reason), and the reason builders share one tx suffix - Repository.AddAsync returns the database's message like AddRangeAsync, so the unique-index race is recognised from it and HasLiveReplacementAsync goes away - GetRbfChainAsync walks up to the root, then down level by level, no re-fetching; the status RPC looks confirmations up in parallel - TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS is clamped at its source - The Withdrawals page shows the stored status plus the replacement; the migration keys RBF-cancelled rows on the link, not on the reason text --- src/Data/ApplicationDbContext.cs | 5 +- src/Data/Models/WalletWithdrawalRequest.cs | 50 ++++++++----- .../IWalletWithdrawalRequestRepository.cs | 10 +-- src/Data/Repositories/Repository.cs | 2 + .../WalletWithdrawalRequestRepository.cs | 61 +++++++--------- src/Helpers/Constants.cs | 3 +- src/Jobs/MonitorWithdrawalsJob.cs | 6 +- .../20261019133733_BumpedIsTerminalOnly.cs | 10 ++- src/Pages/Withdrawals.razor | 9 +-- src/Rpc/NodeGuardService.cs | 29 ++++---- src/Services/WithdrawalRequestService.cs | 71 ++++++++----------- .../WalletWithdrawalRequestRepositoryTests.cs | 41 ++--------- .../Jobs/MonitorWithdrawalsJobTests.cs | 42 ++++++----- .../Rpc/NodeGuardServiceTests.cs | 7 +- .../Services/WithdrawalRequestServiceTests.cs | 36 ++++------ 15 files changed, 167 insertions(+), 215 deletions(-) diff --git a/src/Data/ApplicationDbContext.cs b/src/Data/ApplicationDbContext.cs index d7916d996..f8f6c46f4 100644 --- a/src/Data/ApplicationDbContext.cs +++ b/src/Data/ApplicationDbContext.cs @@ -95,10 +95,11 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .WithMany(x => x.Replacements) .HasForeignKey(x => x.BumpingWalletWithdrawalRequestId); modelBuilder.Entity().HasIndex(x => x.BumpingWalletWithdrawalRequestId); + var liveStatuses = string.Join(", ", WalletWithdrawalRequest.LiveStatuses.Cast().OrderBy(s => s)); modelBuilder.Entity() - .HasIndex(x => x.BumpingWalletWithdrawalRequestId, "IX_WalletWithdrawalRequests_LiveReplacement") + .HasIndex(x => x.BumpingWalletWithdrawalRequestId, WalletWithdrawalRequest.LiveReplacementIndex) .IsUnique() - .HasFilter("\"BumpingWalletWithdrawalRequestId\" IS NOT NULL AND \"Status\" IN (0, 3, 4, 7)"); + .HasFilter($"\"BumpingWalletWithdrawalRequestId\" IS NOT NULL AND \"Status\" IN ({liveStatuses})"); modelBuilder.Entity().HasIndex(x => x.NormalizedUserName).IsUnique(); diff --git a/src/Data/Models/WalletWithdrawalRequest.cs b/src/Data/Models/WalletWithdrawalRequest.cs index 804af0113..a4d29f72d 100644 --- a/src/Data/Models/WalletWithdrawalRequest.cs +++ b/src/Data/Models/WalletWithdrawalRequest.cs @@ -236,9 +236,12 @@ public bool Equals(WalletWithdrawalRequest? other) /// public List Replacements { get; set; } = new(); + /// Partial unique index: at most one replacement of a request in a live status. + public const string LiveReplacementIndex = "IX_WalletWithdrawalRequests_LiveReplacement"; + /// /// Statuses in which a request can still put (or has put) a transaction in the mempool. A replacement in any of - /// them blocks a second replacement of the same request (IX_WalletWithdrawalRequests_LiveReplacement). + /// them blocks a second replacement of the same request (). /// public static readonly WalletWithdrawalRequestStatus[] LiveStatuses = { @@ -258,40 +261,53 @@ or WalletWithdrawalRequestStatus.Cancelled /// The replacement still in flight, if any. Needs loaded. [NotMapped] - public WalletWithdrawalRequest? LiveReplacement => Replacements?.FirstOrDefault(r => r.IsLive); + public WalletWithdrawalRequest? LiveReplacement => Replacements.FirstOrDefault(r => r.IsLive); /// The replacement whose transaction competes with this one's in the mempool, if any. [NotMapped] public WalletWithdrawalRequest? BroadcastReplacement => - Replacements?.FirstOrDefault(r => r.Status == WalletWithdrawalRequestStatus.OnChainConfirmationPending); + Replacements.FirstOrDefault(r => r.Status == WalletWithdrawalRequestStatus.OnChainConfirmationPending); - public const string RbfCancellationReasonPrefix = "Cancelled by RBF replacement request"; + /// The newest replacement that was not abandoned: the next hop when following a chain by id. + [NotMapped] + public WalletWithdrawalRequest? NewestReplacement => Replacements.Where(r => !r.IsAbandoned).MaxBy(r => r.Id); public static string RbfCancellationReason(int replacementId, string? txId) => - $"{RbfCancellationReasonPrefix} {replacementId}" + (string.IsNullOrEmpty(txId) ? "" : $" (tx {txId})"); + WithTx($"Cancelled by RBF replacement request {replacementId}", txId); public static string ReplacedReason(int replacementId, string? txId) => - $"Replaced by request {replacementId}" + (string.IsNullOrEmpty(txId) ? "" : $" (tx {txId})"); + WithTx($"Replaced by request {replacementId}", txId); + + public static string MinedInsteadReason(int originalId, string? txId) => + WithTx($"Withdrawal request {originalId} was mined instead", txId); + + private static string WithTx(string reason, string? txId) => + string.IsNullOrEmpty(txId) ? reason : $"{reason} (tx {txId})"; /// - /// The status to report for this request. The stored one describes its own transaction only: while a - /// replacement's transaction is in the mempool and this one has no confirmations, it is reported as Bumped - /// (Cancelled for an RBF cancellation), the status it will be stored with once that replacement settles. - /// ReplacedById is the newest replacement that was not abandoned, so a chain can be followed by id. + /// What a request superseded by becomes: Cancelled when a cancellation sits + /// on the way to it, otherwise Bumped. /// - public (WalletWithdrawalRequestStatus Status, string? Reason, int? ReplacedById) EffectiveStatus(ulong ownConfirmations = 0) - { - var replacedBy = Replacements?.Where(r => !r.IsAbandoned).MaxBy(r => r.Id); + public static (WalletWithdrawalRequestStatus Status, string Reason) SupersededBy(WalletWithdrawalRequest replacement, bool cancellation) => + cancellation + ? (WalletWithdrawalRequestStatus.Cancelled, RbfCancellationReason(replacement.Id, replacement.TxId)) + : (WalletWithdrawalRequestStatus.Bumped, ReplacedReason(replacement.Id, replacement.TxId)); + /// + /// The status the API reports. The stored one describes this request's own transaction only: while a + /// replacement's transaction is in the mempool and this one has no confirmations, the request is reported + /// with the status it will be stored with once that replacement settles. + /// + public (WalletWithdrawalRequestStatus Status, string? Reason, int? ReplacedById) EffectiveStatus(ulong ownConfirmations) + { if (Status == WalletWithdrawalRequestStatus.OnChainConfirmationPending && ownConfirmations == 0 && BroadcastReplacement is { } broadcast) { - return broadcast.IsRbfCancellation - ? (WalletWithdrawalRequestStatus.Cancelled, RbfCancellationReason(broadcast.Id, broadcast.TxId), broadcast.Id) - : (WalletWithdrawalRequestStatus.Bumped, null, broadcast.Id); + var (status, reason) = SupersededBy(broadcast, broadcast.IsRbfCancellation); + return (status, reason, broadcast.Id); } - return (Status, RejectCancelDescription, replacedBy?.Id); + return (Status, RejectCancelDescription, NewestReplacement?.Id); } public List WalletWithdrawalRequestPSBTs { get; set; } diff --git a/src/Data/Repositories/Interfaces/IWalletWithdrawalRequestRepository.cs b/src/Data/Repositories/Interfaces/IWalletWithdrawalRequestRepository.cs index 06f6f0a5e..6fd51aab2 100644 --- a/src/Data/Repositories/Interfaces/IWalletWithdrawalRequestRepository.cs +++ b/src/Data/Repositories/Interfaces/IWalletWithdrawalRequestRepository.cs @@ -59,18 +59,12 @@ public interface IWalletWithdrawalRequestRepository : IBitcoinRequestRepository Task> GetOnChainPendingWithdrawals(); - /// Whether a request that replaces this one (RBF) is in a live status. - Task HasLiveReplacementAsync(int requestId); - /// /// Every request connected to this one through RBF links, in both directions, the request itself included. /// Untracked, no navigations loaded. /// Task> GetRbfChainAsync(int requestId); - /// - /// Requests in Pending, PSBTSignaturesPending or OnChainConfirmationPending that replace another request or are - /// replaced by one. Not FinalizingPSBT: PerformWithdrawal writes that row whole when it broadcasts. - /// - Task> GetLiveRbfLinkedRequestsAsync(); + /// Ids of the live requests that replace another request or are replaced by one. + Task> GetLiveRbfLinkedRequestIdsAsync(); } \ No newline at end of file diff --git a/src/Data/Repositories/Repository.cs b/src/Data/Repositories/Repository.cs index 3bec0c5b9..c95add584 100644 --- a/src/Data/Repositories/Repository.cs +++ b/src/Data/Repositories/Repository.cs @@ -60,6 +60,8 @@ public async Task> GetAll(ApplicationDbContext applicationDbContext) catch (Exception e) { _logger.LogError(e, "Error on repository"); + // The innermost message is the database's own (e.g. the constraint a unique index rejected). + return (false, e.GetBaseException().Message); } return (rowsChanged, null); diff --git a/src/Data/Repositories/WalletWithdrawalRequestRepository.cs b/src/Data/Repositories/WalletWithdrawalRequestRepository.cs index ef992bd7b..70de087b0 100644 --- a/src/Data/Repositories/WalletWithdrawalRequestRepository.cs +++ b/src/Data/Repositories/WalletWithdrawalRequestRepository.cs @@ -385,62 +385,55 @@ public async Task> GetPendingRequests() return walletWithdrawalRequests; } - public async Task HasLiveReplacementAsync(int requestId) + public async Task> GetRbfChainAsync(int requestId) { await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); + var requests = applicationDbContext.WalletWithdrawalRequests.AsNoTracking(); - var live = WalletWithdrawalRequest.LiveStatuses; - return await applicationDbContext.WalletWithdrawalRequests - .AnyAsync(x => x.BumpingWalletWithdrawalRequestId == requestId && live.Contains(x.Status)); - } + // Up to the first request of the chain, then down through every replacement, level by level. One query + // per hop; chains are a handful of rows. + var root = await requests.SingleOrDefaultAsync(x => x.Id == requestId); + if (root == null) return new List(); - public async Task> GetRbfChainAsync(int requestId) - { - await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); + var chain = new Dictionary { [root.Id] = root }; + while (root.BumpingWalletWithdrawalRequestId is { } replacedId && !chain.ContainsKey(replacedId)) + { + var replaced = await requests.SingleOrDefaultAsync(x => x.Id == replacedId); + if (replaced == null) break; - // Breadth-first over the link in both directions, one query per hop. Chains are a handful of rows. - var chain = new Dictionary(); - var frontier = new List { requestId }; + chain[replaced.Id] = replaced; + root = replaced; + } + + var expanded = new HashSet { root.Id }; + var frontier = new List { root.Id }; while (frontier.Count > 0) { - var ids = frontier; - var hop = await applicationDbContext.WalletWithdrawalRequests - .AsNoTracking() - .Where(x => ids.Contains(x.Id) - || (x.BumpingWalletWithdrawalRequestId != null && ids.Contains(x.BumpingWalletWithdrawalRequestId.Value))) + var parents = frontier; + var children = await requests + .Where(x => x.BumpingWalletWithdrawalRequestId != null && parents.Contains(x.BumpingWalletWithdrawalRequestId.Value)) .ToListAsync(); frontier = new List(); - foreach (var request in hop) + foreach (var child in children) { - if (!chain.TryAdd(request.Id, request)) continue; - - frontier.Add(request.Id); - if (request.BumpingWalletWithdrawalRequestId is { } replacedId && !chain.ContainsKey(replacedId)) - { - frontier.Add(replacedId); - } + chain.TryAdd(child.Id, child); + if (expanded.Add(child.Id)) frontier.Add(child.Id); } } return chain.Values.OrderBy(x => x.Id).ToList(); } - public async Task> GetLiveRbfLinkedRequestsAsync() + public async Task> GetLiveRbfLinkedRequestIdsAsync() { await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); - var statuses = new[] - { - WalletWithdrawalRequestStatus.Pending, - WalletWithdrawalRequestStatus.PSBTSignaturesPending, - WalletWithdrawalRequestStatus.OnChainConfirmationPending, - }; - + var live = WalletWithdrawalRequest.LiveStatuses; return await applicationDbContext.WalletWithdrawalRequests - .AsNoTracking() - .Where(x => statuses.Contains(x.Status) + .Where(x => live.Contains(x.Status) && (x.BumpingWalletWithdrawalRequestId != null || x.Replacements.Any())) + .Select(x => x.Id) .ToListAsync(); } diff --git a/src/Helpers/Constants.cs b/src/Helpers/Constants.cs index 91344a98b..6f6efb89f 100644 --- a/src/Helpers/Constants.cs +++ b/src/Helpers/Constants.cs @@ -525,8 +525,9 @@ static Constants() var environmentVariableMax = Environment.GetEnvironmentVariable("MAXIMUM_WITHDRAWAL_BTC_AMOUNT"); if (environmentVariableMax != null) MAXIMUM_WITHDRAWAL_BTC_AMOUNT = decimal.Parse(environmentVariableMax, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); + // At least one: a transaction evicted from the mempool sits at 0 confirmations and must never count as mined. var transactionConfBlocks = GetEnvironmentalVariableOrThrowIfNotTesting("TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS"); - if (transactionConfBlocks != null) TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS = int.Parse(transactionConfBlocks); + TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS = Math.Max(1, transactionConfBlocks != null ? int.Parse(transactionConfBlocks) : 1); var defaultChannelFeePolicyTimelockDeltaBlocks = Environment.GetEnvironmentVariable("DEFAULT_CHANNEL_FEE_POLICY_TIMELOCK_DELTA_BLOCKS"); if (defaultChannelFeePolicyTimelockDeltaBlocks != null) DEFAULT_CHANNEL_FEE_POLICY_TIMELOCK_DELTA_BLOCKS = int.Parse(defaultChannelFeePolicyTimelockDeltaBlocks); diff --git a/src/Jobs/MonitorWithdrawalsJob.cs b/src/Jobs/MonitorWithdrawalsJob.cs index 7a44abe0c..35d7a898d 100644 --- a/src/Jobs/MonitorWithdrawalsJob.cs +++ b/src/Jobs/MonitorWithdrawalsJob.cs @@ -55,10 +55,6 @@ public async Task Execute(IJobExecutionContext context) _logger.LogInformation($"Job {nameof(MonitorWithdrawalsJob)} started"); var withdrawalsPending = await _walletWithdrawalRequestRepository.GetOnChainPendingWithdrawals(); - // An unset TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS is 0. Replaced requests are polled too, and one whose - // transaction was evicted sits at 0 confirmations: that is not mined. - var minimumConfirmations = Math.Max(1, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS); - foreach (var walletWithdrawalRequest in withdrawalsPending) { if (string.IsNullOrEmpty(walletWithdrawalRequest.TxId)) continue; @@ -73,7 +69,7 @@ public async Task Execute(IJobExecutionContext context) continue; } - if (getTxResult.Confirmations < minimumConfirmations) continue; + if (getTxResult.Confirmations < Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS) continue; walletWithdrawalRequest.Status = WalletWithdrawalRequestStatus.OnChainConfirmed; var (updated, _) = _walletWithdrawalRequestRepository.Update(walletWithdrawalRequest); diff --git a/src/Migrations/20261019133733_BumpedIsTerminalOnly.cs b/src/Migrations/20261019133733_BumpedIsTerminalOnly.cs index a3f63f751..92b4be1c1 100644 --- a/src/Migrations/20261019133733_BumpedIsTerminalOnly.cs +++ b/src/Migrations/20261019133733_BumpedIsTerminalOnly.cs @@ -28,11 +28,15 @@ public partial class BumpedIsTerminalOnly : Migration { // WalletWithdrawalRequestStatus: Pending = 0, Cancelled = 1, PSBTSignaturesPending = 3, // OnChainConfirmationPending = 4, OnChainConfirmed = 5, FinalizingPSBT = 7, Bumped = 8 + // A Cancelled request with an RBF-cancellation replacement was cancelled by it: humans can only cancel a + // request that was never broadcast, and only a broadcast one gets replacements. private const string Repair = @" WITH RECURSIVE roots AS ( - SELECT ""Id"" FROM ""WalletWithdrawalRequests"" - WHERE ""Status"" = 8 - OR (""Status"" = 1 AND ""RejectCancelDescription"" LIKE 'Cancelled by RBF replacement request%') + SELECT w.""Id"" FROM ""WalletWithdrawalRequests"" w + WHERE w.""Status"" = 8 + OR (w.""Status"" = 1 AND EXISTS ( + SELECT 1 FROM ""WalletWithdrawalRequests"" r + WHERE r.""BumpingWalletWithdrawalRequestId"" = w.""Id"" AND r.""IsRbfCancellation"")) ), descendants AS ( SELECT r.""Id"" AS root_id, r.""Id"" AS node_id FROM roots r UNION diff --git a/src/Pages/Withdrawals.razor b/src/Pages/Withdrawals.razor index c75f9e0ba..494c81eae 100644 --- a/src/Pages/Withdrawals.razor +++ b/src/Pages/Withdrawals.razor @@ -416,12 +416,9 @@ - @{ - // A replaced request keeps its own stored status; the UI shows what the API reports. - var (effectiveStatus, effectiveReason, replacedById) = context.EffectiveStatus(); - } - - @effectiveStatus.Humanize()@(replacedById is { } replacedBy ? $" · replaced by #{replacedBy}" : "") + @* The stored status is the row's own transaction; the replacement, if any, is named next to it. *@ + + @context.Status.Humanize()@(context.NewestReplacement is { } replacement ? $" · replaced by #{replacement.Id}" : "") diff --git a/src/Rpc/NodeGuardService.cs b/src/Rpc/NodeGuardService.cs index df9182b91..c9862aca7 100644 --- a/src/Rpc/NodeGuardService.cs +++ b/src/Rpc/NodeGuardService.cs @@ -1339,32 +1339,27 @@ private WITHDRAWAL_REQUEST_STATUS GetStatus(WalletWithdrawalRequestStatus status private async Task GetWithdrawalsRequestStatusResponse(List withdrawalRequests) { - var withdrawalsResponses = new List(); - foreach (var withdrawalRequest in withdrawalRequests) - { - ulong confirmations = 0; - if (withdrawalRequest.TxId != null) - { - var nbxplorerStatus = await _nbXplorerService.GetTransactionAsync(uint256.Parse(withdrawalRequest.TxId)); - confirmations = (ulong)(nbxplorerStatus?.Confirmations ?? 0); - } + // A reference id resolves to its whole RBF chain: one NBXplorer round trip for all of them, not one each. + var confirmations = await Task.WhenAll(withdrawalRequests.Select(GetConfirmationsAsync)); + var withdrawalsResponses = withdrawalRequests.Zip(confirmations, (withdrawalRequest, confirmed) => + { // A replaced request keeps its own stored status; what the client sees is derived from its replacements. - var (status, reason, replacedById) = withdrawalRequest.EffectiveStatus(confirmations); + var (status, reason, replacedById) = withdrawalRequest.EffectiveStatus(confirmed); var response = new WithdrawalRequest { RequestId = withdrawalRequest.Id, Status = GetStatus(status), RejectOrCancelReason = reason ?? "", ReferenceId = withdrawalRequest.ReferenceId ?? "", - Confirmations = confirmations, + Confirmations = confirmed, TxId = withdrawalRequest.TxId ?? "", RequestMetadata = withdrawalRequest.RequestMetadata ?? "", }; if (replacedById is { } id) response.ReplacedByRequestId = id; - withdrawalsResponses.Add(response); - } + return response; + }); return new GetWithdrawalsRequestStatusResponse() { @@ -1372,6 +1367,14 @@ private async Task GetWithdrawalsRequestSta }; } + private async Task GetConfirmationsAsync(WalletWithdrawalRequest withdrawalRequest) + { + if (withdrawalRequest.TxId == null) return 0; + + var nbxplorerStatus = await _nbXplorerService.GetTransactionAsync(uint256.Parse(withdrawalRequest.TxId)); + return (ulong)(nbxplorerStatus?.Confirmations ?? 0); + } + public override async Task GetWithdrawalsRequestStatus(GetWithdrawalsRequestStatusRequest request, ServerCallContext context) { var withdrawalRequests = await _walletWithdrawalRequestRepository.GetByIds(request.RequestIds.ToList()); diff --git a/src/Services/WithdrawalRequestService.cs b/src/Services/WithdrawalRequestService.cs index 70f70a168..da861f43e 100644 --- a/src/Services/WithdrawalRequestService.cs +++ b/src/Services/WithdrawalRequestService.cs @@ -269,7 +269,7 @@ private async Task CreateReplacementAsync(int originalR if (!added) { // The database lets one live replacement per request through; a concurrent one lands here. - if (await _walletWithdrawalRequestRepository.HasLiveReplacementAsync(original.Id)) + if (addError?.Contains(WalletWithdrawalRequest.LiveReplacementIndex) == true) { throw new BumpingException( $"Withdrawal request {original.Id} is already being replaced by another request.", @@ -360,22 +360,23 @@ public async Task ScheduleHotWalletWithdrawalAsync(int requestId) public async Task ReconcileReplacementChainsAsync() { - var liveRequests = await _walletWithdrawalRequestRepository.GetLiveRbfLinkedRequestsAsync(); - var chains = new Dictionary>(); + var liveIds = await _walletWithdrawalRequestRepository.GetLiveRbfLinkedRequestIdsAsync(); + var chains = new Dictionary>(); - foreach (var liveRequest in liveRequests) + foreach (var id in liveIds) { try { - if (!chains.TryGetValue(liveRequest.Id, out var chain)) + if (!chains.TryGetValue(id, out var chain)) { - chain = await _walletWithdrawalRequestRepository.GetRbfChainAsync(liveRequest.Id); - foreach (var member in chain) chains[member.Id] = chain; + chain = (await _walletWithdrawalRequestRepository.GetRbfChainAsync(id)).ToDictionary(member => member.Id); + foreach (var memberId in chain.Keys) chains[memberId] = chain; } - // The chain is the fresher read; a row that moved on in between is left to the next run. - var request = chain.FirstOrDefault(member => member.Id == liveRequest.Id); - if (request == null || !request.IsLive || request.Status == WalletWithdrawalRequestStatus.FinalizingPSBT) continue; + // The chain is the fresher read; a row that moved on in between is left to the next run. So is a + // FinalizingPSBT one: PerformWithdrawal writes that row whole when it broadcasts. + if (!chain.TryGetValue(id, out var request) || !request.IsLive + || request.Status == WalletWithdrawalRequestStatus.FinalizingPSBT) continue; if (FinalStatusFromChain(request, chain) is not var (status, reason)) continue; @@ -393,7 +394,7 @@ public async Task ReconcileReplacementChainsAsync() } catch (Exception e) { - _logger.LogError(e, "Error reconciling withdrawal request {RequestId} against its RBF chain", liveRequest.Id); + _logger.LogError(e, "Error reconciling withdrawal request {RequestId} against its RBF chain", id); } } } @@ -403,54 +404,38 @@ public async Task ReconcileReplacementChainsAsync() /// confirmed ancestor wins over a confirmed descendant: the payment happened, so the request is spent anyway. /// private static (WalletWithdrawalRequestStatus Status, string Reason)? FinalStatusFromChain( - WalletWithdrawalRequest request, List chain) + WalletWithdrawalRequest request, Dictionary chain) { - var byId = chain.ToDictionary(member => member.Id); - - var visited = new HashSet { request.Id }; - var ancestorId = request.BumpingWalletWithdrawalRequestId; - while (ancestorId is { } id && visited.Add(id) && byId.TryGetValue(id, out var ancestor)) + if (Ancestors(request, chain).FirstOrDefault(a => a.Status == WalletWithdrawalRequestStatus.OnChainConfirmed) is { } mined) { - if (ancestor.Status == WalletWithdrawalRequestStatus.OnChainConfirmed) - { - return (WalletWithdrawalRequestStatus.Failed, - $"Withdrawal request {ancestor.Id} was mined instead (tx {ancestor.TxId})"); - } - - ancestorId = ancestor.BumpingWalletWithdrawalRequestId; + return (WalletWithdrawalRequestStatus.Failed, WalletWithdrawalRequest.MinedInsteadReason(mined.Id, mined.TxId)); } - foreach (var confirmed in chain.Where(member => member.Status == WalletWithdrawalRequestStatus.OnChainConfirmed)) + foreach (var confirmed in chain.Values.Where(member => member.Status == WalletWithdrawalRequestStatus.OnChainConfirmed)) { - var path = PathUpTo(confirmed, request.Id, byId); - if (path == null) continue; + var lineage = Ancestors(confirmed, chain).ToList(); + var index = lineage.FindIndex(a => a.Id == request.Id); + if (index < 0) continue; // Cancelled iff a cancellation sits on the way: a bump of a cancellation still returns the funds, while a // cancellation of a bump still means this request's destinations were never paid. - return path.Any(member => member.IsRbfCancellation) - ? (WalletWithdrawalRequestStatus.Cancelled, WalletWithdrawalRequest.RbfCancellationReason(confirmed.Id, confirmed.TxId)) - : (WalletWithdrawalRequestStatus.Bumped, WalletWithdrawalRequest.ReplacedReason(confirmed.Id, confirmed.TxId)); + var cancellation = confirmed.IsRbfCancellation || lineage.Take(index).Any(a => a.IsRbfCancellation); + return WalletWithdrawalRequest.SupersededBy(confirmed, cancellation); } return null; } - /// The requests from up to, excluding, ; null if it is not an ancestor. - private static List? PathUpTo(WalletWithdrawalRequest from, int targetId, - Dictionary byId) + /// What replaces, nearest first, following the link while it stays in the chain. + private static IEnumerable Ancestors(WalletWithdrawalRequest request, + Dictionary chain) { - var path = new List(); - var visited = new HashSet(); - var current = from; - while (current != null && visited.Add(current.Id)) + var visited = new HashSet { request.Id }; + var current = request; + while (current.BumpingWalletWithdrawalRequestId is { } id && visited.Add(id) && chain.TryGetValue(id, out current)) { - path.Add(current); - if (current.BumpingWalletWithdrawalRequestId == targetId) return path; - - current = current.BumpingWalletWithdrawalRequestId is { } id ? byId.GetValueOrDefault(id) : null; + yield return current; } - - return null; } private async Task ResolveFeeRateAsync(MempoolRecommendedFeesType feeType, decimal? customFeeRate) diff --git a/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestRepositoryTests.cs b/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestRepositoryTests.cs index 9c128f01b..15ff828cb 100644 --- a/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestRepositoryTests.cs +++ b/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestRepositoryTests.cs @@ -30,8 +30,8 @@ namespace NodeGuard.Data.Repositories; /// /// RBF replacements point at the request they replace through BumpingWalletWithdrawalRequestId, and a request's status /// only describes its own transaction. These reads answer the questions built on that link: every request a reference -/// id maps to (the whole chain, each reporting its own status), whether a request already has a live replacement, and -/// which rows the monitor's reconciliation has to look at. +/// id maps to (the whole chain, each reporting its own status), the chain a request belongs to, and which rows the +/// monitor's reconciliation has to look at. /// public class WalletWithdrawalRequestRepositoryTests { @@ -147,35 +147,6 @@ public async Task GetByIds_LoadsTheReplacements() result.Single().Replacements.Select(r => r.Id).Should().Equal(new[] { 2 }); } - [Theory] - [InlineData(WalletWithdrawalRequestStatus.Pending, true)] - [InlineData(WalletWithdrawalRequestStatus.PSBTSignaturesPending, true)] - [InlineData(WalletWithdrawalRequestStatus.FinalizingPSBT, true)] - [InlineData(WalletWithdrawalRequestStatus.OnChainConfirmationPending, true)] - [InlineData(WalletWithdrawalRequestStatus.OnChainConfirmed, false)] - [InlineData(WalletWithdrawalRequestStatus.Failed, false)] - [InlineData(WalletWithdrawalRequestStatus.Cancelled, false)] - [InlineData(WalletWithdrawalRequestStatus.Rejected, false)] - [InlineData(WalletWithdrawalRequestStatus.Bumped, false)] - public async Task HasLiveReplacementAsync_CountsOnlyLiveStatuses(WalletWithdrawalRequestStatus replacementStatus, bool expected) - { - var repository = await SeedAsync( - Request(1, WalletWithdrawalRequestStatus.OnChainConfirmationPending), - Request(2, replacementStatus, replaces: 1)); - - (await repository.HasLiveReplacementAsync(1)).Should().Be(expected); - } - - [Fact] - public async Task HasLiveReplacementAsync_UnrelatedLiveRequest_DoesNotCount() - { - var repository = await SeedAsync( - Request(1, WalletWithdrawalRequestStatus.OnChainConfirmationPending), - Request(2, WalletWithdrawalRequestStatus.OnChainConfirmationPending)); - - (await repository.HasLiveReplacementAsync(1)).Should().BeFalse(); - } - [Fact] public async Task GetRbfChainAsync_ReturnsTheWholeChainFromAnyMember() { @@ -205,7 +176,7 @@ public async Task GetRbfChainAsync_UnlinkedRequest_ReturnsItself() } [Fact] - public async Task GetLiveRbfLinkedRequestsAsync_ReturnsLiveRowsWithALinkOrReplacements_NotFinalizing() + public async Task GetLiveRbfLinkedRequestIdsAsync_ReturnsTheLiveRowsWithALinkOrReplacements() { var repository = await SeedAsync( Request(1, WalletWithdrawalRequestStatus.OnChainConfirmationPending), @@ -215,9 +186,9 @@ public async Task GetLiveRbfLinkedRequestsAsync_ReturnsLiveRowsWithALinkOrReplac Request(5, WalletWithdrawalRequestStatus.OnChainConfirmed), Request(6, WalletWithdrawalRequestStatus.PSBTSignaturesPending, replaces: 5)); - var rows = await repository.GetLiveRbfLinkedRequestsAsync(); + var ids = await repository.GetLiveRbfLinkedRequestIdsAsync(); - rows.Select(r => r.Id).Should().BeEquivalentTo(new[] { 1, 6 }, - "1 is replaced, 6 replaces; 2 is being broadcast, 3 is unlinked, 4 and 5 are not live"); + ids.Should().BeEquivalentTo(new[] { 1, 2, 6 }, + "1 is replaced, 2 and 6 replace; 3 is unlinked, 4 and 5 are not live"); } } diff --git a/test/NodeGuard.Tests/Jobs/MonitorWithdrawalsJobTests.cs b/test/NodeGuard.Tests/Jobs/MonitorWithdrawalsJobTests.cs index da44c062b..25c0855ba 100644 --- a/test/NodeGuard.Tests/Jobs/MonitorWithdrawalsJobTests.cs +++ b/test/NodeGuard.Tests/Jobs/MonitorWithdrawalsJobTests.cs @@ -61,22 +61,22 @@ private Task ExecuteAsync(params WalletWithdrawalRequest[] pending) return job.Execute(new Mock().Object); } - /// A broadcast request waiting for confirmation whose transaction has . - private WalletWithdrawalRequest Pending(int id, int confirmations, int? replaces = null) + /// A broadcast request waiting for confirmation; NBXplorer answers for it. + private WalletWithdrawalRequest Pending(int id, Func transaction) { - var request = PendingWithoutTransaction(id, replaces); - _nbXplorer.Setup(x => x.GetTransactionAsync(uint256.Parse(request.TxId!), It.IsAny())) - .ReturnsAsync(new TransactionResult { Confirmations = confirmations }); + var request = new WalletWithdrawalRequest + { + Id = id, + Status = WalletWithdrawalRequestStatus.OnChainConfirmationPending, + TxId = new uint256((ulong)id).ToString(), + }; + _nbXplorer.Setup(x => x.GetTransactionAsync(uint256.Parse(request.TxId), It.IsAny())) + .ReturnsAsync(transaction); return request; } - private static WalletWithdrawalRequest PendingWithoutTransaction(int id, int? replaces = null) => new() - { - Id = id, - Status = WalletWithdrawalRequestStatus.OnChainConfirmationPending, - TxId = new uint256((ulong)id).ToString(), - BumpingWalletWithdrawalRequestId = replaces, - }; + private WalletWithdrawalRequest Pending(int id, int confirmations) + => Pending(id, () => new TransactionResult { Confirmations = confirmations }); [Fact] public async Task Execute_WithdrawalAtTheSettlementDepth_IsSettled() @@ -92,7 +92,8 @@ public async Task Execute_WithdrawalAtTheSettlementDepth_IsSettled() [Fact] public async Task Execute_ReplacementAtTheSettlementDepth_IsSettled() { - var replacement = Pending(2, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS, replaces: 1); + var replacement = Pending(2, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS); + replacement.BumpingWalletWithdrawalRequestId = 1; await ExecuteAsync(replacement); @@ -105,7 +106,7 @@ public async Task Execute_ReplacementAtTheSettlementDepth_IsSettled() [InlineData(1)] public async Task Execute_WithdrawalBelowTheSettlementDepth_IsLeftPending(int confirmations) { - var request = Pending(1, confirmations, replaces: 1); + var request = Pending(1, confirmations); await ExecuteAsync(request); @@ -116,9 +117,7 @@ public async Task Execute_WithdrawalBelowTheSettlementDepth_IsLeftPending(int co [Fact] public async Task Execute_TransactionUnknownToNbxplorer_LeavesTheRequestPendingAndContinues() { - var unknown = PendingWithoutTransaction(1); - _nbXplorer.Setup(x => x.GetTransactionAsync(uint256.Parse(unknown.TxId!), It.IsAny())) - .ReturnsAsync((TransactionResult?)null); + var unknown = Pending(1, () => null); var settling = Pending(2, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS); await ExecuteAsync(unknown, settling); @@ -130,9 +129,7 @@ public async Task Execute_TransactionUnknownToNbxplorer_LeavesTheRequestPendingA [Fact] public async Task Execute_NbxplorerFailureOnOneRequest_DoesNotAbortTheBatch() { - var failing = PendingWithoutTransaction(1); - _nbXplorer.Setup(x => x.GetTransactionAsync(uint256.Parse(failing.TxId!), It.IsAny())) - .ThrowsAsync(new HttpRequestException("nbxplorer down")); + var failing = Pending(1, () => throw new HttpRequestException("nbxplorer down")); var settling = Pending(2, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS); var act = () => ExecuteAsync(failing, settling); @@ -145,7 +142,7 @@ public async Task Execute_NbxplorerFailureOnOneRequest_DoesNotAbortTheBatch() [Fact] public async Task Execute_RequestWithoutTransaction_IsSkipped() { - var request = PendingWithoutTransaction(1); + var request = Pending(1, confirmations: 0); request.TxId = null; await ExecuteAsync(request); @@ -158,7 +155,8 @@ public async Task Execute_RequestWithoutTransaction_IsSkipped() public async Task Execute_ReconcilesTheRbfChainsAfterSettling() { var settling = Pending(1, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS); - var inFlight = Pending(2, confirmations: 0, replaces: 1); + var inFlight = Pending(2, confirmations: 0); + inFlight.BumpingWalletWithdrawalRequestId = 1; await ExecuteAsync(settling, inFlight); diff --git a/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs b/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs index 29e2e73ee..8531fb242 100644 --- a/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs +++ b/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs @@ -1023,8 +1023,8 @@ private static WalletWithdrawalRequest ReplacedRequest(WalletWithdrawalRequestSt private NodeGuardService StatusService(Mock walletWithdrawalRequestRepository, int confirmations) { var nbxplorerService = new Mock(); - nbxplorerService.Setup(x => x.GetTransactionAsync(It.IsAny(), It.IsAny())) - .ReturnsAsync(new NBXplorer.Models.TransactionResult { Confirmations = confirmations }); + nbxplorerService.Setup(x => x.GetTransactionAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(new TransactionResult { Confirmations = confirmations }); return CreateNodeGuardService( walletWithdrawalRequestRepository: walletWithdrawalRequestRepository.Object, @@ -1050,7 +1050,8 @@ public async Task GetWithdrawalsRequestStatus_OriginalWithABroadcastReplacement_ status.Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalBumped, "the replacement's transaction competes with its own in the mempool"); status.ReplacedByRequestId.Should().Be(11); - status.RejectOrCancelReason.Should().BeEmpty(); + status.RejectOrCancelReason.Should().Be($"Replaced by request 11 (tx {ReplacementTxId})", + "the same text it will be stored with once the replacement settles"); } [Fact] diff --git a/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs b/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs index a954e100a..0823fa664 100644 --- a/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs +++ b/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs @@ -478,7 +478,7 @@ public async Task ScheduleHotWalletWithdrawalAsync_WrongStatus_IsRefused(WalletW public async Task CreateBumpRequestAsync_OriginalWithALiveReplacement_IsRefused(WalletWithdrawalRequestStatus replacementStatus) { var original = SetupOriginal(HotWallet()); - original.Replacements.Add(Replacement(12, replacementStatus)); + original.Replacements.Add(Row(12, replacementStatus, replaces: OriginalId)); await AssertRefusedAsync(BumpingErrorReason.InvalidState, MempoolRecommendedFeesType.CustomFee, 10m); } @@ -487,7 +487,7 @@ public async Task CreateBumpRequestAsync_OriginalWithALiveReplacement_IsRefused( public async Task CreateCancelRequestAsync_OriginalWithALiveReplacement_IsRefused() { var original = SetupOriginal(HotWallet()); - original.Replacements.Add(Replacement(12, WalletWithdrawalRequestStatus.OnChainConfirmationPending)); + original.Replacements.Add(Row(12, WalletWithdrawalRequestStatus.OnChainConfirmationPending, replaces: OriginalId)); await AssertRefusedAsync(BumpingErrorReason.InvalidState, MempoolRecommendedFeesType.CustomFee, 10m, cancellation: true); } @@ -499,7 +499,7 @@ public async Task CreateCancelRequestAsync_OriginalWithALiveReplacement_IsRefuse public async Task CreateBumpRequestAsync_OriginalWithOnlyAbandonedReplacements_IsAllowed(WalletWithdrawalRequestStatus replacementStatus) { var original = SetupOriginal(HotWallet()); - original.Replacements.Add(Replacement(12, replacementStatus)); + original.Replacements.Add(Row(12, replacementStatus, replaces: OriginalId)); var bump = await CreateService().CreateBumpRequestAsync(OriginalId, MempoolRecommendedFeesType.CustomFee, 10m); @@ -512,8 +512,7 @@ public async Task CreateBumpRequestAsync_InsertLosesTheRaceToAnotherReplacement_ { SetupOriginal(HotWallet()); _requests.Setup(x => x.AddAsync(It.IsAny())) - .ReturnsAsync((false, "duplicate key value violates unique constraint")); - _requests.Setup(x => x.HasLiveReplacementAsync(OriginalId)).ReturnsAsync(true); + .ReturnsAsync((false, $"23505: duplicate key value violates unique constraint \"{WalletWithdrawalRequest.LiveReplacementIndex}\"")); var act = () => CreateService().CreateBumpRequestAsync(OriginalId, MempoolRecommendedFeesType.CustomFee, 10m); @@ -527,7 +526,6 @@ public async Task CreateBumpRequestAsync_InsertFailsForAnotherReason_IsAPersiste { SetupOriginal(HotWallet()); _requests.Setup(x => x.AddAsync(It.IsAny())).ReturnsAsync((false, "db down")); - _requests.Setup(x => x.HasLiveReplacementAsync(OriginalId)).ReturnsAsync(false); var act = () => CreateService().CreateBumpRequestAsync(OriginalId, MempoolRecommendedFeesType.CustomFee, 10m); @@ -689,7 +687,7 @@ public async Task ReconcileReplacementChainsAsync_AbandonedSiblingReplacement_Is public async Task ReconcileReplacementChainsAsync_OneChainThrowing_DoesNotStopTheOthers() { var broken = Row(10, WalletWithdrawalRequestStatus.OnChainConfirmationPending, replaces: 9); - Live(broken); + Live(broken.Id); _requests.Setup(x => x.GetRbfChainAsync(10)).ThrowsAsync(new InvalidOperationException("db down")); var original = Row(20, WalletWithdrawalRequestStatus.OnChainConfirmationPending); var bump = Row(21, WalletWithdrawalRequestStatus.OnChainConfirmed, replaces: 20); @@ -716,17 +714,9 @@ public async Task ReconcileReplacementChainsAsync_UpdateFails_IsOnlyLogged() // ---- fixtures --------------------------------------------------------------------------------------------- - private readonly List _liveLinked = new(); + private readonly List _liveIds = new(); - private static WalletWithdrawalRequest Replacement(int id, WalletWithdrawalRequestStatus status) => new() - { - Id = id, - Status = status, - Description = "replacement", - BumpingWalletWithdrawalRequestId = OriginalId, - }; - - /// A broadcast-or-later request of an RBF chain; its txid is derived from its id. + /// A request of an RBF chain; its txid is derived from its id. private static WalletWithdrawalRequest Row(int id, WalletWithdrawalRequestStatus status, int? replaces = null, bool cancellation = false) => new() { @@ -739,8 +729,8 @@ private static WalletWithdrawalRequest Row(int id, WalletWithdrawalRequestStatus }; /// - /// Wires a chain the way the repository returns it: every member resolves to the whole chain, and the live ones - /// are what the reconciliation iterates (FinalizingPSBT included, to exercise the service's own guard). + /// Wires a chain the way the repository returns it: every member resolves to the whole chain, and the ids of + /// the live ones are what the reconciliation iterates. /// private void Chain(params WalletWithdrawalRequest[] members) { @@ -750,13 +740,13 @@ private void Chain(params WalletWithdrawalRequest[] members) _requests.Setup(x => x.GetRbfChainAsync(member.Id)).ReturnsAsync(chain); } - Live(members.Where(m => m.IsLive).ToArray()); + Live(members.Where(m => m.IsLive).Select(m => m.Id).ToArray()); } - private void Live(params WalletWithdrawalRequest[] rows) + private void Live(params int[] ids) { - _liveLinked.AddRange(rows); - _requests.Setup(x => x.GetLiveRbfLinkedRequestsAsync()).ReturnsAsync(_liveLinked.ToList()); + _liveIds.AddRange(ids); + _requests.Setup(x => x.GetLiveRbfLinkedRequestIdsAsync()).ReturnsAsync(_liveIds.ToList()); } private async Task AssertRefusedAsync(BumpingErrorReason reason, MempoolRecommendedFeesType feeType, decimal? customFeeRate,