From 54406cef5a416af1cd45fb87f81e567e6c7edbd5 Mon Sep 17 00:00:00 2001 From: Marcos Date: Mon, 23 Nov 2026 16:15:42 +0100 Subject: [PATCH] fix: a changeless withdrawal over gRPC records the amount of its UTXOs, not the declared one --- src/Proto/nodeguard.proto | 6 +- src/Rpc/NodeGuardService.cs | 41 ++++- src/Services/BitcoinService.cs | 9 + src/Services/WithdrawalRequestService.cs | 9 +- .../E2E/WalletEventsE2ETests.cs | 45 +++++ .../Rpc/NodeGuardServiceTests.cs | 159 ++++++++++++++++++ .../Services/BitcoinServiceTests.cs | 91 +++++++++- .../Services/WithdrawalRequestServiceTests.cs | 15 ++ 8 files changed, 368 insertions(+), 7 deletions(-) diff --git a/src/Proto/nodeguard.proto b/src/Proto/nodeguard.proto index 093524f6..65d55a34 100644 --- a/src/Proto/nodeguard.proto +++ b/src/Proto/nodeguard.proto @@ -250,9 +250,11 @@ message RequestWithdrawalRequest { string description = 4; // in JSON format string request_metadata = 5; - // Whether the withdrawal should be performed in a changeless way + // Whether the withdrawal should be performed in a changeless way: utxos_outpoints are sent in full, minus the fee, + // to the single destination, whose amount_sats is ignored and recorded as the total of those UTXOs bool changeless = 6; - // Outpoints for the UTXOs to use for the withdrawal + // Outpoints for the UTXOs to use for the withdrawal. Required when changeless, and every one of them has to be a + // confirmed UTXO of the wallet repeated string utxos_outpoints = 7; // MempoolRecommended fee rate FEES_TYPE mempool_fee_rate = 8; diff --git a/src/Rpc/NodeGuardService.cs b/src/Rpc/NodeGuardService.cs index e141b7fa..ee6657ab 100644 --- a/src/Rpc/NodeGuardService.cs +++ b/src/Rpc/NodeGuardService.cs @@ -260,7 +260,8 @@ private void ValidateWithdrawalDestinations(IList destinations, boo foreach (var destination in destinations) { - if (destination.AmountSats <= 0) + // A changeless withdrawal takes its amount from its UTXOs + if (!isChangeless && destination.AmountSats <= 0) { throw new RpcException(new Status(StatusCode.InvalidArgument, "Amount must be greater than 0")); } @@ -321,11 +322,23 @@ public override async Task RequestWithdrawal(RequestW if (request.Changeless) { + if (request.UtxosOutpoints.Count == 0) + { + throw new RpcException(new Status(StatusCode.InvalidArgument, "Changeless withdrawal requires utxos")); + } + foreach (var outpoint in request.UtxosOutpoints) { - outpoints.Add(OutPoint.Parse(outpoint)); + if (!OutPoint.TryParse(outpoint, out var parsedOutpoint)) + { + throw new RpcException(new Status(StatusCode.InvalidArgument, $"Invalid utxo outpoint {outpoint}")); + } + + outpoints.Add(parsedOutpoint!); } + outpoints = outpoints.Distinct().ToList(); + // Search the utxos and lock them var derivationStrategyBase = wallet.GetDerivationStrategy(); @@ -334,15 +347,37 @@ public override async Task RequestWithdrawal(RequestW utxos = await _coinSelectionService.GetUTXOsByOutpointAsync(derivationStrategyBase, outpoints); + // Every outpoint has to be spendable: the withdrawal sends exactly these UTXOs + if (utxos.Count != outpoints.Count) + { + throw new RpcException(new Status(StatusCode.InvalidArgument, + "Some utxos are not confirmed UTXOs of the wallet")); + } } + // A changeless withdrawal sends its UTXOs in full, so that total is its amount whatever the caller + // declared: the amount is what the audit, the wallet events and the withdrawal interceptor are shown + var changelessSats = utxos.Sum(u => ((Money)u.Value).Satoshi); + // Create destination objects for the withdrawal request var withdrawalDestinations = request.Destinations.Select(d => new WalletWithdrawalRequestDestination() { Address = d.Address, - Amount = new Money(d.AmountSats, MoneyUnit.Satoshi).ToDecimal(MoneyUnit.BTC), + Amount = new Money(request.Changeless ? changelessSats : d.AmountSats, MoneyUnit.Satoshi) + .ToDecimal(MoneyUnit.BTC), }).ToList(); + auditDetails = new + { + request.WalletId, + Destinations = withdrawalDestinations.Select(d => new + { + d.Address, + AmountSats = new Money(d.Amount, MoneyUnit.BTC).Satoshi + }), + request.ReferenceId + }; + withdrawalRequest = new WalletWithdrawalRequest() { WalletId = request.WalletId, diff --git a/src/Services/BitcoinService.cs b/src/Services/BitcoinService.cs index c0f44677..1f7f7574 100644 --- a/src/Services/BitcoinService.cs +++ b/src/Services/BitcoinService.cs @@ -288,6 +288,15 @@ await _coinSelectionService.GetTxInputCoins(availableUTXOs, walletWithdrawalRequ { throw new ArgumentException("Destination address is null or empty."); } + + // The request's amount is what approvers, the audit and the withdrawal interceptor are shown, + // so it has to be what the inputs send + if (walletWithdrawalRequest.SatsAmount != changelessAmount) + { + throw new InvalidOperationException( + $"Changeless withdrawal request {walletWithdrawalRequest.Id} is for {walletWithdrawalRequest.SatsAmount} sats but its UTXOs hold {changelessAmount} sats."); + } + var destinationAddress = BitcoinAddress.Create(destination.Address, nbXplorerNetwork); builder.Send(destinationAddress, changelessAmount); builder.SubtractFees(); diff --git a/src/Services/WithdrawalRequestService.cs b/src/Services/WithdrawalRequestService.cs index 3ae44535..15b5e685 100644 --- a/src/Services/WithdrawalRequestService.cs +++ b/src/Services/WithdrawalRequestService.cs @@ -232,8 +232,15 @@ private async Task CreateReplacementAsync(int originalR } else { + // A changeless request sends its UTXOs in full. Older requests created over gRPC kept the amount the + // caller declared instead, so the replacement takes the UTXO total rather than copying it. + var lockedAmount = Money.Satoshis(lockedUtxos.Sum(u => u.SatsAmount)).ToDecimal(MoneyUnit.BTC); replacementDestinations = destinations - .Select(d => new WalletWithdrawalRequestDestination { Address = d.Address, Amount = d.Amount }) + .Select(d => new WalletWithdrawalRequestDestination + { + Address = d.Address, + Amount = original.Changeless ? lockedAmount : d.Amount + }) .ToList(); } diff --git a/test/NodeGuard.Tests/E2E/WalletEventsE2ETests.cs b/test/NodeGuard.Tests/E2E/WalletEventsE2ETests.cs index 93964448..bd2ddc50 100644 --- a/test/NodeGuard.Tests/E2E/WalletEventsE2ETests.cs +++ b/test/NodeGuard.Tests/E2E/WalletEventsE2ETests.cs @@ -201,6 +201,51 @@ public async Task Interceptor_BlocksAWithdrawal_ThatIsRejectedAndNeverBroadcast( "a blocked withdrawal is never signed"); } + /// + /// A changeless withdrawal sends its UTXOs in full, so that is the amount the integrator decides on, whatever + /// amount the request declared + /// + [E2EFact] + public async Task Interceptor_IsAskedAboutWhatAChangelessWithdrawalSends_NotTheDeclaredAmount() + { + const long declaredSats = 1_000; + + var client = CreateClient(out var headers); + var rpc = CreateBitcoindRpc(); + var walletId = await EnsureHotWalletReadyAsync(client, headers); + var utxo = (await client.GetAvailableUtxosAsync(new GetAvailableUtxosRequest + { + WalletId = walletId, + Strategy = COIN_SELECTION_STRATEGY.BiggestFirst, + Limit = 1, + Amount = 1 + }, headers)).Confirmed.OrderByDescending(u => u.Amount).First(); + utxo.Amount.Should().BeGreaterThan(declaredSats); + await using var integrator = await WalletEventStream.OpenAsync(client, headers, walletId, _output, interceptWithdrawals: true); + + var destination = await rpc.GetNewAddressAsync(); + var withdrawal = await client.RequestWithdrawalAsync(new RequestWithdrawalRequest + { + WalletId = walletId, + Description = "E2E interceptor changeless", + Changeless = true, + UtxosOutpoints = { utxo.Outpoint }, + Destinations = { new Destination { Address = destination.ToString(), AmountSats = declaredSats } }, + MempoolFeeRate = FEES_TYPE.CustomFee, + CustomFeeRate = OriginalFeeRateSatPerVb, + }, headers); + + var asked = await integrator.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalDecisionRequested); + asked.Withdrawal.AmountSats.Should().Be(utxo.Amount); + asked.Withdrawal.Destinations.Should().ContainSingle(d => + d.Address == destination.ToString() && d.AmountSats == utxo.Amount); + + // Blocked, so the UTXO stays in the hot wallet for the other tests + await integrator.DecideAsync(asked, allow: false, reason: "over the limit"); + await integrator.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalRejected); + await AssertNeverBroadcastAsync(client, headers, rpc, withdrawal); + } + [E2EFact] public async Task Interceptor_ThatDoesNotAnswer_BlocksTheWithdrawalAtTheDeadline() { diff --git a/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs b/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs index b1a6e2f8..066e7ec7 100644 --- a/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs +++ b/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs @@ -1016,6 +1016,165 @@ public async Task RequestWithdrawal_Success_AuditsTheCreatedRequest() AuditObjectType.WalletWithdrawalRequest, resp.RequestId.ToString(), It.IsAny()), Times.Once); } + [Fact] + public async Task RequestWithdrawal_Changeless_StoresTheAmountOfItsUtxos_NotTheDeclaredOne() + { + //Arrange + var wallet = InitMockRequestWithdrawal(out var walletRepository, + out var nbxplorerService, + out _, + out _, + out _, + out _, + out var utxoList, + out var bitcoinService, + out var walletWithdrawalRequestRepository, out var mockScheduler); + + wallet.IsHotWallet = false; + utxoList[0].Value = Money.Coins(20); + + var coinSelectionService = new Mock(); + coinSelectionService + .Setup(x => x.GetUTXOsByOutpointAsync(It.IsAny(), It.IsAny>())) + .ReturnsAsync(utxoList); + + WalletWithdrawalRequest? saved = null; + walletWithdrawalRequestRepository.Setup(x => x.AddAsync(It.IsAny())) + .Callback(x => saved = x) + .ReturnsAsync((true, null)); + + object? audited = null; + var auditService = new Mock(); + auditService.Setup(x => x.LogAsync(AuditActionType.Create, AuditEventType.Success, + AuditObjectType.WalletWithdrawalRequest, It.IsAny(), It.IsAny())) + .Callback((_, _, _, _, details) => audited = details); + + var mockNodeGuardService = CreateNodeGuardService( + walletRepository: walletRepository.Object, + walletWithdrawalRequestRepository: walletWithdrawalRequestRepository.Object, + bitcoinService: bitcoinService.Object, + nbXplorerService: nbxplorerService.Object, + schedulerFactory: mockScheduler, + coinSelectionService: coinSelectionService.Object, + auditService: auditService.Object); + + var requestWithdrawalRequest = new RequestWithdrawalRequest + { + WalletId = wallet.Id, + Description = "Request Withdrawal Changeless Test", + Changeless = true, + UtxosOutpoints = { utxoList[0].Outpoint.ToString() }, + Destinations = { new Destination + { + Address = "bcrt1q590shaxaf5u08ml8jwlzghz99dup3z9592vxal", + AmountSats = 1_000 + } + } + }; + + //Act + await mockNodeGuardService.RequestWithdrawal(requestWithdrawalRequest, TestServerCallContext.Create()); + + //Assert + saved.Should().NotBeNull(); + saved!.SatsAmount.Should().Be(Money.Coins(20).Satoshi); + System.Text.Json.JsonSerializer.Serialize(audited).Should().Contain("\"AmountSats\":2000000000"); + } + + [Fact] + public async Task RequestWithdrawal_Changeless_WithoutUtxos_IsRefused() + { + //Arrange + var wallet = InitMockRequestWithdrawal(out var walletRepository, + out var nbxplorerService, + out _, + out _, + out _, + out _, + out _, + out var bitcoinService, + out var walletWithdrawalRequestRepository, out var mockScheduler); + + var mockNodeGuardService = CreateNodeGuardService( + walletRepository: walletRepository.Object, + walletWithdrawalRequestRepository: walletWithdrawalRequestRepository.Object, + bitcoinService: bitcoinService.Object, + nbXplorerService: nbxplorerService.Object, + schedulerFactory: mockScheduler); + + var requestWithdrawalRequest = new RequestWithdrawalRequest + { + WalletId = wallet.Id, + Description = "Request Withdrawal Changeless Test", + Changeless = true, + Destinations = { new Destination + { + Address = "bcrt1q590shaxaf5u08ml8jwlzghz99dup3z9592vxal", + AmountSats = 1_000 + } + } + }; + + //Act + var act = () => mockNodeGuardService.RequestWithdrawal(requestWithdrawalRequest, TestServerCallContext.Create()); + + //Assert + (await act.Should().ThrowAsync()).Which.StatusCode.Should().Be(StatusCode.InvalidArgument); + walletWithdrawalRequestRepository.Verify(x => x.AddAsync(It.IsAny()), Times.Never); + } + + [Fact] + public async Task RequestWithdrawal_Changeless_WithAUtxoTheWalletDoesNotHave_IsRefused() + { + //Arrange + var wallet = InitMockRequestWithdrawal(out var walletRepository, + out var nbxplorerService, + out _, + out _, + out _, + out _, + out var utxoList, + out var bitcoinService, + out var walletWithdrawalRequestRepository, out var mockScheduler); + + utxoList[0].Value = Money.Coins(20); + + // Only the first of the two outpoints is found in the wallet + var coinSelectionService = new Mock(); + coinSelectionService + .Setup(x => x.GetUTXOsByOutpointAsync(It.IsAny(), It.IsAny>())) + .ReturnsAsync(utxoList); + + var mockNodeGuardService = CreateNodeGuardService( + walletRepository: walletRepository.Object, + walletWithdrawalRequestRepository: walletWithdrawalRequestRepository.Object, + bitcoinService: bitcoinService.Object, + nbXplorerService: nbxplorerService.Object, + schedulerFactory: mockScheduler, + coinSelectionService: coinSelectionService.Object); + + var requestWithdrawalRequest = new RequestWithdrawalRequest + { + WalletId = wallet.Id, + Description = "Request Withdrawal Changeless Test", + Changeless = true, + UtxosOutpoints = { utxoList[0].Outpoint.ToString(), new OutPoint(uint256.One, 7).ToString() }, + Destinations = { new Destination + { + Address = "bcrt1q590shaxaf5u08ml8jwlzghz99dup3z9592vxal", + AmountSats = 1_000 + } + } + }; + + //Act + var act = () => mockNodeGuardService.RequestWithdrawal(requestWithdrawalRequest, TestServerCallContext.Create()); + + //Assert + (await act.Should().ThrowAsync()).Which.StatusCode.Should().Be(StatusCode.InvalidArgument); + walletWithdrawalRequestRepository.Verify(x => x.AddAsync(It.IsAny()), Times.Never); + } + [Fact] public async Task RequestWithdrawal_RefreshReturnsNull_CancelsAndAuditsTheSavedRequest() { diff --git a/test/NodeGuard.Tests/Services/BitcoinServiceTests.cs b/test/NodeGuard.Tests/Services/BitcoinServiceTests.cs index 7fe7d532..8cd16f3d 100644 --- a/test/NodeGuard.Tests/Services/BitcoinServiceTests.cs +++ b/test/NodeGuard.Tests/Services/BitcoinServiceTests.cs @@ -677,7 +677,7 @@ async Task GenerateTemplatePSBT_Changeless_SingleSigSucceeds() new WalletWithdrawalRequestDestination { Address = "bcrt1q8k3av6q5yp83rn332lx8a90k6kukhg28hs5qw7krdq95t629hgsqk6ztmf", - Amount = 0.09m + Amount = 0.1m } }, Changeless = true, @@ -738,6 +738,95 @@ async Task GenerateTemplatePSBT_Changeless_SingleSigSucceeds() result.Should().BeEquivalentTo(psbt); } + [Fact] + async Task GenerateTemplatePSBT_Changeless_AmountDifferentFromItsUtxos_ShouldFail() + { + // Arrange + var wallet = CreateWallet.SingleSig(_internalWallet); + var utxos = new List() + { + new UTXO() + { + Value = new Money((long)10000000), + ScriptPubKey = (wallet.GetDerivationStrategy() as StandardDerivationStrategyBase)!.GetDerivation(KeyPath.Parse("0/0")).ScriptPubKey, + KeyPath = KeyPath.Parse("0/0"), + Index = 1, + TransactionHash = 12345678901234567890, + Outpoint = new OutPoint(12345678901234567890, 1) + } + }; + var withdrawalRequest = new WalletWithdrawalRequest() + { + Id = 1, + Status = WalletWithdrawalRequestStatus.Pending, + Wallet = wallet, + WalletWithdrawalRequestPSBTs = new List(), + WalletWithdrawalRequestDestinations = new List + { + new WalletWithdrawalRequestDestination + { + Address = "bcrt1q8k3av6q5yp83rn332lx8a90k6kukhg28hs5qw7krdq95t629hgsqk6ztmf", + Amount = 0.09m + } + }, + Changeless = true, + }; + + var walletWithdrawalRequestRepository = new Mock(); + var walletWithdrawalRequestPsbtRepository = new Mock(); + var fmutxoRepository = new Mock(); + var utxoTagRepository = new Mock(); + var nbXplorerService = new Mock(); + var mapper = new Mock(); + walletWithdrawalRequestRepository + .Setup((w) => w.GetById(It.IsAny())) + .ReturnsAsync(withdrawalRequest); + walletWithdrawalRequestRepository + .Setup((w) => w.AddUTXOs(It.IsAny(), It.IsAny>())) + .ReturnsAsync((true, null)); + walletWithdrawalRequestPsbtRepository + .Setup((w) => w.AddAsync(It.IsAny())) + .ReturnsAsync((true, null)); + nbXplorerService + .Setup(x => x.GetStatusAsync(default)) + .ReturnsAsync(new StatusResult() { IsFullySynched = true }); + nbXplorerService + .Setup(x => x.GetUnusedAsync(It.IsAny(), DerivationFeature.Change, 0, false, default)) + .ReturnsAsync(new KeyPathInformation() { Address = BitcoinAddress.Create("bcrt1q83ml8tve8vh672wsm83getxfzetaquq352jr6t423tdwjvdz3f3qe4r4t7", Network.RegTest) }); + utxoTagRepository + .Setup(x => x.GetByKeyValue(It.IsAny(), It.IsAny())) + .ReturnsAsync(new List()); + nbXplorerService + .Setup(x => x.GetUTXOsAsync(It.IsAny(), default)) + .ReturnsAsync(new UTXOChanges() + { + Confirmed = new UTXOChange() + { + UTXOs = utxos, + } + }); + + var fmUtxos = utxos.Select(x => new FMUTXO() { TxId = x.Outpoint.Hash.ToString(), OutputIndex = 1 }).ToList(); + fmutxoRepository + .Setup(x => x.GetLockedUTXOs(null, null)) + .ReturnsAsync(fmUtxos); + + walletWithdrawalRequestRepository + .Setup(x => x.GetUTXOs(It.IsAny())) + .ReturnsAsync((true, fmUtxos)); + + var coinSelectionService = new CoinSelectionService(_logger, mapper.Object, fmutxoRepository.Object, nbXplorerService.Object, null, walletWithdrawalRequestRepository.Object, utxoTagRepository.Object); + + var bitcoinService = new BitcoinService(_logger, mapper.Object, walletWithdrawalRequestRepository.Object, walletWithdrawalRequestPsbtRepository.Object, null, null, nbXplorerService.Object, coinSelectionService); + + // Act + var act = () => bitcoinService.GenerateTemplatePSBT(withdrawalRequest); + + // Assert + await act.Should().ThrowAsync().WithMessage("*9000000 sats but its UTXOs hold 10000000 sats*"); + walletWithdrawalRequestPsbtRepository.Verify(w => w.AddAsync(It.IsAny()), Times.Never); + } + /// /// Builds the unsigned template PSBT for the same transaction a set of approver PSBTs signs. Signing does /// not alter the transaction, so the template shares its txid — which is exactly what PerformWithdrawal's diff --git a/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs b/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs index 4aebf1c1..ff119c43 100644 --- a/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs +++ b/test/NodeGuard.Tests/Services/WithdrawalRequestServiceTests.cs @@ -126,6 +126,21 @@ public async Task CreateBumpRequestAsync_HotWallet_CreatesTheBumpInPsbtSignature BitcoinRequestType.WalletWithdrawal), Times.Once); } + /// + /// A changeless request sends its inputs in full. Requests created over gRPC used to keep the amount the caller + /// declared, so their bump takes the amount of the inputs instead of copying it. + /// + [Fact] + public async Task CreateBumpRequestAsync_ChangelessOriginal_TakesTheAmountOfItsInputs() + { + SetupOriginal(HotWallet(), changeless: true, inputSats: 10_000_000); + + var bump = await CreateService().CreateBumpRequestAsync(OriginalId, MempoolRecommendedFeesType.CustomFee, 10m); + + bump.WalletWithdrawalRequestDestinations.Should().ContainSingle() + .Which.Should().BeEquivalentTo(new { Address = DestinationAddress, Amount = 0.1m }); + } + /// /// The replacement stands in for the same original request, so it keeps the requested coin selection strategy /// the way it keeps RequestMetadata and ReferenceId. Nothing reads the field yet.