diff --git a/CLAUDE.md b/CLAUDE.md index 2138970c..5b82f387 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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` plus per-entity repos in [src/Data/Repositories/](src/Data/Repositories/). Both `AddDbContext` (transient) **and** `AddDbContextFactory` 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. diff --git a/docker/e2e/README.md b/docker/e2e/README.md index 1ba02acd..757bb075 100644 --- a/docker/e2e/README.md +++ b/docker/e2e/README.md @@ -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]`. diff --git a/docker/e2e/docker-compose.yml b/docker/e2e/docker-compose.yml index eb71c498..8bbd3355 100644 --- a/docker/e2e/docker-compose.yml +++ b/docker/e2e/docker-compose.yml @@ -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" diff --git a/src/Data/Models/AuditLog.cs b/src/Data/Models/AuditLog.cs index 7230ed80..7d9756a5 100644 --- a/src/Data/Models/AuditLog.cs +++ b/src/Data/Models/AuditLog.cs @@ -165,7 +165,13 @@ public enum AuditActionType // Spark transit wallet alerts SparkBalanceStuck, - SparkExitOverdue + SparkExitOverdue, + + // Withdrawal interceptors (SubscribeWalletEvents with intercept_withdrawals) + WithdrawalInterceptorConnected, + WithdrawalInterceptorDisconnected, + WithdrawalAllowedByIntegrator, + WithdrawalBlockedByIntegrator } /// diff --git a/src/Helpers/Constants.cs b/src/Helpers/Constants.cs index 5673f35b..68fa2753 100644 --- a/src/Helpers/Constants.cs +++ b/src/Helpers/Constants.cs @@ -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"; @@ -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; diff --git a/src/Jobs/PerformWithdrawalJob.cs b/src/Jobs/PerformWithdrawalJob.cs index ba016d3c..37245751 100644 --- a/src/Jobs/PerformWithdrawalJob.cs +++ b/src/Jobs/PerformWithdrawalJob.cs @@ -27,7 +27,8 @@ namespace NodeGuard.Jobs; /// -/// 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. /// /// [DisallowConcurrentExecution] @@ -36,13 +37,23 @@ public class PerformWithdrawalJob : IJob private readonly ILogger _logger; private readonly IBitcoinService _bitcoinService; private readonly IWalletWithdrawalRequestRepository _walletWithdrawalRequestRepository; + private readonly IWithdrawalInterceptorGate _interceptorGate; + private readonly IWithdrawalRequestService _withdrawalRequestService; + private readonly IAuditService _auditService; - - public PerformWithdrawalJob(ILogger logger, IBitcoinService bitcoinService, IWalletWithdrawalRequestRepository walletWithdrawalRequestRepository) + public PerformWithdrawalJob(ILogger 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) @@ -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) { @@ -93,4 +109,57 @@ public async Task Execute(IJobExecutionContext context) _logger.LogInformation("{JobName} ended", nameof(PerformWithdrawalJob)); } + + /// + /// 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. + /// + private Task 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); + } + + /// + /// Rejects a request an integrator blocked, and reverts the request it was replacing, for an RBF replacement + /// + 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 + }; } diff --git a/src/Program.cs b/src/Program.cs index afb33e87..bab37ab8 100644 --- a/src/Program.cs +++ b/src/Program.cs @@ -170,6 +170,7 @@ public static async Task Main(string[] args) builder.Services.AddHostedService(); builder.Services.AddSingleton(); builder.Services.AddTransient(); + builder.Services.AddSingleton(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddScoped(); diff --git a/src/Proto/nodeguard.proto b/src/Proto/nodeguard.proto index d38a16c8..b1c6290f 100644 --- a/src/Proto/nodeguard.proto +++ b/src/Proto/nodeguard.proto @@ -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); } @@ -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 { @@ -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 { @@ -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; } diff --git a/src/Rpc/NodeGuardService.cs b/src/Rpc/NodeGuardService.cs index 4003ad9c..000309d2 100644 --- a/src/Rpc/NodeGuardService.cs +++ b/src/Rpc/NodeGuardService.cs @@ -108,6 +108,7 @@ public class NodeGuardService : Nodeguard.NodeGuardService.NodeGuardServiceBase, private readonly IAuditService _auditService; private readonly ISparkWalletService _sparkWallet; private readonly IWalletEventHub _walletEventHub; + private readonly IWithdrawalInterceptorGate _withdrawalInterceptorGate; private readonly TimeProvider _timeProvider; public NodeGuardService(ILogger logger, @@ -134,10 +135,12 @@ public NodeGuardService(ILogger logger, IAuditService auditService, ISparkWalletService sparkWallet, IWalletEventHub walletEventHub, + IWithdrawalInterceptorGate withdrawalInterceptorGate, TimeProvider timeProvider ) { _walletEventHub = walletEventHub; + _withdrawalInterceptorGate = withdrawalInterceptorGate; _timeProvider = timeProvider; _sparkWallet = sparkWallet; _swapsService = swapsService; @@ -1657,21 +1660,31 @@ public override async Task SubscribeWalletEvents(IAsyncStreamReader 0 && !types.Contains(walletEvent.Type)) + var alwaysSent = walletEvent.Type == WALLET_EVENT_TYPE.WalletEventWithdrawalDecisionRequested; + if (types.Count > 0 && !alwaysSent && !types.Contains(walletEvent.Type)) continue; await responseStream.WriteAsync(walletEvent); @@ -1689,6 +1702,63 @@ await responseStream.WriteAsync(new WalletEvent { // The client went away } + finally + { + await callEnded.CancelAsync(); + await reading; + + if (intercept) + { + await _auditService.LogAsync(AuditActionType.WithdrawalInterceptorDisconnected, AuditEventType.Success, + AuditObjectType.Wallet, wallet.Id.ToString(), new { Subscriber = subscriber, SubscriptionId = subscription.Id }); + } + } + } + + /// + /// Reads what the client sends after subscribing: an interceptor's decisions. An interceptor that half-closes can + /// no longer answer, so its subscription ends (the gate then treats any pending decision as blocked). + /// + private async Task ReadWalletEventsClientMessagesAsync(IAsyncStreamReader requestStream, + WalletEventSubscription subscription, CancellationToken cancellationToken) + { + try + { + while (await requestStream.MoveNext(cancellationToken)) + { + var message = requestStream.Current; + if (message.MessageCase != WalletEventsClientMessage.MessageOneofCase.Decision + || !subscription.InterceptWithdrawals) + { + _logger.LogWarning("Wallet events: ignored a {Message} message from {Subscriber} on wallet {WalletId}", + message.MessageCase, subscription.Subscriber, subscription.WalletId); + continue; + } + + var decision = message.Decision; + var reason = decision.HasReason ? decision.Reason : null; + if (!_withdrawalInterceptorGate.Decide(subscription.Id, decision.DecisionId, decision.Allow, reason)) + { + _logger.LogWarning( + "Wallet events: decision {DecisionId} from {Subscriber} on wallet {WalletId} matches no pending withdrawal (unknown, expired or already answered)", + decision.DecisionId, subscription.Subscriber, subscription.WalletId); + } + } + + if (subscription.InterceptWithdrawals) + subscription.Dispose(); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // The call ended + } + catch (Exception e) + { + _logger.LogWarning(e, "Wallet events: reading from {Subscriber} on wallet {WalletId} failed", + subscription.Subscriber, subscription.WalletId); + if (subscription.InterceptWithdrawals) + subscription.Dispose(); + } } /// diff --git a/src/Services/WalletEventHub.cs b/src/Services/WalletEventHub.cs index 06850f32..4c96f6cc 100644 --- a/src/Services/WalletEventHub.cs +++ b/src/Services/WalletEventHub.cs @@ -41,12 +41,14 @@ public sealed class WalletEventSubscription : IDisposable { private readonly Channel _channel; private readonly Action _unsubscribe; + private readonly CancellationTokenSource _closed = new(); - internal WalletEventSubscription(int walletId, string? subscriber, int capacity, + internal WalletEventSubscription(int walletId, string? subscriber, bool interceptWithdrawals, int capacity, Action unsubscribe) { WalletId = walletId; Subscriber = subscriber; + InterceptWithdrawals = interceptWithdrawals; _unsubscribe = unsubscribe; _channel = Channel.CreateBounded(new BoundedChannelOptions(capacity) { @@ -64,11 +66,31 @@ internal WalletEventSubscription(int walletId, string? subscriber, int capacity, /// public string? Subscriber { get; } + /// + /// The subscriber decides on this wallet's withdrawals before they are signed and broadcast + /// + public bool InterceptWithdrawals { get; } + public ChannelReader Reader => _channel.Reader; + /// + /// Cancelled once the subscription ends, whatever the reason + /// + public CancellationToken Closed => _closed.Token; + internal bool TryWrite(WalletEvent walletEvent) => _channel.Writer.TryWrite(walletEvent); - internal void Complete(Exception? error = null) => _channel.Writer.TryComplete(error); + internal void Complete(Exception? error = null) + { + _channel.Writer.TryComplete(error); + try + { + _closed.Cancel(); + } + catch (ObjectDisposedException) + { + } + } public void Dispose() { @@ -83,10 +105,21 @@ public void Dispose() /// public interface IWalletEventHub { - WalletEventSubscription Subscribe(int walletId, string? subscriber = null); + WalletEventSubscription Subscribe(int walletId, string? subscriber = null, bool interceptWithdrawals = false); bool HasSubscribers(int walletId); + /// + /// The open subscriptions that intercept the wallet's withdrawals + /// + IReadOnlyList GetInterceptors(int walletId); + + /// + /// Hands the event to one subscriber only, as does; false when that subscriber was full and + /// got disconnected, or is gone + /// + bool Send(WalletEventSubscription subscription, WalletEvent walletEvent); + /// /// Hands the event to every subscriber of its wallet without blocking: a subscriber whose buffer is full is /// disconnected with @@ -114,14 +147,15 @@ internal WalletEventHub(ILogger logger, IHostApplicationLifetime lifetime.ApplicationStopping.Register(CompleteAll); } - public WalletEventSubscription Subscribe(int walletId, string? subscriber = null) + public WalletEventSubscription Subscribe(int walletId, string? subscriber = null, bool interceptWithdrawals = false) { - var subscription = new WalletEventSubscription(walletId, subscriber, _capacity, Unsubscribe); + var subscription = new WalletEventSubscription(walletId, subscriber, interceptWithdrawals, _capacity, Unsubscribe); _subscriptions.GetOrAdd(walletId, _ => new ConcurrentDictionary()) [subscription.Id] = subscription; - _logger.LogInformation("Wallet events: {Subscriber} subscribed to wallet {WalletId} ({SubscriptionId})", - subscriber, walletId, subscription.Id); + _logger.LogInformation( + "Wallet events: {Subscriber} subscribed to wallet {WalletId} ({SubscriptionId}), intercepting withdrawals: {Intercept}", + subscriber, walletId, subscription.Id, interceptWithdrawals); return subscription; } @@ -129,22 +163,35 @@ public WalletEventSubscription Subscribe(int walletId, string? subscriber = null public bool HasSubscribers(int walletId) => _subscriptions.TryGetValue(walletId, out var subscriptions) && !subscriptions.IsEmpty; + public IReadOnlyList GetInterceptors(int walletId) => + _subscriptions.TryGetValue(walletId, out var subscriptions) + ? subscriptions.Values.Where(x => x.InterceptWithdrawals).ToList() + : []; + public void Publish(WalletEvent walletEvent) { if (!_subscriptions.TryGetValue(walletEvent.WalletId, out var subscriptions)) return; foreach (var subscription in subscriptions.Values) - { - if (subscription.TryWrite(walletEvent)) - continue; + Send(subscription, walletEvent); + } - _logger.LogWarning( - "Wallet events: {Subscriber} on wallet {WalletId} ({SubscriptionId}) is {Capacity} events behind; disconnecting it", - subscription.Subscriber, subscription.WalletId, subscription.Id, _capacity); - Unsubscribe(subscription); - subscription.Complete(new WalletEventSubscriberTooSlowException(_capacity)); - } + public bool Send(WalletEventSubscription subscription, WalletEvent walletEvent) + { + if (subscription.TryWrite(walletEvent)) + return true; + + // Already closed (unsubscribed, dropped, shutting down): nothing to disconnect + if (subscription.Closed.IsCancellationRequested) + return false; + + _logger.LogWarning( + "Wallet events: {Subscriber} on wallet {WalletId} ({SubscriptionId}) is {Capacity} events behind; disconnecting it", + subscription.Subscriber, subscription.WalletId, subscription.Id, _capacity); + Unsubscribe(subscription); + subscription.Complete(new WalletEventSubscriberTooSlowException(_capacity)); + return false; } private void Unsubscribe(WalletEventSubscription subscription) diff --git a/src/Services/WithdrawalInterceptorGate.cs b/src/Services/WithdrawalInterceptorGate.cs new file mode 100644 index 00000000..870fdc8d --- /dev/null +++ b/src/Services/WithdrawalInterceptorGate.cs @@ -0,0 +1,214 @@ +/* + * 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 System.Collections.Concurrent; +using NodeGuard.Data.Models; +using NodeGuard.Helpers; +using Nodeguard; + +namespace NodeGuard.Services; + +public enum WithdrawalInterceptOutcomeKind +{ + /// No interceptor is connected to the wallet: the check does not apply + Skipped, + Allowed, + Blocked +} + +/// Who was asked (subscriber names), empty when skipped +/// The interceptor whose answer (or silence) blocked the withdrawal +public record WithdrawalInterceptOutcome( + WithdrawalInterceptOutcomeKind Kind, + string? DecisionId, + IReadOnlyList Interceptors, + string? Reason = null, + string? DecidedBy = null) +{ + public static WithdrawalInterceptOutcome Skipped { get; } = new(WithdrawalInterceptOutcomeKind.Skipped, null, []); +} + +/// +/// Asks the integrators intercepting a wallet's withdrawals (SubscribeWalletEvents with intercept_withdrawals) to +/// allow or block one. Fail closed: a connected interceptor that blocks, does not answer in time or leaves first +/// blocks the withdrawal. With nobody intercepting, the check is skipped. +/// +public interface IWithdrawalInterceptorGate +{ + Task RequestDecisionAsync(WalletWithdrawalRequest request, + CancellationToken cancellationToken = default); + + /// + /// Records an interceptor's answer; false when there is no such pending decision for that subscription + /// (unknown, expired, already answered, or asked of another subscription) + /// + bool Decide(Guid subscriptionId, string decisionId, bool allow, string? reason); +} + +/// +/// Coordinates one withdrawal decision: asks every interceptor through its own and +/// applies the policy. The first block wins; the withdrawal is allowed only when every interceptor allows it. +/// +public class WithdrawalInterceptorGate : IWithdrawalInterceptorGate +{ + private sealed record Answer(bool Allow, string? Reason, string Subscriber); + + private readonly ConcurrentDictionary<(string DecisionId, Guid SubscriptionId), InterceptorDecision> _pending = new(); + + private readonly IWalletEventHub _hub; + private readonly TimeProvider _timeProvider; + private readonly ILogger _logger; + private readonly TimeSpan? _timeout; + + public WithdrawalInterceptorGate(IWalletEventHub hub, TimeProvider timeProvider, ILogger logger) + : this(hub, timeProvider, logger, null) + { + } + + internal WithdrawalInterceptorGate(IWalletEventHub hub, TimeProvider timeProvider, + ILogger logger, TimeSpan? timeout) + { + _hub = hub; + _timeProvider = timeProvider; + _logger = logger; + _timeout = timeout; + } + + private TimeSpan Timeout => _timeout ?? TimeSpan.FromSeconds(Constants.WITHDRAWAL_INTERCEPTOR_TIMEOUT_SECONDS); + + public async Task RequestDecisionAsync(WalletWithdrawalRequest request, + CancellationToken cancellationToken = default) + { + var interceptors = _hub.GetInterceptors(request.WalletId); + if (interceptors.Count == 0) + return WithdrawalInterceptOutcome.Skipped; + + var decisionId = Guid.NewGuid().ToString("N"); + var timeout = Timeout; + var now = _timeProvider.GetUtcNow(); + + var payload = WithdrawalEventMapper.ToWithdrawalEvent(request); + payload.DecisionId = decisionId; + payload.DecisionDeadlineUnixMs = (now + timeout).ToUnixTimeMilliseconds(); + var decisionRequested = new WalletEvent + { + Type = WALLET_EVENT_TYPE.WalletEventWithdrawalDecisionRequested, + WalletId = request.WalletId, + OccurredAtUnixMs = now.ToUnixTimeMilliseconds(), + Withdrawal = payload + }; + + var decisions = interceptors + .Select(x => new InterceptorDecision(this, decisionId, x, timeout, cancellationToken)) + .ToList(); + var names = decisions.Select(x => x.Subscriber).ToList(); + try + { + foreach (var decision in decisions) + decision.Ask(decisionRequested); + + _logger.LogInformation( + "Withdrawal request {RequestId} on wallet {WalletId} waits up to {Timeout} for {Interceptors} (decision {DecisionId})", + request.Id, request.WalletId, timeout, names, decisionId); + + var remaining = decisions.Select(x => x.Result).ToList(); + while (remaining.Count > 0) + { + var finished = await Task.WhenAny(remaining); + remaining.Remove(finished); + var answer = await finished; + if (!answer.Allow) + { + return new WithdrawalInterceptOutcome(WithdrawalInterceptOutcomeKind.Blocked, decisionId, names, + string.IsNullOrWhiteSpace(answer.Reason) ? "blocked by the integrator" : answer.Reason, + answer.Subscriber); + } + } + + return new WithdrawalInterceptOutcome(WithdrawalInterceptOutcomeKind.Allowed, decisionId, names); + } + finally + { + foreach (var decision in decisions) + await decision.DisposeAsync(); + } + } + + public bool Decide(Guid subscriptionId, string decisionId, bool allow, string? reason) => + _pending.TryGetValue((decisionId, subscriptionId), out var decision) && decision.Settle(allow, reason); + + /// + /// Asks one interceptor and always ends in an answer: its own, or a block when it cannot be reached, disconnects, + /// does not answer within the timeout, or NodeGuard stops waiting + /// + private sealed class InterceptorDecision : IAsyncDisposable + { + private readonly TaskCompletionSource _answer = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly WithdrawalInterceptorGate _gate; + private readonly (string DecisionId, Guid SubscriptionId) _key; + private readonly WalletEventSubscription _interceptor; + private readonly TimeSpan _timeout; + private readonly CancellationToken _cancellationToken; + private readonly List _registrations = []; + private CancellationTokenSource? _deadline; + + public InterceptorDecision(WithdrawalInterceptorGate gate, string decisionId, + WalletEventSubscription interceptor, TimeSpan timeout, CancellationToken cancellationToken) + { + _gate = gate; + _key = (decisionId, interceptor.Id); + _interceptor = interceptor; + _timeout = timeout; + _cancellationToken = cancellationToken; + Subscriber = interceptor.Subscriber ?? interceptor.Id.ToString(); + } + + public string Subscriber { get; } + + public Task Result => _answer.Task; + + public void Ask(WalletEvent decisionRequested) + { + // Registered before sending, so an answer that comes back at once finds its decision + _gate._pending[_key] = this; + + _deadline = new CancellationTokenSource(_timeout, _gate._timeProvider); + _registrations.Add(_deadline.Token.Register(() => + Settle(false, $"no decision from the integrator within {_timeout.TotalSeconds:0}s"))); + _registrations.Add(_cancellationToken.Register(() => + Settle(false, "NodeGuard stopped waiting before the integrator decided"))); + _registrations.Add(_interceptor.Closed.Register(() => + Settle(false, "the integrator disconnected before deciding"))); + + if (!_gate._hub.Send(_interceptor, decisionRequested)) + Settle(false, "the integrator could not be reached"); + } + + /// Settles the decision; false when it was already settled + public bool Settle(bool allow, string? reason) => _answer.TrySetResult(new Answer(allow, reason, Subscriber)); + + public async ValueTask DisposeAsync() + { + _gate._pending.TryRemove(_key, out _); + foreach (var registration in _registrations) + await registration.DisposeAsync(); + _deadline?.Dispose(); + } + } +} diff --git a/test/NodeGuard.Tests/E2E/WalletEventsE2ETests.cs b/test/NodeGuard.Tests/E2E/WalletEventsE2ETests.cs index f5987000..93964448 100644 --- a/test/NodeGuard.Tests/E2E/WalletEventsE2ETests.cs +++ b/test/NodeGuard.Tests/E2E/WalletEventsE2ETests.cs @@ -154,6 +154,121 @@ await call.RequestStream.WriteAsync(new WalletEventsClientMessage (await act.Should().ThrowAsync()).Which.StatusCode.Should().Be(StatusCode.NotFound); } + // ---- withdrawal interceptor ----------------------------------------------------------------------------------- + + [E2EFact] + public async Task Interceptor_AllowsAWithdrawal_ThatIsThenBroadcast() + { + var client = CreateClient(out var headers); + var rpc = CreateBitcoindRpc(); + var walletId = await EnsureHotWalletReadyAsync(client, headers); + await using var integrator = await WalletEventStream.OpenAsync(client, headers, walletId, _output, interceptWithdrawals: true); + + var destination = await rpc.GetNewAddressAsync(); + var withdrawal = await RequestHotWithdrawalAsync(client, headers, walletId, destination, "E2E interceptor allows"); + + var asked = await integrator.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalDecisionRequested); + asked.Withdrawal.Destinations.Should().ContainSingle(d => + d.Address == destination.ToString() && d.AmountSats == WithdrawalAmountSats); + asked.Withdrawal.DecisionDeadlineUnixMs.Should().BeGreaterThan(asked.OccurredAtUnixMs); + await integrator.DecideAsync(asked, allow: true); + + var broadcast = await integrator.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalBroadcast); + (await rpc.GetRawTransactionAsync(uint256.Parse(broadcast.Withdrawal.TxId), throwIfNotFound: false)) + .Should().NotBeNull(); + + await MineAsync(rpc, 6); + await integrator.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalConfirmed, TimeSpan.FromMinutes(3)); + } + + [E2EFact] + public async Task Interceptor_BlocksAWithdrawal_ThatIsRejectedAndNeverBroadcast() + { + var client = CreateClient(out var headers); + var rpc = CreateBitcoindRpc(); + var walletId = await EnsureHotWalletReadyAsync(client, headers); + await using var integrator = await WalletEventStream.OpenAsync(client, headers, walletId, _output, interceptWithdrawals: true); + + var withdrawal = await RequestHotWithdrawalAsync(client, headers, walletId, await rpc.GetNewAddressAsync(), + "E2E interceptor blocks"); + var asked = await integrator.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalDecisionRequested); + await integrator.DecideAsync(asked, allow: false, reason: "destination failed screening"); + + var rejected = await integrator.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalRejected); + rejected.Withdrawal.RejectOrCancelReason.Should().Contain("destination failed screening"); + await AssertNeverBroadcastAsync(client, headers, rpc, withdrawal); + integrator.Seen(withdrawal.RequestId).Should().NotContain(WALLET_EVENT_TYPE.WalletEventWithdrawalSigning, + "a blocked withdrawal is never signed"); + } + + [E2EFact] + public async Task Interceptor_ThatDoesNotAnswer_BlocksTheWithdrawalAtTheDeadline() + { + var client = CreateClient(out var headers); + var rpc = CreateBitcoindRpc(); + var walletId = await EnsureHotWalletReadyAsync(client, headers); + await using var integrator = await WalletEventStream.OpenAsync(client, headers, walletId, _output, interceptWithdrawals: true); + + var withdrawal = await RequestHotWithdrawalAsync(client, headers, walletId, await rpc.GetNewAddressAsync(), + "E2E interceptor silent"); + await integrator.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalDecisionRequested); + + // No answer: WITHDRAWAL_INTERCEPTOR_TIMEOUT_SECONDS is 10s in the e2e stack + var rejected = await integrator.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalRejected, + TimeSpan.FromSeconds(60)); + rejected.Withdrawal.RejectOrCancelReason.Should().Contain("no decision"); + await AssertNeverBroadcastAsync(client, headers, rpc, withdrawal); + } + + [E2EFact] + public async Task Interceptor_BlocksAFeeBump_AndTheOriginalWaitsForConfirmationAgain() + { + var client = CreateClient(out var headers); + var rpc = CreateBitcoindRpc(); + var walletId = await EnsureHotWalletReadyAsync(client, headers); + await using var integrator = await WalletEventStream.OpenAsync(client, headers, walletId, _output, interceptWithdrawals: true); + + var withdrawal = await RequestHotWithdrawalAsync(client, headers, walletId, await rpc.GetNewAddressAsync(), + "E2E interceptor blocks bump"); + await integrator.DecideAsync( + await integrator.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalDecisionRequested), + allow: true); + await integrator.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalBroadcast); + + var bump = await client.BumpWithdrawalAsync(new BumpWithdrawalRequest + { + RequestId = withdrawal.RequestId, + MempoolFeeRate = FEES_TYPE.CustomFee, + CustomFeeRate = BumpedFeeRateSatPerVb, + }, headers); + var askedBump = await integrator.NextAsync(bump.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalDecisionRequested); + askedBump.Withdrawal.BumpingRequestId.Should().Be(withdrawal.RequestId); + await integrator.DecideAsync(askedBump, allow: false, reason: "no fee bumps today"); + + await integrator.NextAsync(bump.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalRejected); + var reverted = await integrator.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalReplacementReverted); + reverted.Withdrawal.Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingConfirmation); + (await rpc.GetMempoolEntryAsync(uint256.Parse(withdrawal.Txid), throwIfNotFound: false)) + .Should().NotBeNull("the original stays in the mempool when its replacement is blocked"); + + await MineAsync(rpc, 6); + await integrator.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalConfirmed, TimeSpan.FromMinutes(3)); + } + + private async Task AssertNeverBroadcastAsync(NodeGuardService.NodeGuardServiceClient client, Metadata headers, + RPCClient rpc, RequestWithdrawalResponse withdrawal) + { + var status = await client.GetWithdrawalsRequestStatusAsync( + new GetWithdrawalsRequestStatusRequest { RequestIds = { withdrawal.RequestId } }, headers); + status.WithdrawalRequests.Should().ContainSingle().Which.Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalRejected); + + if (!string.IsNullOrEmpty(withdrawal.Txid)) + { + (await rpc.GetRawTransactionAsync(uint256.Parse(withdrawal.Txid), throwIfNotFound: false)) + .Should().BeNull("a blocked withdrawal is never broadcast"); + } + } + // ---- plumbing ------------------------------------------------------------------------------------------------ /// @@ -192,12 +307,16 @@ private WalletEventStream(AsyncDuplexStreamingCall OpenAsync(NodeGuardService.NodeGuardServiceClient client, - Metadata headers, int walletId, ITestOutputHelper output) + Metadata headers, int walletId, ITestOutputHelper output, bool interceptWithdrawals = false) { var stream = new WalletEventStream(client.SubscribeWalletEvents(headers), output); await stream._call.RequestStream.WriteAsync(new WalletEventsClientMessage { - Subscribe = new SubscribeWalletEventsRequest { WalletId = walletId } + Subscribe = new SubscribeWalletEventsRequest + { + WalletId = walletId, + InterceptWithdrawals = interceptWithdrawals + } }); var subscribed = await stream.NextAsync(e => e.Type == WALLET_EVENT_TYPE.WalletEventSubscribed, TimeSpan.FromSeconds(30), "subscribed"); @@ -209,6 +328,14 @@ public Task NextAsync(int requestId, WALLET_EVENT_TYPE type, TimeSp NextAsync(e => e.Type == type && e.Withdrawal?.RequestId == requestId, timeout ?? TimeSpan.FromMinutes(2), $"{type} for request {requestId}"); + /// Answers a WALLET_EVENT_WITHDRAWAL_DECISION_REQUESTED + public Task DecideAsync(WalletEvent decisionRequested, bool allow, string? reason = null) + { + var decision = new WithdrawalDecision { DecisionId = decisionRequested.Withdrawal.DecisionId, Allow = allow }; + if (reason != null) decision.Reason = reason; + return _call.RequestStream.WriteAsync(new WalletEventsClientMessage { Decision = decision }); + } + public List Seen(int requestId) { lock (_all) return _all.Where(e => e.Withdrawal?.RequestId == requestId).Select(e => e.Type).ToList(); diff --git a/test/NodeGuard.Tests/Jobs/PerformWithdrawalJobTests.cs b/test/NodeGuard.Tests/Jobs/PerformWithdrawalJobTests.cs new file mode 100644 index 00000000..e58421ed --- /dev/null +++ b/test/NodeGuard.Tests/Jobs/PerformWithdrawalJobTests.cs @@ -0,0 +1,139 @@ +/* + * 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 NodeGuard.Data.Models; +using NodeGuard.Data.Repositories.Interfaces; +using NodeGuard.Services; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using Quartz; + +namespace NodeGuard.Jobs; + +public class PerformWithdrawalJobTests +{ + private const int RequestId = 12; + + private readonly IBitcoinService _bitcoinService = Substitute.For(); + private readonly IWalletWithdrawalRequestRepository _repository = Substitute.For(); + private readonly IWithdrawalInterceptorGate _gate = Substitute.For(); + private readonly IWithdrawalRequestService _withdrawalRequestService = Substitute.For(); + private readonly IAuditService _auditService = Substitute.For(); + private readonly IJobExecutionContext _context = Substitute.For(); + private readonly PerformWithdrawalJob _job; + private readonly WalletWithdrawalRequest _request = new() + { + Id = RequestId, + WalletId = 4, + Status = WalletWithdrawalRequestStatus.PSBTSignaturesPending, + BumpingWalletWithdrawalRequestId = 11 + }; + + public PerformWithdrawalJobTests() + { + var jobDetail = Substitute.For(); + jobDetail.JobDataMap.Returns(new JobDataMap { { "withdrawalRequestId", RequestId } }); + _context.JobDetail.Returns(jobDetail); + _repository.GetById(RequestId).Returns(_request); + _repository.Update(Arg.Any()).Returns((true, null)); + + _job = new PerformWithdrawalJob(NullLogger.Instance, _bitcoinService, _repository, _gate, + _withdrawalRequestService, _auditService); + } + + private void GateAnswers(WithdrawalInterceptOutcome outcome) => + _gate.RequestDecisionAsync(_request, Arg.Any()).Returns(outcome); + + [Fact] + public async Task Execute_NobodyIntercepting_PerformsTheWithdrawal() + { + GateAnswers(WithdrawalInterceptOutcome.Skipped); + + await _job.Execute(_context); + + await _bitcoinService.Received(1).PerformWithdrawal(_request); + await _auditService.DidNotReceiveWithAnyArgs().LogSystemAsync(default, default, default); + } + + [Fact] + public async Task Execute_IntegratorAllows_PerformsTheWithdrawalAndAuditsIt() + { + GateAnswers(new WithdrawalInterceptOutcome(WithdrawalInterceptOutcomeKind.Allowed, "d1", ["integrator"])); + + await _job.Execute(_context); + + await _bitcoinService.Received(1).PerformWithdrawal(_request); + await _auditService.Received(1).LogSystemAsync(AuditActionType.WithdrawalAllowedByIntegrator, + AuditEventType.Success, AuditObjectType.WalletWithdrawalRequest, RequestId.ToString(), Arg.Any()); + } + + [Fact] + public async Task Execute_IntegratorBlocks_RejectsWithoutSigningAndRevertsTheOriginal() + { + GateAnswers(new WithdrawalInterceptOutcome(WithdrawalInterceptOutcomeKind.Blocked, "d1", ["compliance"], + "sanctioned address", "compliance")); + + await _job.Execute(_context); + + await _bitcoinService.DidNotReceiveWithAnyArgs().PerformWithdrawal(default!); + _request.Status.Should().Be(WalletWithdrawalRequestStatus.Rejected); + _request.RejectCancelDescription.Should().Be("Blocked by integrator 'compliance': sanctioned address"); + _repository.Received(1).Update(_request); + await _withdrawalRequestService.Received(1).RevertOriginalAsync(_request); + await _auditService.Received(1).LogSystemAsync(AuditActionType.WithdrawalBlockedByIntegrator, + AuditEventType.Success, AuditObjectType.WalletWithdrawalRequest, RequestId.ToString(), Arg.Any()); + } + + [Fact] + public async Task Execute_BlockedButNotPersisted_NeverSignsAndFailsTheRequest() + { + GateAnswers(new WithdrawalInterceptOutcome(WithdrawalInterceptOutcomeKind.Blocked, "d1", ["compliance"], "no", "compliance")); + _repository.Update(Arg.Is(r => r.Status == WalletWithdrawalRequestStatus.Rejected)) + .Returns((false, "db down")); + + await _job.Execute(_context); + + await _bitcoinService.DidNotReceiveWithAnyArgs().PerformWithdrawal(default!); + _request.Status.Should().Be(WalletWithdrawalRequestStatus.Failed); + } + + [Fact] + public async Task Execute_RequestNotReadyToSign_IsNotPutToTheIntegrators() + { + _request.Status = WalletWithdrawalRequestStatus.Pending; + + await _job.Execute(_context); + + await _gate.DidNotReceiveWithAnyArgs().RequestDecisionAsync(default!, default); + } + + [Fact] + public async Task Execute_SigningFails_RevertsTheOriginalAndFailsTheRequest() + { + GateAnswers(WithdrawalInterceptOutcome.Skipped); + _bitcoinService.PerformWithdrawal(_request).ThrowsAsync(new InvalidOperationException("signer down")); + + await _job.Execute(_context); + + await _withdrawalRequestService.Received(1).RevertOriginalAsync(_request); + _request.Status.Should().Be(WalletWithdrawalRequestStatus.Failed); + } +} diff --git a/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs b/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs index d56e066d..d963b27a 100644 --- a/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs +++ b/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs @@ -87,7 +87,8 @@ private NodeGuardService CreateNodeGuardService( ISwapOutRepository? swapOutRepository = null, IAuditService? auditService = null, ISparkWalletService? sparkWallet = null, - IWalletEventHub? walletEventHub = null) + IWalletEventHub? walletEventHub = null, + IWithdrawalInterceptorGate? withdrawalInterceptorGate = null) { return new NodeGuardService( logger ?? _logger.Object, @@ -114,6 +115,7 @@ private NodeGuardService CreateNodeGuardService( auditService ?? new Mock().Object, sparkWallet ?? new Mock().Object, walletEventHub ?? new Mock().Object, + withdrawalInterceptorGate ?? new Mock().Object, TimeProvider.System); } @@ -2596,7 +2598,10 @@ public Task Start() => Service.SubscribeWalletEvents(Requests, Responses, TestServerCallContext.Create(cancellationToken: ClientCancellation.Token)); } - private WalletEventsCall WalletEventsCallFor(params Wallet[] wallets) + private WalletEventsCall WalletEventsCallFor(params Wallet[] wallets) => WalletEventsCallFor(null, null, wallets); + + private WalletEventsCall WalletEventsCallFor(IWithdrawalInterceptorGate? gate, IAuditService? auditService, + params Wallet[] wallets) { var walletRepository = new Mock(); foreach (var wallet in wallets) @@ -2609,7 +2614,8 @@ private WalletEventsCall WalletEventsCallFor(params Wallet[] wallets) return new WalletEventsCall { - Service = CreateNodeGuardService(walletRepository: walletRepository.Object, walletEventHub: hub), + Service = CreateNodeGuardService(walletRepository: walletRepository.Object, walletEventHub: hub, + withdrawalInterceptorGate: gate, auditService: auditService), Hub = hub, Stopping = stopping }; @@ -2620,6 +2626,21 @@ private WalletEventsCall WalletEventsCallFor(params Wallet[] wallets) Subscribe = new SubscribeWalletEventsRequest { WalletId = walletId, EventTypes = { types } } }; + private static WalletEventsClientMessage Intercept(int walletId, params WALLET_EVENT_TYPE[] types) => new() + { + Subscribe = new SubscribeWalletEventsRequest + { + WalletId = walletId, EventTypes = { types }, InterceptWithdrawals = true + } + }; + + private static WalletEventsClientMessage Decision(string decisionId, bool allow, string? reason = null) + { + var decision = new WithdrawalDecision { DecisionId = decisionId, Allow = allow }; + if (reason != null) decision.Reason = reason; + return new WalletEventsClientMessage { Decision = decision }; + } + private static WalletEvent WithdrawalEvent(int walletId, WALLET_EVENT_TYPE type, int requestId) => new() { Type = type, @@ -2719,5 +2740,75 @@ public async Task SubscribeWalletEvents_Shutdown_EndsTheCallAsUnavailable() (await running.Invoking(t => t.WaitAsync(TimeSpan.FromSeconds(5))).Should().ThrowAsync()) .Which.StatusCode.Should().Be(StatusCode.Unavailable); } + + [Fact] + public async Task SubscribeWalletEvents_Interceptor_RoutesDecisionsToTheGateAndAuditsTheConnection() + { + var gate = new Mock(); + var decided = new TaskCompletionSource<(Guid, string, bool, string?)>(); + gate.Setup(x => x.Decide(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((id, decisionId, allow, reason) => decided.TrySetResult((id, decisionId, allow, reason))) + .Returns(true); + var audit = new Mock(); + var call = WalletEventsCallFor(gate.Object, audit.Object, new Wallet { Id = 1 }); + call.Requests.Add(Intercept(1)); + var running = call.Start(); + (await call.Responses.ReadNextAsync()).Type.Should().Be(WALLET_EVENT_TYPE.WalletEventSubscribed); + var interceptor = call.Hub.GetInterceptors(1).Should().ContainSingle().Subject; + + call.Requests.Add(Decision("d-1", allow: false, reason: "sanctioned")); + + var (subscriptionId, decisionId, allowed, why) = await decided.Task.WaitAsync(TimeSpan.FromSeconds(5)); + subscriptionId.Should().Be(interceptor.Id); + decisionId.Should().Be("d-1"); + allowed.Should().BeFalse(); + why.Should().Be("sanctioned"); + + // Half-closing ends an interceptor's call: it can no longer answer + call.Requests.Complete(); + await running.WaitAsync(TimeSpan.FromSeconds(5)); + call.Hub.GetInterceptors(1).Should().BeEmpty(); + audit.Verify(x => x.LogAsync(AuditActionType.WithdrawalInterceptorConnected, AuditEventType.Success, + AuditObjectType.Wallet, "1", It.IsAny()), Times.Once); + audit.Verify(x => x.LogAsync(AuditActionType.WithdrawalInterceptorDisconnected, AuditEventType.Success, + AuditObjectType.Wallet, "1", It.IsAny()), Times.Once); + } + + [Fact] + public async Task SubscribeWalletEvents_Observer_CannotDecideAndIsNotAnInterceptor() + { + var gate = new Mock(); + var call = WalletEventsCallFor(gate.Object, null, new Wallet { Id = 1 }); + call.Requests.Add(Subscribe(1)); + var running = call.Start(); + (await call.Responses.ReadNextAsync()).Type.Should().Be(WALLET_EVENT_TYPE.WalletEventSubscribed); + + call.Hub.GetInterceptors(1).Should().BeEmpty(); + call.Requests.Add(Decision("d-1", allow: true)); + call.Requests.Complete(); + + (await call.Responses.NothingMoreWrittenAsync()).Should().BeTrue(); + running.IsCompleted.Should().BeFalse("an observer that half-closes keeps receiving events"); + gate.Verify(x => x.Decide(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + + await call.ClientCancellation.CancelAsync(); + await running.WaitAsync(TimeSpan.FromSeconds(5)); + } + + [Fact] + public async Task SubscribeWalletEvents_Interceptor_GetsDecisionRequestsWhateverItsFilter() + { + var call = WalletEventsCallFor(new Mock().Object, null, new Wallet { Id = 1 }); + call.Requests.Add(Intercept(1, WALLET_EVENT_TYPE.WalletEventWithdrawalConfirmed)); + var running = call.Start(); + (await call.Responses.ReadNextAsync()).Type.Should().Be(WALLET_EVENT_TYPE.WalletEventSubscribed); + + call.Hub.Publish(WithdrawalEvent(1, WALLET_EVENT_TYPE.WalletEventWithdrawalDecisionRequested, 10)); + + (await call.Responses.ReadNextAsync()).Type.Should().Be(WALLET_EVENT_TYPE.WalletEventWithdrawalDecisionRequested); + + await call.ClientCancellation.CancelAsync(); + await running.WaitAsync(TimeSpan.FromSeconds(5)); + } } } diff --git a/test/NodeGuard.Tests/Services/WalletEventHubTests.cs b/test/NodeGuard.Tests/Services/WalletEventHubTests.cs index 2604d35c..059ebe65 100644 --- a/test/NodeGuard.Tests/Services/WalletEventHubTests.cs +++ b/test/NodeGuard.Tests/Services/WalletEventHubTests.cs @@ -128,4 +128,43 @@ public async Task ApplicationStopping_ClosesEverySubscription() hub.HasSubscribers(1).Should().BeFalse(); hub.HasSubscribers(2).Should().BeFalse(); } + + [Fact] + public void GetInterceptors_ListsOnlyInterceptingSubscriptionsOfTheWallet() + { + var hub = CreateHub(); + using var observer = hub.Subscribe(1, "observer"); + using var interceptor = hub.Subscribe(1, "integrator", interceptWithdrawals: true); + using var elsewhere = hub.Subscribe(2, "other", interceptWithdrawals: true); + + hub.GetInterceptors(1).Should().ContainSingle().Which.Should().BeSameAs(interceptor); + hub.GetInterceptors(3).Should().BeEmpty(); + } + + [Fact] + public void Send_ReachesOnlyThatSubscription() + { + var hub = CreateHub(); + using var target = hub.Subscribe(1, interceptWithdrawals: true); + using var other = hub.Subscribe(1); + + hub.Send(target, Event(1)).Should().BeTrue(); + + target.Reader.TryRead(out _).Should().BeTrue(); + other.Reader.TryRead(out _).Should().BeFalse(); + } + + [Fact] + public void Closed_FiresWhenTheSubscriptionEnds_AndSendThenFails() + { + var hub = CreateHub(); + var subscription = hub.Subscribe(1, interceptWithdrawals: true); + subscription.Closed.IsCancellationRequested.Should().BeFalse(); + + subscription.Dispose(); + + subscription.Closed.IsCancellationRequested.Should().BeTrue(); + hub.Send(subscription, Event(1)).Should().BeFalse(); + } } + diff --git a/test/NodeGuard.Tests/Services/WithdrawalInterceptorGateTests.cs b/test/NodeGuard.Tests/Services/WithdrawalInterceptorGateTests.cs new file mode 100644 index 00000000..b1691fc2 --- /dev/null +++ b/test/NodeGuard.Tests/Services/WithdrawalInterceptorGateTests.cs @@ -0,0 +1,194 @@ +/* + * 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.Hosting; +using Microsoft.Extensions.Logging.Abstractions; +using NodeGuard.Data.Models; +using Nodeguard; +using NSubstitute; +using Wallet = NodeGuard.Data.Models.Wallet; + +namespace NodeGuard.Services; + +public class WithdrawalInterceptorGateTests +{ + private const int WalletId = 9; + + private readonly WalletEventHub _hub; + + public WithdrawalInterceptorGateTests() + { + var lifetime = Substitute.For(); + lifetime.ApplicationStopping.Returns(CancellationToken.None); + _hub = new WalletEventHub(NullLogger.Instance, lifetime); + } + + private WithdrawalInterceptorGate Gate(TimeSpan? timeout = null) => + new(_hub, TimeProvider.System, NullLogger.Instance, timeout ?? TimeSpan.FromSeconds(10)); + + private static WalletWithdrawalRequest Request() => new() + { + Id = 77, + WalletId = WalletId, + Status = WalletWithdrawalRequestStatus.PSBTSignaturesPending, + Wallet = new Wallet { Id = WalletId, IsHotWallet = true }, + WalletWithdrawalRequestDestinations = [new() { Address = "bcrt1qdest", Amount = 0.01m }] + }; + + /// Waits for the decision request the gate sends to this interceptor + private static async Task DecisionRequestedAsync(WalletEventSubscription interceptor) + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + var e = await interceptor.Reader.ReadAsync(cts.Token); + e.Type.Should().Be(WALLET_EVENT_TYPE.WalletEventWithdrawalDecisionRequested); + return e; + } + + [Fact] + public async Task RequestDecision_NoInterceptor_IsSkippedAndObserversAreNotAsked() + { + using var observer = _hub.Subscribe(WalletId, "observer"); + + var outcome = await Gate().RequestDecisionAsync(Request()); + + outcome.Kind.Should().Be(WithdrawalInterceptOutcomeKind.Skipped); + observer.Reader.TryRead(out _).Should().BeFalse(); + } + + [Fact] + public async Task RequestDecision_InterceptorAllows_IsAllowed() + { + using var interceptor = _hub.Subscribe(WalletId, "integrator", interceptWithdrawals: true); + var gate = Gate(); + + var pending = gate.RequestDecisionAsync(Request()); + var asked = await DecisionRequestedAsync(interceptor); + asked.Withdrawal.RequestId.Should().Be(77); + asked.Withdrawal.AmountSats.Should().Be(1_000_000); + asked.Withdrawal.Destinations.Should().ContainSingle(d => d.Address == "bcrt1qdest"); + asked.Withdrawal.HasDecisionDeadlineUnixMs.Should().BeTrue(); + + gate.Decide(interceptor.Id, asked.Withdrawal.DecisionId, allow: true, reason: null).Should().BeTrue(); + + var outcome = await pending; + outcome.Kind.Should().Be(WithdrawalInterceptOutcomeKind.Allowed); + outcome.DecisionId.Should().Be(asked.Withdrawal.DecisionId); + outcome.Interceptors.Should().Equal("integrator"); + } + + [Fact] + public async Task RequestDecision_AnyInterceptorBlocks_IsBlockedWithItsReason() + { + using var allowing = _hub.Subscribe(WalletId, "treasury", interceptWithdrawals: true); + using var blocking = _hub.Subscribe(WalletId, "compliance", interceptWithdrawals: true); + var gate = Gate(); + + var pending = gate.RequestDecisionAsync(Request()); + var askedAllowing = await DecisionRequestedAsync(allowing); + var askedBlocking = await DecisionRequestedAsync(blocking); + askedBlocking.Withdrawal.DecisionId.Should().Be(askedAllowing.Withdrawal.DecisionId); + + gate.Decide(allowing.Id, askedAllowing.Withdrawal.DecisionId, true, null); + gate.Decide(blocking.Id, askedBlocking.Withdrawal.DecisionId, false, "sanctioned address"); + + var outcome = await pending; + outcome.Kind.Should().Be(WithdrawalInterceptOutcomeKind.Blocked); + outcome.Reason.Should().Be("sanctioned address"); + outcome.DecidedBy.Should().Be("compliance"); + } + + [Fact] + public async Task RequestDecision_OneBlocksWhileAnotherIsSilent_BlocksWithoutWaitingForTheTimeout() + { + using var silent = _hub.Subscribe(WalletId, "sleepy", interceptWithdrawals: true); + using var blocking = _hub.Subscribe(WalletId, "compliance", interceptWithdrawals: true); + var gate = Gate(TimeSpan.FromMinutes(5)); + + var pending = gate.RequestDecisionAsync(Request()); + var asked = await DecisionRequestedAsync(blocking); + gate.Decide(blocking.Id, asked.Withdrawal.DecisionId, false, "sanctioned address"); + + var outcome = await pending.WaitAsync(TimeSpan.FromSeconds(5)); + outcome.Kind.Should().Be(WithdrawalInterceptOutcomeKind.Blocked); + outcome.DecidedBy.Should().Be("compliance"); + outcome.Interceptors.Should().BeEquivalentTo("sleepy", "compliance"); + gate.Decide(silent.Id, asked.Withdrawal.DecisionId, true, null).Should().BeFalse("the decision is closed"); + } + + [Fact] + public async Task RequestDecision_NoAnswerInTime_IsBlocked() + { + using var interceptor = _hub.Subscribe(WalletId, "sleepy", interceptWithdrawals: true); + + var outcome = await Gate(TimeSpan.FromMilliseconds(200)).RequestDecisionAsync(Request()); + + outcome.Kind.Should().Be(WithdrawalInterceptOutcomeKind.Blocked); + outcome.Reason.Should().Contain("no decision"); + outcome.DecidedBy.Should().Be("sleepy"); + } + + [Fact] + public async Task RequestDecision_InterceptorLeavesBeforeAnswering_IsBlocked() + { + var interceptor = _hub.Subscribe(WalletId, "flaky", interceptWithdrawals: true); + var gate = Gate(); + + var pending = gate.RequestDecisionAsync(Request()); + await DecisionRequestedAsync(interceptor); + interceptor.Dispose(); + + var outcome = await pending.WaitAsync(TimeSpan.FromSeconds(5)); + outcome.Kind.Should().Be(WithdrawalInterceptOutcomeKind.Blocked); + outcome.Reason.Should().Contain("disconnected"); + outcome.DecidedBy.Should().Be("flaky"); + } + + [Fact] + public async Task RequestDecision_Cancelled_IsBlocked() + { + using var interceptor = _hub.Subscribe(WalletId, "integrator", interceptWithdrawals: true); + using var cts = new CancellationTokenSource(); + + var pending = Gate().RequestDecisionAsync(Request(), cts.Token); + await DecisionRequestedAsync(interceptor); + await cts.CancelAsync(); + + var outcome = await pending.WaitAsync(TimeSpan.FromSeconds(5)); + outcome.Kind.Should().Be(WithdrawalInterceptOutcomeKind.Blocked); + outcome.Reason.Should().Contain("stopped waiting"); + } + + [Fact] + public async Task Decide_OnlyMatchesTheSubscriptionThatWasAsked_AndOnlyOnce() + { + using var interceptor = _hub.Subscribe(WalletId, "integrator", interceptWithdrawals: true); + using var stranger = _hub.Subscribe(WalletId + 1, "other wallet", interceptWithdrawals: true); + var gate = Gate(); + + var pending = gate.RequestDecisionAsync(Request()); + var decisionId = (await DecisionRequestedAsync(interceptor)).Withdrawal.DecisionId; + + gate.Decide(interceptor.Id, "not-a-decision", true, null).Should().BeFalse(); + gate.Decide(stranger.Id, decisionId, true, null).Should().BeFalse(); + gate.Decide(interceptor.Id, decisionId, true, null).Should().BeTrue(); + (await pending).Kind.Should().Be(WithdrawalInterceptOutcomeKind.Allowed); + gate.Decide(interceptor.Id, decisionId, false, "too late").Should().BeFalse("the decision is closed"); + } +}