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
6 changes: 4 additions & 2 deletions src/Proto/nodeguard.proto
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
41 changes: 38 additions & 3 deletions src/Rpc/NodeGuardService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,8 @@ private void ValidateWithdrawalDestinations(IList<Destination> 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"));
}
Expand Down Expand Up @@ -321,11 +322,23 @@ public override async Task<RequestWithdrawalResponse> 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();

Expand All @@ -334,15 +347,37 @@ public override async Task<RequestWithdrawalResponse> 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,
Expand Down
9 changes: 9 additions & 0 deletions src/Services/BitcoinService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
9 changes: 8 additions & 1 deletion src/Services/WithdrawalRequestService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,15 @@ private async Task<WalletWithdrawalRequest> 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();
}

Expand Down
45 changes: 45 additions & 0 deletions test/NodeGuard.Tests/E2E/WalletEventsE2ETests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,51 @@ public async Task Interceptor_BlocksAWithdrawal_ThatIsRejectedAndNeverBroadcast(
"a blocked withdrawal is never signed");
}

/// <summary>
/// A changeless withdrawal sends its UTXOs in full, so that is the amount the integrator decides on, whatever
/// amount the request declared
/// </summary>
[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()
{
Expand Down
159 changes: 159 additions & 0 deletions test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1016,6 +1016,165 @@ public async Task RequestWithdrawal_Success_AuditsTheCreatedRequest()
AuditObjectType.WalletWithdrawalRequest, resp.RequestId.ToString(), It.IsAny<object?>()), 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<ICoinSelectionService>();
coinSelectionService
.Setup(x => x.GetUTXOsByOutpointAsync(It.IsAny<DerivationStrategyBase>(), It.IsAny<List<OutPoint>>()))
.ReturnsAsync(utxoList);

WalletWithdrawalRequest? saved = null;
walletWithdrawalRequestRepository.Setup(x => x.AddAsync(It.IsAny<WalletWithdrawalRequest>()))
.Callback<WalletWithdrawalRequest>(x => saved = x)
.ReturnsAsync((true, null));

object? audited = null;
var auditService = new Mock<IAuditService>();
auditService.Setup(x => x.LogAsync(AuditActionType.Create, AuditEventType.Success,
AuditObjectType.WalletWithdrawalRequest, It.IsAny<string?>(), It.IsAny<object?>()))
.Callback<AuditActionType, AuditEventType, AuditObjectType, string?, object?>((_, _, _, _, 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<RpcException>()).Which.StatusCode.Should().Be(StatusCode.InvalidArgument);
walletWithdrawalRequestRepository.Verify(x => x.AddAsync(It.IsAny<WalletWithdrawalRequest>()), 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<ICoinSelectionService>();
coinSelectionService
.Setup(x => x.GetUTXOsByOutpointAsync(It.IsAny<DerivationStrategyBase>(), It.IsAny<List<OutPoint>>()))
.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<RpcException>()).Which.StatusCode.Should().Be(StatusCode.InvalidArgument);
walletWithdrawalRequestRepository.Verify(x => x.AddAsync(It.IsAny<WalletWithdrawalRequest>()), Times.Never);
}

[Fact]
public async Task RequestWithdrawal_RefreshReturnsNull_CancelsAndAuditsTheSavedRequest()
{
Expand Down
Loading
Loading