diff --git a/src/Data/Models/AuditLog.cs b/src/Data/Models/AuditLog.cs
index 7d9756a5..f5f01a86 100644
--- a/src/Data/Models/AuditLog.cs
+++ b/src/Data/Models/AuditLog.cs
@@ -171,7 +171,10 @@ public enum AuditActionType
WithdrawalInterceptorConnected,
WithdrawalInterceptorDisconnected,
WithdrawalAllowedByIntegrator,
- WithdrawalBlockedByIntegrator
+ WithdrawalBlockedByIntegrator,
+
+ // RBF cancellation: a replacement request that sends the funds back to the wallet
+ RbfCancel
}
///
diff --git a/src/Pages/AuditTrail.razor b/src/Pages/AuditTrail.razor
index 9346f943..c71f3177 100644
--- a/src/Pages/AuditTrail.razor
+++ b/src/Pages/AuditTrail.razor
@@ -386,6 +386,7 @@
AuditActionType.Approve => Color.Success,
AuditActionType.Reject => Color.Warning,
AuditActionType.Cancel => Color.Secondary,
+ AuditActionType.RbfCancel => Color.Secondary,
AuditActionType.Login => Color.Primary,
AuditActionType.Logout => Color.Secondary,
AuditActionType.TwoFactorLogin => Color.Primary,
diff --git a/src/Pages/Withdrawals.razor b/src/Pages/Withdrawals.razor
index fbada670..b0b8fe3e 100644
--- a/src/Pages/Withdrawals.razor
+++ b/src/Pages/Withdrawals.razor
@@ -943,13 +943,16 @@
}
}
+ /// The audit action of the bump modal's current operation: an RBF cancellation or a fee bump.
+ private AuditActionType BumpAuditAction => _bumpIsCancellation ? AuditActionType.RbfCancel : AuditActionType.BumpFee;
+
private async Task ShowBumpfeeModal(WalletWithdrawalRequest walletWithdrawalRequest, bool cancellation = false)
{
_bumpIsCancellation = cancellation;
if (walletWithdrawalRequest == null)
{
ToastService.ShowError("Invalid request");
- await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, null, "Invalid bump fee request.");
+ await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, null, "Invalid RBF replacement request.");
return;
}
@@ -957,7 +960,7 @@
if (request == null)
{
ToastService.ShowError("Request not found");
- await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, walletWithdrawalRequest, "Withdrawal request not found for bumping.");
+ await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, walletWithdrawalRequest, "Withdrawal request to replace not found.");
return;
}
@@ -965,7 +968,7 @@
if (request.Status != WalletWithdrawalRequestStatus.OnChainConfirmationPending)
{
ToastService.ShowError("Bumpfee can only be used for transactions that are pending on-chain confirmation.");
- await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, request, "Bump requested for withdrawal not pending on-chain confirmation.");
+ await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, request, "RBF replacement requested for withdrawal not pending on-chain confirmation.");
return;
}
@@ -980,7 +983,7 @@
catch (Exception)
{
ToastService.ShowError("Error getting confirmations");
- await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, request, "Failed to retrieve transaction confirmations for bumping.");
+ await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, request, "Failed to retrieve transaction confirmations for the RBF replacement.");
return;
}
}
@@ -989,7 +992,7 @@
{
ToastService.ShowError("Bumpfee can only be used for transactions with no confirmations. " +
"This transaction has already been mined.");
- await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, request, "Bump requested for transaction that already has confirmations.");
+ await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, request, "RBF replacement requested for transaction that already has confirmations.");
return;
}
@@ -997,7 +1000,7 @@
if (!cancellation && request.Changeless && request.WalletWithdrawalRequestDestinations!.Count > 1)
{
ToastService.ShowError("Fee bumping is not supported for changeless transactions. Please create a new withdrawal with higher fees instead.");
- await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, request, "Bump requested for changeless transaction with multiple outputs.");
+ await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, request, "Bump requested for changeless transaction with multiple outputs.");
return;
}
@@ -1010,8 +1013,8 @@
catch (Exception ex)
{
ToastService.ShowError("Error while creating bumpfee modal");
- var message = string.IsNullOrWhiteSpace(ex.Message) ? "Error while creating bump fee modal." : ex.Message;
- await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, request, message);
+ var message = string.IsNullOrWhiteSpace(ex.Message) ? "Error while creating the RBF replacement modal." : ex.Message;
+ await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, request, message);
}
}
@@ -1106,14 +1109,14 @@
if (newRequest == null || _bumpfeeRef == null)
{
ToastService.ShowError("Something went wrong");
- await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, newRequest, "Invalid bump fee request parameters.");
+ await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, newRequest, "Invalid RBF replacement request parameters.");
return;
}
// The replacement was validated, created and its UTXOs locked by WithdrawalRequestService (see BumpfeeModal).
_selectedRequest = newRequest;
await _bumpfeeRef.HideModal();
- await LogWithdrawalAuditAsync(newRequest.IsRbfCancellation ? AuditActionType.Cancel : AuditActionType.BumpFee,
+ await LogWithdrawalAuditAsync(newRequest.IsRbfCancellation ? AuditActionType.RbfCancel : AuditActionType.BumpFee,
AuditEventType.Success, newRequest,
newRequest.IsRbfCancellation ? "RBF cancellation request created." : "Bump withdrawal request created.");
await GetData();
@@ -1134,7 +1137,7 @@
{
Logger.LogError(e, "Error while bumping withdrawal request {RequestId}", newRequest?.Id);
ToastService.ShowError("Something went wrong");
- await LogWithdrawalAuditAsync(AuditActionType.BumpFee, AuditEventType.Failure, newRequest, "Unexpected error while bumping withdrawal.");
+ await LogWithdrawalAuditAsync(BumpAuditAction, AuditEventType.Failure, newRequest, "Unexpected error while replacing withdrawal.");
if (_bumpfeeRef != null) await _bumpfeeRef.HideModal();
}
}
diff --git a/src/Rpc/NodeGuardService.cs b/src/Rpc/NodeGuardService.cs
index 000309d2..ca529726 100644
--- a/src/Rpc/NodeGuardService.cs
+++ b/src/Rpc/NodeGuardService.cs
@@ -292,6 +292,12 @@ public override async Task RequestWithdrawal(RequestW
ServerCallContext context)
{
WalletWithdrawalRequest? withdrawalRequest = null;
+ var auditDetails = new
+ {
+ request.WalletId,
+ Destinations = request.Destinations.Select(d => new { d.Address, d.AmountSats }),
+ request.ReferenceId
+ };
try
{
//We get the wallet
@@ -375,18 +381,26 @@ await _coinSelectionService.LockUTXOs(utxos, withdrawalRequest,
BitcoinRequestType.WalletWithdrawal);
}
- // Update to refresh from db
- withdrawalRequest = await _walletWithdrawalRequestRepository.GetById(withdrawalRequest.Id);
+ // Update to refresh from db. A missing row keeps the saved instance so the failure handling can still
+ // cancel and audit it
+ withdrawalRequest = await _walletWithdrawalRequestRepository.GetById(withdrawalRequest.Id)
+ ?? throw new InvalidOperationException(
+ $"Withdrawal request {withdrawalRequest.Id} not found after saving it");
- if (!withdrawalSaved.Item1)
+ // Template PSBT generation with SIGHASH_ALL
+ var psbt = await _bitcoinService.GenerateTemplatePSBT(withdrawalRequest);
+
+ // Built before the job is scheduled: once it is, nothing may fail and cancel a request the job will execute
+ var response = new RequestWithdrawalResponse
{
- _logger.LogError("Error saving withdrawal request for wallet with id {walletId}", request.WalletId);
- throw new RpcException(new Status(StatusCode.Internal, "Error saving withdrawal request for wallet"));
- }
+ IsHotWallet = wallet.IsHotWallet,
+ Txid = psbt.GetGlobalTransaction().GetHash().ToString(),
+ RequestId = withdrawalRequest.Id
+ };
- // Template PSBT generation with SIGHASH_ALL
- var psbt = await _bitcoinService.GenerateTemplatePSBT(withdrawalRequest ??
- throw new ArgumentException(nameof(withdrawalRequest)));
+ // Audited before the hot wallet job is scheduled, so the creation precedes the job's own audits
+ await _auditService.LogAsync(AuditActionType.Create, AuditEventType.Success,
+ AuditObjectType.WalletWithdrawalRequest, withdrawalRequest.Id.ToString(), auditDetails);
// If the wallet is hot, we send the withdrawal request to the embedded or remote signer
if (wallet.IsHotWallet)
@@ -397,40 +411,80 @@ await _coinSelectionService.LockUTXOs(utxos, withdrawalRequest,
await _scheduler.ScheduleJob(job.Job, job.Trigger);
}
- var response = new RequestWithdrawalResponse
- {
- IsHotWallet = wallet.IsHotWallet,
- Txid = psbt.GetGlobalTransaction().GetHash().ToString(),
- RequestId = withdrawalRequest.Id
- };
-
return response;
}
catch (NoUTXOsAvailableException)
{
- MarkWithdrawalRequestCancelled(withdrawalRequest);
+ await CancelFailedWithdrawalRequestAsync(withdrawalRequest, AuditActionType.Create, auditDetails,
+ "No available UTXOs for wallet");
_logger.LogError("No available UTXOs for wallet with id {walletId}", request.WalletId);
throw new RpcException(new Status(StatusCode.ResourceExhausted, "No available UTXOs for wallet"));
}
catch (NotEnoughBalanceInWalletException e)
{
+ await CancelFailedWithdrawalRequestAsync(withdrawalRequest, AuditActionType.Create, auditDetails, e.Message);
_logger.LogError(e.Message);
throw new RpcException(new Status(StatusCode.ResourceExhausted, e.Message));
}
catch (RpcException e)
{
- MarkWithdrawalRequestCancelled(withdrawalRequest);
+ await CancelFailedWithdrawalRequestAsync(withdrawalRequest, AuditActionType.Create, auditDetails,
+ e.Status.Detail);
_logger.LogError(e.Message);
throw new RpcException(new Status(e.Status.StatusCode, e.Status.Detail));
}
catch (Exception e)
{
- MarkWithdrawalRequestCancelled(withdrawalRequest);
+ await CancelFailedWithdrawalRequestAsync(withdrawalRequest, AuditActionType.Create, auditDetails,
+ e.Message);
_logger.LogError(e, "Error requesting withdrawal for wallet with id {walletId}", request.WalletId);
throw new RpcException(new Status(StatusCode.Internal, "Error requesting withdrawal for wallet"));
}
}
+ private Task CancelFailedWithdrawalRequestAsync(WalletWithdrawalRequest? withdrawalRequest,
+ AuditActionType actionType, object details, string? error)
+ {
+ int? persistedRequestId = withdrawalRequest is { Id: > 0 } ? withdrawalRequest.Id : null;
+
+ return FailRequestAndAuditAsync(persistedRequestId, () => MarkWithdrawalRequestCancelled(withdrawalRequest),
+ actionType, AuditObjectType.WalletWithdrawalRequest, details, error);
+ }
+
+ ///
+ /// Audits a failed request and, if it was already persisted, takes it out of the active states with
+ /// (which also releases its locked UTXOs, held only by active requests), so the
+ /// request id has a record of why it never went out. Requests refused before being persisted are audited
+ /// without an id.
+ ///
+ /// Runs inside catch blocks, so it never throws: that would replace the error being reported.
+ private async Task FailRequestAndAuditAsync(int? persistedRequestId, Action markFailed,
+ AuditActionType actionType, AuditObjectType objectType, object details, string? error)
+ {
+ // Separate tries so the failure is audited even if marking the request fails
+ if (persistedRequestId != null)
+ {
+ try
+ {
+ markFailed();
+ }
+ catch (Exception e)
+ {
+ _logger.LogError(e, "Error marking {ObjectType} {RequestId} as failed", objectType, persistedRequestId);
+ }
+ }
+
+ try
+ {
+ await _auditService.LogAsync(actionType, AuditEventType.Failure, objectType,
+ persistedRequestId?.ToString(), new { Request = details, Error = error });
+ }
+ catch (Exception e)
+ {
+ _logger.LogError(e, "Error auditing the failure of {ObjectType} {RequestId}", objectType, persistedRequestId);
+ }
+ }
+
private void MarkWithdrawalRequestCancelled(WalletWithdrawalRequest? withdrawalRequest)
{
if (withdrawalRequest != null)
@@ -496,7 +550,10 @@ private readonly record struct ReplacementTarget(int? RequestId, string? TxId)
MempoolRecommendedFeesType feeType, decimal? customFeeRate, bool cancellation)
{
var action = cancellation ? "cancellation" : "fee bump";
+ var auditAction = cancellation ? AuditActionType.RbfCancel : AuditActionType.BumpFee;
WalletWithdrawalRequest? replacement = null;
+ // Until the replacement exists, failures can only be tied to the requested target
+ object auditDetails = new { Target = target.ToString() };
try
{
var originalRequestId = await ResolveReplacementTargetAsync(target);
@@ -505,11 +562,27 @@ private readonly record struct ReplacementTarget(int? RequestId, string? TxId)
? await _withdrawalRequestService.CreateCancelRequestAsync(originalRequestId, feeType, customFeeRate)
: await _withdrawalRequestService.CreateBumpRequestAsync(originalRequestId, feeType, customFeeRate);
+ auditDetails = new { replacement.WalletId, ReplacedRequestId = originalRequestId, replacement.ReferenceId };
+
var isHotWallet = replacement.Wallet?.IsHotWallet ?? false;
+ Task AuditSuccessAsync()
+ {
+ return _auditService.LogAsync(auditAction, AuditEventType.Success,
+ AuditObjectType.WalletWithdrawalRequest, replacement.Id.ToString(), auditDetails);
+ }
- var psbt = isHotWallet
- ? await _withdrawalRequestService.ScheduleHotWalletWithdrawalAsync(replacement.Id)
- : await _bitcoinService.GenerateTemplatePSBT(replacement);
+ PSBT psbt;
+ if (isHotWallet)
+ {
+ // Audited once the PSBT exists but before the job is scheduled, so the replacement precedes the job's
+ // own audits
+ psbt = await _withdrawalRequestService.ScheduleHotWalletWithdrawalAsync(replacement.Id, AuditSuccessAsync);
+ }
+ else
+ {
+ psbt = await _bitcoinService.GenerateTemplatePSBT(replacement);
+ await AuditSuccessAsync();
+ }
return (replacement.Id, psbt.GetGlobalTransaction().GetHash().ToString(), isHotWallet);
}
@@ -517,29 +590,30 @@ private readonly record struct ReplacementTarget(int? RequestId, string? TxId)
{
_logger.LogWarning("RBF {Action} of withdrawal request {Target} refused ({Reason}): {Message}",
action, target, e.Reason, e.Message);
- MarkWithdrawalRequestCancelled(replacement);
+ await CancelFailedWithdrawalRequestAsync(replacement, auditAction, auditDetails, e.Message);
throw new RpcException(new Status(ToStatusCode(e.Reason), e.Message));
}
catch (NoUTXOsAvailableException)
{
- MarkWithdrawalRequestCancelled(replacement);
+ await CancelFailedWithdrawalRequestAsync(replacement, auditAction, auditDetails,
+ "No available UTXOs for wallet");
_logger.LogError("No available UTXOs for the RBF {Action} of withdrawal request {Target}", action, target);
throw new RpcException(new Status(StatusCode.ResourceExhausted, "No available UTXOs for wallet"));
}
catch (ShowToUserException e)
{
- MarkWithdrawalRequestCancelled(replacement);
+ await CancelFailedWithdrawalRequestAsync(replacement, auditAction, auditDetails, e.Message);
_logger.LogError(e, "Error in the RBF {Action} of withdrawal request {Target}", action, target);
throw new RpcException(new Status(StatusCode.FailedPrecondition, e.Message));
}
- catch (RpcException)
+ catch (RpcException e)
{
- MarkWithdrawalRequestCancelled(replacement);
+ await CancelFailedWithdrawalRequestAsync(replacement, auditAction, auditDetails, e.Status.Detail);
throw;
}
catch (Exception e)
{
- MarkWithdrawalRequestCancelled(replacement);
+ await CancelFailedWithdrawalRequestAsync(replacement, auditAction, auditDetails, e.Message);
_logger.LogError(e, "Error in the RBF {Action} of withdrawal request {Target}", action, target);
throw new RpcException(new Status(StatusCode.Internal, $"Error in the RBF {action} of the withdrawal request"));
}
@@ -751,38 +825,69 @@ public override async Task GetNodes(GetNodesRequest request, S
public override async Task OpenChannel(OpenChannelRequest request, ServerCallContext context)
{
- var sourceNode = await _nodeRepository.GetByPubkey(request.SourcePubKey);
- if (sourceNode == null)
+ var auditDetails = new
{
- throw new RpcException(new Status(StatusCode.NotFound, "Source node not found"));
- }
+ request.WalletId,
+ request.SatsAmount,
+ request.SourcePubKey,
+ request.DestinationPubKey
+ };
- var destNode = await _nodeRepository.GetByPubkey(request.DestinationPubKey);
- if (destNode == null)
+ NodeGuard.Data.Models.Node? sourceNode;
+ NodeGuard.Data.Models.Node? destNode;
+ Wallet? wallet;
+ try
{
- throw new RpcException(new Status(StatusCode.NotFound, "Destination node not found"));
- }
+ sourceNode = await _nodeRepository.GetByPubkey(request.SourcePubKey);
+ if (sourceNode == null)
+ {
+ throw new RpcException(new Status(StatusCode.NotFound, "Source node not found"));
+ }
- var wallet = await _walletRepository.GetById(request.WalletId);
- if (wallet == null)
- {
- throw new RpcException(new Status(StatusCode.NotFound, "Wallet not found"));
- }
+ destNode = await _nodeRepository.GetByPubkey(request.DestinationPubKey);
+ if (destNode == null)
+ {
+ throw new RpcException(new Status(StatusCode.NotFound, "Destination node not found"));
+ }
- RefuseSparkWallet(wallet);
+ wallet = await _walletRepository.GetById(request.WalletId);
+ if (wallet == null)
+ {
+ throw new RpcException(new Status(StatusCode.NotFound, "Wallet not found"));
+ }
- if (request.MempoolFeeRate == FEES_TYPE.CustomFee && request.CustomFeeRate == 0)
- {
- throw new RpcException(
- new Status(StatusCode.InvalidArgument, "Mempool fee rate configuration is not valid"));
- }
+ RefuseSparkWallet(wallet);
+
+ if (request.MempoolFeeRate == FEES_TYPE.CustomFee && request.CustomFeeRate == 0)
+ {
+ throw new RpcException(
+ new Status(StatusCode.InvalidArgument, "Mempool fee rate configuration is not valid"));
+ }
- if (request.Changeless && request.UtxosOutpoints.Count == 0)
+ if (request.Changeless && request.UtxosOutpoints.Count == 0)
+ {
+ throw new RpcException(new Status(StatusCode.InvalidArgument, "Changeless channel open requires utxos"));
+ }
+ }
+ catch (Exception e)
{
- throw new RpcException(new Status(StatusCode.InvalidArgument, "Changeless channel open requires utxos"));
+ // Nothing is persisted yet, so the refusal is only audited
+ var error = e is RpcException rpcException ? rpcException.Status.Detail : e.Message;
+ await _auditService.LogAsync(AuditActionType.Create, AuditEventType.Failure,
+ AuditObjectType.ChannelOperationRequest, null, new { Request = auditDetails, Error = error });
+
+ if (e is RpcException)
+ {
+ throw;
+ }
+
+ _logger?.LogError(e, "Error validating channel open request through gRPC");
+ throw new RpcException(new Status(StatusCode.Internal, "Error validating the channel open request"));
}
int requestId;
+ ChannelOperationRequest? channelOperationRequest = null;
+ var jobScheduled = false;
try
{
@@ -823,7 +928,7 @@ public override async Task OpenChannel(OpenChannelRequest r
throw new RpcException(new Status(StatusCode.NotFound, "Custom fee rate is required"));
}
- var channelOperationRequest = new ChannelOperationRequest
+ channelOperationRequest = new ChannelOperationRequest
{
SatsAmount = request.SatsAmount,
Description = $"Channel open from {sourceNode.PubKey} to {destNode.PubKey} (API)",
@@ -860,8 +965,7 @@ await _coinSelectionService.LockUTXOs(utxos, channelOperationRequest,
(await _lightningService.GenerateTemplatePSBT(channelOperationRequest));
if (templatePsbt == null)
{
- channelOperationRequest.Status = ChannelOperationRequestStatus.Failed;
- _channelOperationRequestRepository.Update(channelOperationRequest);
+ // The catch below marks the request as failed
if (noUtxosAvailable)
{
_logger?.LogError("No UTXOs available for opening the channel");
@@ -883,20 +987,38 @@ await _coinSelectionService.LockUTXOs(utxos, channelOperationRequest,
var retryList = RetriableJob.ParseRetryListFromString(Constants.JOB_RETRY_INTERVAL_LIST_IN_MINUTES);
var job = RetriableJob.Create(map, channelOperationRequest.Id.ToString(), retryList);
+
+ // Audited before the job is scheduled, so the creation precedes the job's own audits
+ await _auditService.LogAsync(AuditActionType.Create, AuditEventType.Success,
+ AuditObjectType.ChannelOperationRequest, channelOperationRequest.Id.ToString(), auditDetails);
+
await scheduler.ScheduleJob(job.Job, job.Trigger);
+ jobScheduled = true;
var jobUpdateResult = _channelOperationRequestRepository.Update(channelOperationRequest);
+ // The job is scheduled and will open the channel, so failing the call here would only make the client
+ // retry and open a second one
if (!jobUpdateResult.Item1)
{
- _logger?.LogError("Error updating channel operation request, error: {error}", jobUpdateResult.Item2);
- throw new RpcException(new Status(StatusCode.Internal, "Error updating channel operation request"));
+ _logger?.LogError("Error updating channel operation request {RequestId} after scheduling its job: {error}",
+ channelOperationRequest.Id, jobUpdateResult.Item2);
}
requestId = channelOperationRequest.Id;
}
+ catch (Exception e) when (jobScheduled)
+ {
+ // The job is scheduled and will open the channel, so the request stays active and audited as created.
+ // Failing the call would only make the client retry and open a second one
+ _logger?.LogError(e, "Error opening channel through gRPC after scheduling the job of request {RequestId}",
+ channelOperationRequest!.Id);
+ requestId = channelOperationRequest.Id;
+ }
catch (Exception e)
{
+ await FailChannelOpenRequestAsync(channelOperationRequest, auditDetails, e.Message);
+
_logger?.LogError(e, "Error opening channel through gRPC");
throw new RpcException(new Status(StatusCode.Internal, e.Message));
}
@@ -908,6 +1030,26 @@ await _coinSelectionService.LockUTXOs(utxos, channelOperationRequest,
};
}
+ private Task FailChannelOpenRequestAsync(ChannelOperationRequest? channelOperationRequest, object details,
+ string error)
+ {
+ int? persistedRequestId = channelOperationRequest is { Id: > 0 } ? channelOperationRequest.Id : null;
+
+ return FailRequestAndAuditAsync(persistedRequestId, () => MarkChannelOperationRequestFailed(channelOperationRequest!),
+ AuditActionType.Create, AuditObjectType.ChannelOperationRequest, details, error);
+ }
+
+ private void MarkChannelOperationRequestFailed(ChannelOperationRequest channelOperationRequest)
+ {
+ channelOperationRequest.Status = ChannelOperationRequestStatus.Failed;
+ var (updated, error) = _channelOperationRequestRepository.Update(channelOperationRequest);
+ if (!updated)
+ {
+ _logger?.LogError("Error marking channel operation request {RequestId} as failed: {Error}",
+ channelOperationRequest.Id, error);
+ }
+ }
+
public override async Task CloseChannel(CloseChannelRequest request,
ServerCallContext context)
{
diff --git a/src/Services/AuditService.cs b/src/Services/AuditService.cs
index 3e535e38..3007eda8 100644
--- a/src/Services/AuditService.cs
+++ b/src/Services/AuditService.cs
@@ -19,6 +19,7 @@
using System.Security.Claims;
using System.Text.Json;
+using System.Text.Json.Nodes;
using NodeGuard.Data.Models;
using NodeGuard.Data.Repositories.Interfaces;
using NodeGuard.Helpers;
@@ -27,6 +28,8 @@ namespace NodeGuard.Services;
public class AuditService : IAuditService
{
+ private const string ApiTokenIdKey = "ApiTokenId";
+
private readonly IAuditLogRepository _auditLogRepository;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ILogger _logger;
@@ -48,8 +51,9 @@ public async Task LogAsync(
string? objectId = null,
object? details = null)
{
- var (userId, username, ipAddress) = ExtractContextInfo();
- await LogInternalAsync(actionType, eventType, objectAffected, objectId, userId, username, ipAddress, details);
+ var (userId, username, ipAddress, contextDetails) = ExtractContextInfo();
+ await LogInternalAsync(actionType, eventType, objectAffected, objectId, userId, username, ipAddress, details,
+ contextDetails);
}
public async Task LogSystemAsync(
@@ -70,11 +74,12 @@ private async Task LogInternalAsync(
string? userId,
string? username,
string? ipAddress,
- object? details)
+ object? details,
+ IReadOnlyDictionary? contextDetails = null)
{
try
{
- var detailsJson = details != null ? JsonSerializer.Serialize(details) : null;
+ var detailsJson = SerializeDetails(details, contextDetails);
// Log to system logger
_logger.LogInformation(
@@ -113,11 +118,53 @@ private async Task LogInternalAsync(
}
}
- private (string? UserId, string? Username, string? IpAddress) ExtractContextInfo()
+ ///
+ /// Serializes the details, adding the request context (the user's roles at the time of the action, or the API
+ /// token that authenticated a gRPC call) so it can be checked later even if roles or tokens change. Details that
+ /// are not a JSON object are wrapped under Details and keys supplied by the caller are never overwritten.
+ /// The context is recorded even when the caller passes no details, so every user audit keeps its roles.
+ ///
+ private static string? SerializeDetails(object? details, IReadOnlyDictionary? contextDetails)
+ {
+ if (contextDetails == null || contextDetails.Count == 0)
+ {
+ return details == null ? null : JsonSerializer.Serialize(details);
+ }
+
+ var node = details != null ? JsonSerializer.SerializeToNode(details) : new JsonObject();
+ var detailsObject = node as JsonObject ?? new JsonObject { ["Details"] = node };
+
+ foreach (var (key, value) in contextDetails)
+ {
+ if (!detailsObject.ContainsKey(key))
+ {
+ detailsObject[key] = value?.DeepClone();
+ }
+ }
+
+ return detailsObject.ToJsonString();
+ }
+
+ ///
+ /// Token names have no length limit, so the name is cut to keep the username within 's
+ /// 256 characters; otherwise the insert fails and the audit is lost.
+ ///
+ private static string FormatApiTokenUsername(AuthenticatedApiToken apiToken)
+ {
+ const int usernameMaxLength = 256;
+ var prefix = $"API token {apiToken.Id} (";
+ var maxNameLength = usernameMaxLength - prefix.Length - 1;
+ var name = apiToken.Name.Length > maxNameLength ? apiToken.Name[..maxNameLength] : apiToken.Name;
+ return $"{prefix}{name})";
+ }
+
+ private (string? UserId, string? Username, string? IpAddress, IReadOnlyDictionary ContextDetails)
+ ExtractContextInfo()
{
string? userId = null;
string? username = null;
string? ipAddress = null;
+ var contextDetails = new Dictionary();
try
{
@@ -133,6 +180,18 @@ private async Task LogInternalAsync(
username = user.FindFirst(ClaimTypes.Name)?.Value
?? user.FindFirst(ClaimTypes.Email)?.Value
?? user.Identity.Name;
+ contextDetails["UserRoles"] = new JsonArray(user.FindAll(ClaimTypes.Role)
+ .Select(c => (JsonNode?)JsonValue.Create(c.Value)).ToArray());
+ }
+
+ // gRPC calls are authenticated by an API token instead of a user (see GRPCAuthInterceptor)
+ if (httpContext.Items.TryGetValue(AuthenticatedApiToken.HttpContextItemKey, out var item)
+ && item is AuthenticatedApiToken apiToken)
+ {
+ // The id keeps tokens sharing a name apart, and the spaces keep it from passing for a username
+ username ??= FormatApiTokenUsername(apiToken);
+ contextDetails[ApiTokenIdKey] = apiToken.Id;
+ contextDetails["ApiTokenName"] = apiToken.Name;
}
// Extract IP address (considering proxies)
@@ -144,6 +203,6 @@ private async Task LogInternalAsync(
_logger.LogWarning(ex, "Error extracting context info for audit log");
}
- return (userId, username, ipAddress);
+ return (userId, username, ipAddress, contextDetails);
}
}
diff --git a/src/Services/WithdrawalRequestService.cs b/src/Services/WithdrawalRequestService.cs
index 686c9673..3ae44535 100644
--- a/src/Services/WithdrawalRequestService.cs
+++ b/src/Services/WithdrawalRequestService.cs
@@ -62,8 +62,11 @@ Task CreateCancelRequestAsync(int originalRequestId, Me
/// 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.
///
+ /// The hot-wallet request to execute.
+ /// Runs once the template PSBT exists and the replaced request is marked, right
+ /// before the job is scheduled, so callers can audit the request ahead of the job's own audits.
/// The template PSBT; its global transaction hash is the txid that will be broadcast.
- Task ScheduleHotWalletWithdrawalAsync(int requestId);
+ Task ScheduleHotWalletWithdrawalAsync(int requestId, Func? beforeScheduling = null);
///
/// Marks the request replaced by as Bumped (fee bump) or Cancelled (RBF cancellation).
@@ -291,7 +294,7 @@ private async Task CreateReplacementAsync(int originalR
return await _walletWithdrawalRequestRepository.GetById(replacement.Id) ?? replacement;
}
- public async Task ScheduleHotWalletWithdrawalAsync(int requestId)
+ public async Task ScheduleHotWalletWithdrawalAsync(int requestId, Func? beforeScheduling = null)
{
var request = await _walletWithdrawalRequestRepository.GetById(requestId)
?? throw new InvalidOperationException($"Withdrawal request {requestId} not found");
@@ -333,6 +336,11 @@ public async Task ScheduleHotWalletWithdrawalAsync(int requestId)
await MarkOriginalAsReplacedAsync(request);
}
+ if (beforeScheduling != null)
+ {
+ await beforeScheduling();
+ }
+
var scheduler = await _schedulerFactory.GetScheduler();
var map = new JobDataMap();
map.Put("withdrawalRequestId", request.Id);
diff --git a/src/Shared/TransferFundsModal.razor b/src/Shared/TransferFundsModal.razor
index 315733eb..1740bb42 100644
--- a/src/Shared/TransferFundsModal.razor
+++ b/src/Shared/TransferFundsModal.razor
@@ -461,15 +461,15 @@ _amountToTransfer;
await AuditService.LogAsync(
AuditActionType.Transfer,
AuditEventType.Success,
- AuditObjectType.Wallet,
- _sourceTransferWallet?.Id.ToString(),
+ AuditObjectType.WalletWithdrawalRequest,
+ withdrawalRequest.Id.ToString(),
new
{
+ SourceWalletId = _sourceTransferWallet?.Id,
SourceWallet = _sourceWalletName,
TargetWallet = _targetWalletName,
Amount = _amountToTransfer,
- AllFunds = _transferAllFunds,
- WithdrawalRequestId = withdrawalRequest.Id
+ AllFunds = _transferAllFunds
});
await _multisigTransferModal.ShowModal();
await CloseAndCleanTransferFundsModal();
@@ -515,39 +515,43 @@ _amountToTransfer;
var amount = _selectedUTXOs.Count > 0 ? SelectedUTXOsValue() : _amountToTransfer;
var withdrawalRequest = await CreateWithdrawalRequestForFunds(_sourceTransferWallet, _targetTransferWallet, amount,
_transferAllFunds);
- var transferSuccess = await TransferInnerWithdrawalProcess(withdrawalRequest);
+ bool transferSuccess;
+ try
+ {
+ transferSuccess = await TransferInnerWithdrawalProcess(withdrawalRequest);
+ }
+ catch (Exception e)
+ {
+ // The request is already saved: fail it so its UTXOs are released and audit why, then let the outer catch toast
+ withdrawalRequest.Status = WalletWithdrawalRequestStatus.Failed;
+ var (updated, updateError) = WalletWithdrawalRequestRepository.Update(withdrawalRequest);
+ if (!updated)
+ {
+ Logger.LogError("Error while updating the withdrawal request {RequestId} status to failed: {Error}", withdrawalRequest.Id, updateError);
+ }
+
+ await AuditService.LogAsync(
+ AuditActionType.Transfer,
+ AuditEventType.Failure,
+ AuditObjectType.WalletWithdrawalRequest,
+ withdrawalRequest.Id.ToString(),
+ new { Request = HotWalletTransferAuditDetails(), Error = e.Message });
+ throw;
+ }
+ // The Success entry is written in CreateJobForFunds, before the job is scheduled
if (transferSuccess)
{
ToastService.ShowSuccess("Funds transferred successfully");
- await AuditService.LogAsync(
- AuditActionType.Transfer,
- AuditEventType.Success,
- AuditObjectType.Wallet,
- _sourceTransferWallet?.Id.ToString(),
- new
- {
- SourceWallet = _sourceWalletName,
- TargetWallet = _targetWalletName,
- Amount = _amountToTransfer,
- AllFunds = _transferAllFunds,
- WithdrawalRequestId = withdrawalRequest.Id
- });
}
else
{
await AuditService.LogAsync(
AuditActionType.Transfer,
AuditEventType.Failure,
- AuditObjectType.Wallet,
- _sourceTransferWallet?.Id.ToString(),
- new
- {
- SourceWallet = _sourceWalletName,
- TargetWallet = _targetWalletName,
- Amount = _amountToTransfer,
- WithdrawalRequestId = withdrawalRequest.Id
- });
+ AuditObjectType.WalletWithdrawalRequest,
+ withdrawalRequest.Id.ToString(),
+ HotWalletTransferAuditDetails());
ToastService.ShowError("Error while transferring funds, please contact a superadmin for troubleshooting");
}
@@ -628,6 +632,18 @@ _amountToTransfer;
return result;
}
+ private object HotWalletTransferAuditDetails()
+ {
+ return new
+ {
+ SourceWalletId = _sourceTransferWallet?.Id,
+ SourceWallet = _sourceWalletName,
+ TargetWallet = _targetWalletName,
+ Amount = _amountToTransfer,
+ AllFunds = _transferAllFunds
+ };
+ }
+
private async Task CreateJobForFunds(WalletWithdrawalRequest withdrawalRequest)
{
var result = false;
@@ -640,6 +656,14 @@ _amountToTransfer;
map.Put("withdrawalRequestId", withdrawalRequest.Id);
var job = SimpleJob.Create(map, withdrawalRequest.Id.ToString());
+
+ // Audit before scheduling so the transfer comes before the job's own audits
+ await AuditService.LogAsync(
+ AuditActionType.Transfer,
+ AuditEventType.Success,
+ AuditObjectType.WalletWithdrawalRequest,
+ withdrawalRequest.Id.ToString(),
+ HotWalletTransferAuditDetails());
await scheduler.ScheduleJob(job.Job, job.Trigger);
// No write after scheduling: the job may already have moved the request to FinalizingPSBT or broadcast
diff --git a/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs b/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs
index d963b27a..34b505ee 100644
--- a/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs
+++ b/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs
@@ -134,11 +134,13 @@ public async Task OpenChannel_SourceNodeNotFound_ReturnsNotFoundError()
nodeRepositoryMock.Setup(repo => repo.GetByPubkey(sourcePubKey)).ReturnsAsync((Node?)null);
nodeRepositoryMock.Setup(repo => repo.GetByPubkey(destPubKey))
.ReturnsAsync(new Node { Id = 2, PubKey = destPubKey });
+ var auditService = new Mock();
var service = CreateNodeGuardService(
schedulerFactory: schedulerFactoryMock,
nodeRepository: nodeRepositoryMock.Object,
- channelOperationRequestRepository: channelOperationRequestRepositoryMock.Object);
+ channelOperationRequestRepository: channelOperationRequestRepositoryMock.Object,
+ auditService: auditService.Object);
var request = new OpenChannelRequest
{
@@ -155,6 +157,206 @@ public async Task OpenChannel_SourceNodeNotFound_ReturnsNotFoundError()
// Assert
(await act.Should().ThrowAsync()).Which.Status.StatusCode.Should().Be(StatusCode.NotFound);
+ auditService.Verify(x => x.LogAsync(AuditActionType.Create, AuditEventType.Failure,
+ AuditObjectType.ChannelOperationRequest, null, It.IsAny