Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions src/Jobs/MonitorWithdrawalsJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,25 @@ 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))
{
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;
Expand All @@ -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);
}
}
}
Expand Down
6 changes: 2 additions & 4 deletions src/Pages/Withdrawals.razor
Original file line number Diff line number Diff line change
Expand Up @@ -1362,10 +1362,8 @@
var job = SimpleJob.Create<PerformWithdrawalJob>(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)
Expand Down
8 changes: 3 additions & 5 deletions src/Shared/TransferFundsModal.razor
Original file line number Diff line number Diff line change
Expand Up @@ -642,11 +642,9 @@ _amountToTransfer;
var job = SimpleJob.Create<PerformWithdrawalJob>(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)
{
Expand Down
91 changes: 91 additions & 0 deletions test/NodeGuard.Tests/Jobs/MonitorWithdrawalsJobTests.cs
Original file line number Diff line number Diff line change
@@ -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<IWalletWithdrawalRequestRepository>();
private readonly INBXplorerService _nbXplorerService = Substitute.For<INBXplorerService>();
private readonly MonitorWithdrawalsJob _job;

public MonitorWithdrawalsJobTests()
{
_repository.Update(Arg.Any<WalletWithdrawalRequest>()).Returns((true, null));
_job = new MonitorWithdrawalsJob(NullLogger<MonitorWithdrawalsJob>.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<WalletWithdrawalRequest> { evicted, confirmed });
_nbXplorerService.GetTransactionAsync(uint256.Parse(evicted.TxId!), Arg.Any<CancellationToken>())
.Returns((TransactionResult?)null);
_nbXplorerService.GetTransactionAsync(uint256.Parse(confirmed.TxId!), Arg.Any<CancellationToken>())
.Returns(new TransactionResult { Confirmations = ConfirmedDepth });

await _job.Execute(Substitute.For<IJobExecutionContext>());

evicted.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmationPending);
confirmed.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed);
_repository.Received(1).Update(Arg.Is<WalletWithdrawalRequest>(r => r.Id == confirmed.Id));
_repository.DidNotReceive().Update(Arg.Is<WalletWithdrawalRequest>(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<WalletWithdrawalRequest> { failing, confirmed });
_nbXplorerService.GetTransactionAsync(uint256.Parse(failing.TxId!), Arg.Any<CancellationToken>())
.ThrowsAsync(new HttpRequestException("nbxplorer down"));
_nbXplorerService.GetTransactionAsync(uint256.Parse(confirmed.TxId!), Arg.Any<CancellationToken>())
.Returns(new TransactionResult { Confirmations = ConfirmedDepth });

var act = () => _job.Execute(Substitute.For<IJobExecutionContext>());

await act.Should().NotThrowAsync();
confirmed.Status.Should().Be(WalletWithdrawalRequestStatus.OnChainConfirmed);
_repository.Received(1).Update(Arg.Is<WalletWithdrawalRequest>(r => r.Id == confirmed.Id));
}
}
Loading