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
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ Use [reference-code/](reference-code/) as **read-only** source material when inf
- `FinanceManager` — handles on-chain funds and signing (wallets, withdrawals, signing keys).
- `Superadmin` — full admin (user/API token management, internal wallet setup); typically also holds the other two roles.

gRPC uses a stateless `auth-token` header validated by [src/Rpc/GRPCAuthInterceptor.cs](src/Rpc/GRPCAuthInterceptor.cs) against the `APIToken` table, on unary and streaming calls alike; the validated token is in `GRPCAuthInterceptor.GetApiToken(context)`. `SubscribeWalletEvents` (bidirectional) streams wallet events from the in-process `WalletEventHub`; withdrawal events are published by the withdrawal repositories after each save. Outbound gRPC to LND/Loop nodes uses macaroons via [src/Services/GRPCMacaroonInterceptor.cs](src/Services/GRPCMacaroonInterceptor.cs).
gRPC uses a stateless `auth-token` header validated by [src/Rpc/GRPCAuthInterceptor.cs](src/Rpc/GRPCAuthInterceptor.cs) against the `APIToken` table, on unary and streaming calls alike; the validated token is in `GRPCAuthInterceptor.GetApiToken(context)`. `SubscribeWalletEvents` (bidirectional) streams wallet events from the in-process `WalletEventHub`; withdrawal events are published by the withdrawal repositories after each save. A subscriber with `intercept_withdrawals` is asked by `PerformWithdrawalJob` (via `WithdrawalInterceptorGate`) before every withdrawal is signed; a block, timeout or disconnect rejects it, no interceptor skips the check. The hub and gate are in-process, so they assume a single NodeGuard instance. Outbound gRPC to LND/Loop nodes uses macaroons via [src/Services/GRPCMacaroonInterceptor.cs](src/Services/GRPCMacaroonInterceptor.cs).

**Data layer** ([src/Data/](src/Data/)). PostgreSQL via Npgsql + EF Core. `ApplicationDbContext` extends `IdentityDbContext`. Repository pattern — generic `Repository<T>` plus per-entity repos in [src/Data/Repositories/](src/Data/Repositories/). Both `AddDbContext<ApplicationDbContext>` (transient) **and** `AddDbContextFactory<ApplicationDbContext>` are registered in `Program.cs` — **prefer the factory inside Quartz jobs and singletons**, the transient context is for short request-scoped work. Queries use `UseQuerySplittingBehavior(SingleQuery)` deliberately.

Expand Down
4 changes: 4 additions & 0 deletions docker/e2e/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ tests (`DustUtxoWithdrawalE2ETests`, `WithdrawalRbfBumpE2ETests`, `GetNewWalletA
over gRPC, asserting bitcoind evicts the original for the higher-fee replacement, NodeGuard marks the original
`WITHDRAWAL_BUMPED`, and the replacement settles once mined. It relies on `MONITOR_WITHDRAWALS_CRON` being fast on
the `nodeguard` service (10s here; prod keeps the every-5-minutes default) and never mines between the two calls.
- **Withdrawal interceptor scenarios** (`WalletEventsE2ETests`): an integrator subscribes with
`intercept_withdrawals` and allows, blocks or ignores a hot-wallet withdrawal (and blocks an RBF bump). The
unanswered case relies on `WITHDRAWAL_INTERCEPTOR_TIMEOUT_SECONDS` being short on the `nodeguard` service (10s
here; prod default 60s).
- **Adding an e2e test**: put it in `[Collection("E2E")]` (so it serialises with the others on the one
regtest chain — without it the class runs in parallel and they interfere), have it provision the
resources it needs and reset its own state, and gate it with `[E2EFact]`.
2 changes: 2 additions & 0 deletions docker/e2e/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ services:
# WithdrawalRbfBumpE2ETests waits for the bumped withdrawal to settle once mined; poll confirmations every 10s
# instead of the default every-5-minutes cron.
MONITOR_WITHDRAWALS_CRON: "0/10 * * * * ?"
# WalletEventsE2ETests leaves one withdrawal unanswered and waits for it to be blocked; 10s instead of 60s.
WITHDRAWAL_INTERCEPTOR_TIMEOUT_SECONDS: "10"
ROUTING_ENGINE_ENABLED: "true"
ROUTING_ENGINE_DRY_RUN: "false"
ROUTING_ENGINE_FEE_MIN_CHANNEL_SIZE_SATS: "15000000"
Expand Down
8 changes: 7 additions & 1 deletion src/Data/Models/AuditLog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,13 @@ public enum AuditActionType

// Spark transit wallet alerts
SparkBalanceStuck,
SparkExitOverdue
SparkExitOverdue,

// Withdrawal interceptors (SubscribeWalletEvents with intercept_withdrawals)
WithdrawalInterceptorConnected,
WithdrawalInterceptorDisconnected,
WithdrawalAllowedByIntegrator,
WithdrawalBlockedByIntegrator
}

/// <summary>
Expand Down
7 changes: 7 additions & 0 deletions src/Helpers/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,10 @@ public class Constants
/// Default timeout (seconds) for a rebalance payment to search for a route before giving up.
public static int DEFAULT_REBALANCE_TIMEOUT_SECONDS = 180;

/// How long (seconds) a withdrawal waits for the integrators intercepting its wallet (SubscribeWalletEvents with
/// intercept_withdrawals) to allow it before it is blocked
public static int WITHDRAWAL_INTERCEPTOR_TIMEOUT_SECONDS = 60;

public const string IsFrozenTag = "frozen";
public const string IsManuallyFrozenTag = "manually_frozen";

Expand Down Expand Up @@ -727,6 +731,9 @@ static Constants()
var rebalanceTimeoutSeconds = Environment.GetEnvironmentVariable("DEFAULT_REBALANCE_TIMEOUT_SECONDS");
if (rebalanceTimeoutSeconds != null) DEFAULT_REBALANCE_TIMEOUT_SECONDS = int.Parse(rebalanceTimeoutSeconds);

var withdrawalInterceptorTimeoutSeconds = Environment.GetEnvironmentVariable("WITHDRAWAL_INTERCEPTOR_TIMEOUT_SECONDS");
if (withdrawalInterceptorTimeoutSeconds != null) WITHDRAWAL_INTERCEPTOR_TIMEOUT_SECONDS = int.Parse(withdrawalInterceptorTimeoutSeconds);

// DB Initialization
ALICE_PUBKEY = Environment.GetEnvironmentVariable("ALICE_PUBKEY") ?? ALICE_PUBKEY;
ALICE_HOST = Environment.GetEnvironmentVariable("ALICE_HOST") ?? ALICE_HOST;
Expand Down
117 changes: 93 additions & 24 deletions src/Jobs/PerformWithdrawalJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
namespace NodeGuard.Jobs;

/// <summary>
/// Job for performing withdrawal requests from the btc wallet, with automatic retry
/// Job for performing withdrawal requests from the btc wallet. Before signing, the integrators intercepting the
/// wallet's withdrawals (SubscribeWalletEvents with intercept_withdrawals) are asked; a block rejects the request.
/// </summary>
/// <returns></returns>
[DisallowConcurrentExecution]
Expand All @@ -36,13 +37,23 @@ public class PerformWithdrawalJob : IJob
private readonly ILogger<PerformWithdrawalJob> _logger;
private readonly IBitcoinService _bitcoinService;
private readonly IWalletWithdrawalRequestRepository _walletWithdrawalRequestRepository;
private readonly IWithdrawalInterceptorGate _interceptorGate;
private readonly IWithdrawalRequestService _withdrawalRequestService;
private readonly IAuditService _auditService;


public PerformWithdrawalJob(ILogger<PerformWithdrawalJob> logger, IBitcoinService bitcoinService, IWalletWithdrawalRequestRepository walletWithdrawalRequestRepository)
public PerformWithdrawalJob(ILogger<PerformWithdrawalJob> logger,
IBitcoinService bitcoinService,
IWalletWithdrawalRequestRepository walletWithdrawalRequestRepository,
IWithdrawalInterceptorGate interceptorGate,
IWithdrawalRequestService withdrawalRequestService,
IAuditService auditService)
{
_logger = logger;
_bitcoinService = bitcoinService;
_walletWithdrawalRequestRepository = walletWithdrawalRequestRepository;
_interceptorGate = interceptorGate;
_withdrawalRequestService = withdrawalRequestService;
_auditService = auditService;
}

public async Task Execute(IJobExecutionContext context)
Expand All @@ -53,35 +64,40 @@ public async Task Execute(IJobExecutionContext context)
try
{
var withdrawalRequest = await _walletWithdrawalRequestRepository.GetById(withdrawalRequestId);
if (withdrawalRequest != null)
{
var outcome = await AskIntegratorsAsync(withdrawalRequest, context.CancellationToken);
switch (outcome.Kind)
{
case WithdrawalInterceptOutcomeKind.Allowed:
await _auditService.LogSystemAsync(AuditActionType.WithdrawalAllowedByIntegrator,
AuditEventType.Success, AuditObjectType.WalletWithdrawalRequest,
withdrawalRequest.Id.ToString(), AuditDetails(withdrawalRequest, outcome));
break;
case WithdrawalInterceptOutcomeKind.Blocked:
await RejectBlockedAsync(withdrawalRequest, outcome);
_logger.LogInformation("{JobName} ended: withdrawal request {RequestId} blocked by an integrator",
nameof(PerformWithdrawalJob), withdrawalRequestId);
return;
}
}

await _bitcoinService.PerformWithdrawal(withdrawalRequest!);
}
catch (Exception e)
{
var request = await _walletWithdrawalRequestRepository.GetById(withdrawalRequestId);

// If an error occurs and the wd was bumping another one, we need to update the status of the withdrawal request to previous status
if (request != null && request!.BumpingWalletWithdrawalRequestId.HasValue)
if (request == null)
{
var bumped = await _walletWithdrawalRequestRepository.GetById(request.BumpingWalletWithdrawalRequestId.Value);
if (bumped == null)
{
_logger.LogError("Failed to find withdrawal request with ID {WithdrawalRequestId}", withdrawalRequestId);
return;
}

bumped.Status = WalletWithdrawalRequestStatus.OnChainConfirmationPending;
var (ok, _) = _walletWithdrawalRequestRepository.Update(bumped);
if (!ok)
{
_logger.LogError("Failed to update withdrawal request status to OnChainConfirmationPending for ID {WithdrawalRequestId}", withdrawalRequestId);
}
else
{
_logger.LogInformation("Updated withdrawal request status to OnChainConfirmationPending for ID {WithdrawalRequestId}", withdrawalRequestId);
}
_logger.LogError(e, "Error on {JobName}, and withdrawal request {RequestId} could not be found",
nameof(PerformWithdrawalJob), withdrawalRequestId);
return;
}

request!.Status = WalletWithdrawalRequestStatus.Failed;
// A failed RBF replacement puts the request it was replacing back to pending confirmation
await _withdrawalRequestService.RevertOriginalAsync(request);

request.Status = WalletWithdrawalRequestStatus.Failed;
var (updated, _) = _walletWithdrawalRequestRepository.Update(request);
if (!updated)
{
Expand All @@ -93,4 +109,57 @@ public async Task Execute(IJobExecutionContext context)

_logger.LogInformation("{JobName} ended", nameof(PerformWithdrawalJob));
}

/// <summary>
/// Puts the request to the integrators intercepting its wallet and returns their outcome, without acting on it.
/// Skipped with nobody intercepting, or when the request is not about to be signed.
/// </summary>
private Task<WithdrawalInterceptOutcome> AskIntegratorsAsync(WalletWithdrawalRequest request,
CancellationToken cancellationToken)
{
// Only a request about to be signed is put to the integrators; anything else fails in PerformWithdrawal as before
if (request.Status is not (WalletWithdrawalRequestStatus.PSBTSignaturesPending
or WalletWithdrawalRequestStatus.FinalizingPSBT))
{
return Task.FromResult(WithdrawalInterceptOutcome.Skipped);
}

return _interceptorGate.RequestDecisionAsync(request, cancellationToken);
}

/// <summary>
/// Rejects a request an integrator blocked, and reverts the request it was replacing, for an RBF replacement
/// </summary>
private async Task RejectBlockedAsync(WalletWithdrawalRequest request, WithdrawalInterceptOutcome outcome)
{
_logger.LogWarning("Withdrawal request {RequestId} blocked by integrator {Integrator}: {Reason}",
request.Id, outcome.DecidedBy, outcome.Reason);

request.Status = WalletWithdrawalRequestStatus.Rejected;
request.RejectCancelDescription = $"Blocked by integrator '{outcome.DecidedBy}': {outcome.Reason}";
var (updated, error) = _walletWithdrawalRequestRepository.Update(request);
if (!updated)
{
// Never sign a blocked withdrawal: let the job's failure path mark it failed instead
throw new InvalidOperationException(
$"Withdrawal request {request.Id} was blocked by an integrator but could not be rejected: {error}");
}

await _withdrawalRequestService.RevertOriginalAsync(request);

await _auditService.LogSystemAsync(AuditActionType.WithdrawalBlockedByIntegrator, AuditEventType.Success,
AuditObjectType.WalletWithdrawalRequest, request.Id.ToString(), AuditDetails(request, outcome));
}

private static object AuditDetails(WalletWithdrawalRequest request, WithdrawalInterceptOutcome outcome) => new
{
RequestId = request.Id,
request.WalletId,
outcome.DecisionId,
outcome.Interceptors,
outcome.DecidedBy,
outcome.Reason,
request.BumpingWalletWithdrawalRequestId,
request.IsRbfCancellation
};
}
1 change: 1 addition & 0 deletions src/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ public static async Task Main(string[] args)
builder.Services.AddHostedService<SparkStartupService>();
builder.Services.AddSingleton<IWalletEventHub, WalletEventHub>();
builder.Services.AddTransient<IWithdrawalEventPublisher, WithdrawalEventPublisher>();
builder.Services.AddSingleton<IWithdrawalInterceptorGate, WithdrawalInterceptorGate>();
builder.Services.AddTransient<IRebalanceService, RebalanceService>();
builder.Services.AddTransient<IRoutingEngineSnapshotService, RoutingEngineSnapshotService>();
builder.Services.AddScoped<IAuditService, AuditService>();
Expand Down
29 changes: 28 additions & 1 deletion src/Proto/nodeguard.proto
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,15 @@ service NodeGuardService {
failed, and an RBF replacement reverted. Events are live only: nothing is stored or replayed, so a client that
reconnects should reconcile with GetWithdrawalsRequestStatus after WALLET_EVENT_SUBSCRIBED. Events come from the
NodeGuard instance the call is connected to. A client that cannot keep up is disconnected with RESOURCE_EXHAUSTED.

With intercept_withdrawals, the client also decides on the wallet's withdrawals: before NodeGuard signs and
broadcasts one (RBF bumps and cancellations included), it sends WALLET_EVENT_WITHDRAWAL_DECISION_REQUESTED with a
decision_id and a deadline, and the client answers with a WithdrawalDecision on this call. The withdrawal goes ahead
only when every connected interceptor allows it; a block, no answer before the deadline
(WITHDRAWAL_INTERCEPTOR_TIMEOUT_SECONDS, 60s by default) or an interceptor leaving before it answers rejects it,
and an RBF replacement that is rejected puts the original back to pending confirmation. With no interceptor
connected the check is skipped. Interceptors are only seen by the NodeGuard instance they are connected to, so
this holds for a single NodeGuard instance. Half-closing the request stream ends an interceptor's call.
*/
rpc SubscribeWalletEvents(stream WalletEventsClientMessage) returns (stream WalletEvent);
}
Expand Down Expand Up @@ -844,13 +853,26 @@ message WalletEventsClientMessage {
oneof message {
// Must be the first message of the call
SubscribeWalletEventsRequest subscribe = 1;
// Answers a WALLET_EVENT_WITHDRAWAL_DECISION_REQUESTED; only from a subscription with intercept_withdrawals
WithdrawalDecision decision = 2;
}
}

message WithdrawalDecision {
// The decision_id of the WALLET_EVENT_WITHDRAWAL_DECISION_REQUESTED being answered
string decision_id = 1;
bool allow = 2;
// Why it was blocked; stored as the withdrawal's rejection reason
optional string reason = 3;
}

message SubscribeWalletEventsRequest {
int32 wallet_id = 1;
// Only these event types are sent; empty sends all. WALLET_EVENT_SUBSCRIBED is always sent.
// Only these event types are sent; empty sends all. WALLET_EVENT_SUBSCRIBED and, for interceptors,
// WALLET_EVENT_WITHDRAWAL_DECISION_REQUESTED are always sent.
repeated WALLET_EVENT_TYPE event_types = 2;
// Decide on the wallet's withdrawals before they are signed and broadcast
bool intercept_withdrawals = 3;
}

enum WALLET_EVENT_TYPE {
Expand All @@ -877,6 +899,8 @@ enum WALLET_EVENT_TYPE {
WALLET_EVENT_WITHDRAWAL_REPLACEMENT_REVERTED = 19;
// Any other status change, e.g. a hot wallet withdrawal moving to signatures pending
WALLET_EVENT_WITHDRAWAL_STATUS_CHANGED = 20;
// Sent to interceptors only: answer with a WithdrawalDecision for decision_id before decision_deadline_unix_ms
WALLET_EVENT_WITHDRAWAL_DECISION_REQUESTED = 21;
}

message WalletEvent {
Expand Down Expand Up @@ -916,4 +940,7 @@ message WithdrawalEvent {
optional string request_metadata = 14;
// Requested fee rate when one was set explicitly
optional double fee_rate_sat_vb = 15;
// Set on WALLET_EVENT_WITHDRAWAL_DECISION_REQUESTED
optional string decision_id = 16;
optional int64 decision_deadline_unix_ms = 17;
}
Loading
Loading