diff --git a/src/Jobs/MonitorWithdrawalsJob.cs b/src/Jobs/MonitorWithdrawalsJob.cs index c1ecf2d4..f3311b83 100644 --- a/src/Jobs/MonitorWithdrawalsJob.cs +++ b/src/Jobs/MonitorWithdrawalsJob.cs @@ -50,6 +50,8 @@ public async Task Execute(IJobExecutionContext context) _logger.LogInformation($"Job {nameof(MonitorWithdrawalsJob)} started"); var withdrawalsPending = await _walletWithdrawalRequestRepository.GetOnChainPendingWithdrawals(); + // One withdrawal that cannot be checked (evicted or unknown tx, NBXplorer hiccup) must not stop the others + // from being confirmed, so failures are logged per request and the loop carries on. foreach (var walletWithdrawalRequest in withdrawalsPending) { if (!string.IsNullOrEmpty(walletWithdrawalRequest.TxId)) @@ -57,9 +59,16 @@ public async Task Execute(IJobExecutionContext context) try { //Let's check if the minimum amount of confirmations are established - var getTxResult = await _nbXplorerService.GetTransactionAsync(uint256.Parse(walletWithdrawalRequest.TxId), default); + if (getTxResult == null) + { + _logger.LogWarning( + "NBXplorer does not know the transaction {TxId} of withdrawal request {RequestId}; it may have been evicted or replaced", + walletWithdrawalRequest.TxId, walletWithdrawalRequest.Id); + continue; + } + if (getTxResult.Confirmations >= Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS) { walletWithdrawalRequest.Status = WalletWithdrawalRequestStatus.OnChainConfirmed; @@ -82,9 +91,8 @@ public async Task Execute(IJobExecutionContext context) } catch (Exception e) { - _logger.LogError(e, "Error while monitoring TxId: {TxId}", walletWithdrawalRequest.TxId); - - throw new JobExecutionException(e, false); + _logger.LogError(e, "Error while monitoring TxId: {TxId} of withdrawal request {RequestId}", + walletWithdrawalRequest.TxId, walletWithdrawalRequest.Id); } } } diff --git a/src/Pages/Withdrawals.razor b/src/Pages/Withdrawals.razor index e7015e90..fbada670 100644 --- a/src/Pages/Withdrawals.razor +++ b/src/Pages/Withdrawals.razor @@ -1362,10 +1362,8 @@ var job = SimpleJob.Create(map, _selectedRequest.Id.ToString()); await scheduler.ScheduleJob(job.Job, job.Trigger); - if (_selectedRequest != null) - { - WalletWithdrawalRequestRepository.Update(_selectedRequest); - } + // No write after scheduling: the job may already have moved the request to FinalizingPSBT or broadcast + // it, and persisting this copy (loaded before scheduling) would revert its status and wipe its TxId. await LogWithdrawalAuditAsync(AuditActionType.Approve, AuditEventType.Success, _selectedRequest, "Withdrawal job scheduled."); } catch (Exception ex) diff --git a/src/Shared/TransferFundsModal.razor b/src/Shared/TransferFundsModal.razor index 23eeb2c7..315733eb 100644 --- a/src/Shared/TransferFundsModal.razor +++ b/src/Shared/TransferFundsModal.razor @@ -642,11 +642,9 @@ _amountToTransfer; var job = SimpleJob.Create(map, withdrawalRequest.Id.ToString()); await scheduler.ScheduleJob(job.Job, job.Trigger); - if (withdrawalRequest != null) - { - WalletWithdrawalRequestRepository.Update(withdrawalRequest); - result = true; - } + // No write after scheduling: the job may already have moved the request to FinalizingPSBT or broadcast + // it, and persisting this copy (loaded before scheduling) would revert its status and wipe its TxId. + result = true; } catch (Exception e) { diff --git a/test/NodeGuard.Tests/Jobs/MonitorWithdrawalsJobTests.cs b/test/NodeGuard.Tests/Jobs/MonitorWithdrawalsJobTests.cs new file mode 100644 index 00000000..0d1e3730 --- /dev/null +++ b/test/NodeGuard.Tests/Jobs/MonitorWithdrawalsJobTests.cs @@ -0,0 +1,91 @@ +/* + * 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.Services; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using Quartz; + +namespace NodeGuard.Jobs; + +public class MonitorWithdrawalsJobTests +{ + private static readonly long ConfirmedDepth = Math.Max(6, Constants.TRANSACTION_CONFIRMATION_MINIMUM_BLOCKS); + + private readonly IWalletWithdrawalRequestRepository _repository = Substitute.For(); + private readonly INBXplorerService _nbXplorerService = Substitute.For(); + private readonly MonitorWithdrawalsJob _job; + + public MonitorWithdrawalsJobTests() + { + _repository.Update(Arg.Any()).Returns((true, null)); + _job = new MonitorWithdrawalsJob(NullLogger.Instance, _repository, _nbXplorerService); + } + + private static WalletWithdrawalRequest PendingWithdrawal(int id) => new() + { + Id = id, + WalletId = 1, + Status = WalletWithdrawalRequestStatus.OnChainConfirmationPending, + TxId = RandomUtils.GetUInt256().ToString() + }; + + [Fact] + public async Task Execute_UnknownTransaction_StillConfirmsTheOtherWithdrawals() + { + var evicted = PendingWithdrawal(1); + var confirmed = PendingWithdrawal(2); + _repository.GetOnChainPendingWithdrawals().Returns(new List { evicted, confirmed }); + _nbXplorerService.GetTransactionAsync(uint256.Parse(evicted.TxId!), Arg.Any()) + .Returns((TransactionResult?)null); + _nbXplorerService.GetTransactionAsync(uint256.Parse(confirmed.TxId!), Arg.Any()) + .Returns(new TransactionResult { Confirmations = ConfirmedDepth }); + + await _job.Execute(Substitute.For()); + + evicted.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending); + confirmed.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed); + _repository.Received(1).Update(Arg.Is(r => r.Id == confirmed.Id)); + _repository.DidNotReceive().Update(Arg.Is(r => r.Id == evicted.Id)); + } + + [Fact] + public async Task Execute_NBXplorerError_StillConfirmsTheOtherWithdrawals() + { + var failing = PendingWithdrawal(1); + var confirmed = PendingWithdrawal(2); + _repository.GetOnChainPendingWithdrawals().Returns(new List { failing, confirmed }); + _nbXplorerService.GetTransactionAsync(uint256.Parse(failing.TxId!), Arg.Any()) + .ThrowsAsync(new HttpRequestException("nbxplorer down")); + _nbXplorerService.GetTransactionAsync(uint256.Parse(confirmed.TxId!), Arg.Any()) + .Returns(new TransactionResult { Confirmations = ConfirmedDepth }); + + var act = () => _job.Execute(Substitute.For()); + + await act.Should().NotThrowAsync(); + confirmed.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed); + _repository.Received(1).Update(Arg.Is(r => r.Id == confirmed.Id)); + } +}