diff --git a/CLAUDE.md b/CLAUDE.md index f0e02f55..2138970c 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. 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. 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/src/Data/Repositories/WalletWithdrawalRequestPsbtRepository.cs b/src/Data/Repositories/WalletWithdrawalRequestPsbtRepository.cs index e0d25a68..b6223c72 100644 --- a/src/Data/Repositories/WalletWithdrawalRequestPsbtRepository.cs +++ b/src/Data/Repositories/WalletWithdrawalRequestPsbtRepository.cs @@ -22,6 +22,7 @@ using Microsoft.EntityFrameworkCore; using NBitcoin; using NodeGuard.Helpers; +using NodeGuard.Services; using Npgsql; namespace NodeGuard.Data.Repositories @@ -37,11 +38,14 @@ public class WalletWithdrawalRequestPsbtRepository : IWalletWithdrawalRequestPsb private readonly IRepository _repository; private readonly ILogger _logger; private readonly IDbContextFactory _dbContextFactory; + private readonly IWithdrawalEventPublisher _withdrawalEventPublisher; public WalletWithdrawalRequestPsbtRepository(IRepository repository, ILogger logger, - IDbContextFactory dbContextFactory) + IDbContextFactory dbContextFactory, + IWithdrawalEventPublisher withdrawalEventPublisher) { + _withdrawalEventPublisher = withdrawalEventPublisher; _repository = repository; _logger = logger; _dbContextFactory = dbContextFactory; @@ -115,7 +119,11 @@ public async Task> GetAll() return (false, null); } - return await _repository.AddAsync(type, applicationDbContext); + var added = await _repository.AddAsync(type, applicationDbContext); + if (added.Item1 && request != null && !type.IsInternalWalletPSBT && !type.IsFinalisedPSBT) + _withdrawalEventPublisher.PublishSignatureAdded(request.WalletId, request.Id); + + return added; } /// diff --git a/src/Data/Repositories/WalletWithdrawalRequestRepository.cs b/src/Data/Repositories/WalletWithdrawalRequestRepository.cs index 9f2a2079..e0781e81 100644 --- a/src/Data/Repositories/WalletWithdrawalRequestRepository.cs +++ b/src/Data/Repositories/WalletWithdrawalRequestRepository.cs @@ -36,15 +36,18 @@ public class WalletWithdrawalRequestRepository : IWalletWithdrawalRequestReposit private readonly IMapper _mapper; private readonly NotificationService _notificationService; private readonly INBXplorerService _nBXplorerService; + private readonly IWithdrawalEventPublisher _withdrawalEventPublisher; public WalletWithdrawalRequestRepository(IRepository repository, ILogger logger, IDbContextFactory dbContextFactory, IMapper mapper, NotificationService notificationService, - INBXplorerService nBXplorerService + INBXplorerService nBXplorerService, + IWithdrawalEventPublisher withdrawalEventPublisher ) { + _withdrawalEventPublisher = withdrawalEventPublisher; _repository = repository; _logger = logger; _dbContextFactory = dbContextFactory; @@ -266,6 +269,9 @@ public async Task> GetAllUnsignedPendingRequests() var valueTuple = await _repository.AddAsync(type, applicationDbContext); + if (valueTuple.Item1) + _withdrawalEventPublisher.PublishCreated(type); + if (!wallet.IsHotWallet) await _notificationService.NotifyRequestSigners(type.WalletId, "/withdrawals"); @@ -300,10 +306,19 @@ public async Task> GetAllUnsignedPendingRequests() // Stamp before mapping, otherwise the stripped copy that is persisted keeps the old UpdateDatetime. type.SetUpdateDatetime(); + // The stored status and TxId tell which wallet event this update stands for, so they are read before the + // write. The publisher skips the read when nobody listens to the wallet. + var before = _withdrawalEventPublisher.ReadBeforeUpdate(type); + //Automapper to remove collections var strippedType = _mapper.Map(type); - return _repository.Update(strippedType, applicationDbContext); + var result = _repository.Update(strippedType, applicationDbContext); + + if (result.Item1) + _withdrawalEventPublisher.PublishUpdated(before, type); + + return result; } public async Task<(bool, string?)> AddUTXOs(IBitcoinRequest type, List utxos) diff --git a/src/Helpers/AuthenticatedApiToken.cs b/src/Helpers/AuthenticatedApiToken.cs new file mode 100644 index 00000000..188bbb65 --- /dev/null +++ b/src/Helpers/AuthenticatedApiToken.cs @@ -0,0 +1,30 @@ +/* + * 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/. + * + */ + +namespace NodeGuard.Helpers; + +/// Identifies the API token that authenticated a call, without its secret value. +public sealed record AuthenticatedApiToken(int Id, string Name) +{ + /// + /// Key under which the authenticating token is stored in , + /// so records it on every audit of the call. + /// + public const string HttpContextItemKey = "NodeGuard.ApiToken"; +} diff --git a/src/Helpers/WithdrawalEventMapper.cs b/src/Helpers/WithdrawalEventMapper.cs new file mode 100644 index 00000000..66b8d6c5 --- /dev/null +++ b/src/Helpers/WithdrawalEventMapper.cs @@ -0,0 +1,125 @@ +/* + * 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 NBitcoin; +using NodeGuard.Data.Models; +using Nodeguard; + +namespace NodeGuard.Helpers; + +/// +/// Maps withdrawal requests and their status transitions to the gRPC wallet event shapes +/// +public static class WithdrawalEventMapper +{ + public static WITHDRAWAL_REQUEST_STATUS ToProtoStatus(WalletWithdrawalRequestStatus status) + { + return status switch + { + WalletWithdrawalRequestStatus.Cancelled => WITHDRAWAL_REQUEST_STATUS.WithdrawalCancelled, + WalletWithdrawalRequestStatus.Failed => WITHDRAWAL_REQUEST_STATUS.WithdrawalFailed, + WalletWithdrawalRequestStatus.FinalizingPSBT => WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingApproval, + WalletWithdrawalRequestStatus.OnChainConfirmationPending => WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingConfirmation, + WalletWithdrawalRequestStatus.OnChainConfirmed => WITHDRAWAL_REQUEST_STATUS.WithdrawalSettled, + WalletWithdrawalRequestStatus.Pending => WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingApproval, + WalletWithdrawalRequestStatus.PSBTSignaturesPending => WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingApproval, + WalletWithdrawalRequestStatus.Rejected => WITHDRAWAL_REQUEST_STATUS.WithdrawalRejected, + WalletWithdrawalRequestStatus.Bumped => WITHDRAWAL_REQUEST_STATUS.WithdrawalBumped, + _ => throw new ArgumentOutOfRangeException(nameof(status), status, "Unknown status") + }; + } + + /// + /// The event a persisted change of a withdrawal request stands for, or null when nothing a subscriber cares + /// about changed (e.g. an update that only touched the description) + /// + public static WALLET_EVENT_TYPE? TransitionEventType( + WalletWithdrawalRequestStatus previousStatus, string? previousTxId, + WalletWithdrawalRequestStatus status, string? txId) + { + var statusChanged = previousStatus != status; + var txIdChanged = !string.Equals(previousTxId, txId, StringComparison.Ordinal); + + if (status == WalletWithdrawalRequestStatus.OnChainConfirmationPending) + { + if (previousStatus is WalletWithdrawalRequestStatus.Bumped or WalletWithdrawalRequestStatus.Cancelled) + return WALLET_EVENT_TYPE.WalletEventWithdrawalReplacementReverted; + + if (txIdChanged && !string.IsNullOrEmpty(txId)) + return WALLET_EVENT_TYPE.WalletEventWithdrawalBroadcast; + } + + if (!statusChanged) + return null; + + return status switch + { + WalletWithdrawalRequestStatus.FinalizingPSBT => WALLET_EVENT_TYPE.WalletEventWithdrawalSigning, + WalletWithdrawalRequestStatus.OnChainConfirmed => WALLET_EVENT_TYPE.WalletEventWithdrawalConfirmed, + WalletWithdrawalRequestStatus.Bumped => WALLET_EVENT_TYPE.WalletEventWithdrawalBumped, + WalletWithdrawalRequestStatus.Cancelled => WALLET_EVENT_TYPE.WalletEventWithdrawalCancelled, + WalletWithdrawalRequestStatus.Rejected => WALLET_EVENT_TYPE.WalletEventWithdrawalRejected, + WalletWithdrawalRequestStatus.Failed => WALLET_EVENT_TYPE.WalletEventWithdrawalFailed, + _ => WALLET_EVENT_TYPE.WalletEventWithdrawalStatusChanged + }; + } + + /// + /// Builds the event payload. Signature counts need with its keys and + /// the request's PSBTs loaded; amounts need its destinations. + /// + public static WithdrawalEvent ToWithdrawalEvent(WalletWithdrawalRequest request, + WalletWithdrawalRequestStatus? previousStatus = null, int? replacedByRequestId = null) + { + var withdrawalEvent = new WithdrawalEvent + { + RequestId = request.Id, + Status = ToProtoStatus(request.Status), + IsRbfCancellation = request.IsRbfCancellation, + AmountSats = request.SatsAmount + }; + + if (previousStatus != null) withdrawalEvent.PreviousStatus = ToProtoStatus(previousStatus.Value); + if (!string.IsNullOrEmpty(request.TxId)) withdrawalEvent.TxId = request.TxId; + if (!string.IsNullOrEmpty(request.ReferenceId)) withdrawalEvent.ReferenceId = request.ReferenceId; + if (!string.IsNullOrEmpty(request.RejectCancelDescription)) withdrawalEvent.RejectOrCancelReason = request.RejectCancelDescription; + if (!string.IsNullOrEmpty(request.RequestMetadata)) withdrawalEvent.RequestMetadata = request.RequestMetadata; + if (request.BumpingWalletWithdrawalRequestId != null) withdrawalEvent.BumpingRequestId = request.BumpingWalletWithdrawalRequestId.Value; + if (replacedByRequestId != null) withdrawalEvent.ReplacedByRequestId = replacedByRequestId.Value; + if (request.CustomFeeRate != null) withdrawalEvent.FeeRateSatVb = (double)request.CustomFeeRate.Value; + + foreach (var destination in request.WalletWithdrawalRequestDestinations ?? []) + { + withdrawalEvent.Destinations.Add(new WithdrawalDestination + { + Address = destination.Address, + AmountSats = new Money(destination.Amount, MoneyUnit.BTC).Satoshi + }); + } + + var wallet = request.Wallet; + if (wallet is { IsHotWallet: false }) + { + withdrawalEvent.SignaturesCollected = request.NumberOfSignaturesCollected; + withdrawalEvent.SignaturesRequired = wallet.MofN - (wallet.RequiresInternalWalletSigning ? 1 : 0); + } + + return withdrawalEvent; + } +} diff --git a/src/Program.cs b/src/Program.cs index 1bd8df7f..afb33e87 100644 --- a/src/Program.cs +++ b/src/Program.cs @@ -168,6 +168,8 @@ public static async Task Main(string[] args) builder.Services.AddTransient(); builder.Services.AddSingleton(); builder.Services.AddHostedService(); + builder.Services.AddSingleton(); + builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddScoped(); @@ -210,6 +212,11 @@ public static async Task Main(string[] args) }); builder.WebHost.ConfigureKestrel(options => { + // SubscribeWalletEvents keeps a call open with nothing to send for long stretches: ping the client so + // proxies and load balancers do not drop the idle connection, and dead clients are noticed. + options.Limits.Http2.KeepAlivePingDelay = TimeSpan.FromSeconds(30); + options.Limits.Http2.KeepAlivePingTimeout = TimeSpan.FromSeconds(20); + // Setup a HTTP/2 endpoint without TLS. options.ListenAnyIP(50051, o => o.Protocols = HttpProtocols.Http2); diff --git a/src/Proto/nodeguard.proto b/src/Proto/nodeguard.proto index 37cef55f..d38a16c8 100644 --- a/src/Proto/nodeguard.proto +++ b/src/Proto/nodeguard.proto @@ -171,6 +171,16 @@ service NodeGuardService { Archives a Spark wallet; refused unless it is empty and no node uses it */ rpc ArchiveSparkWallet(ArchiveSparkWalletRequest) returns (ArchiveSparkWalletResponse); + + /* + Streams what happens to an on-chain wallet's withdrawals while the call is open. The first client message must be + a subscribe with the wallet id; the server answers with WALLET_EVENT_SUBSCRIBED once the subscription is live, then + one WalletEvent per change: created, signature added, signing, broadcast, confirmed, bumped, cancelled, rejected, + 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. + */ + rpc SubscribeWalletEvents(stream WalletEventsClientMessage) returns (stream WalletEvent); } message GetLiquidityRulesRequest { @@ -829,3 +839,81 @@ message ArchiveSparkWalletRequest { message ArchiveSparkWalletResponse { } + +message WalletEventsClientMessage { + oneof message { + // Must be the first message of the call + SubscribeWalletEventsRequest subscribe = 1; + } +} + +message SubscribeWalletEventsRequest { + int32 wallet_id = 1; + // Only these event types are sent; empty sends all. WALLET_EVENT_SUBSCRIBED is always sent. + repeated WALLET_EVENT_TYPE event_types = 2; +} + +enum WALLET_EVENT_TYPE { + WALLET_EVENT_UNSPECIFIED = 0; + // First message of every call: the subscription is live + WALLET_EVENT_SUBSCRIBED = 1; + // A withdrawal request was created, including an RBF replacement (bumping_request_id is set) + WALLET_EVENT_WITHDRAWAL_CREATED = 10; + // An approver's signed PSBT was stored + WALLET_EVENT_WITHDRAWAL_SIGNATURE_ADDED = 11; + // Every human signature is in: NodeGuard is signing and broadcasting + WALLET_EVENT_WITHDRAWAL_SIGNING = 12; + // The transaction was broadcast (tx_id is set) and waits for confirmation + WALLET_EVENT_WITHDRAWAL_BROADCAST = 13; + // The transaction reached the required confirmations + WALLET_EVENT_WITHDRAWAL_CONFIRMED = 14; + // Replaced by a fee bump (replaced_by_request_id is set when known) + WALLET_EVENT_WITHDRAWAL_BUMPED = 15; + // Cancelled by its requestor, or replaced by an RBF cancellation + WALLET_EVENT_WITHDRAWAL_CANCELLED = 16; + WALLET_EVENT_WITHDRAWAL_REJECTED = 17; + WALLET_EVENT_WITHDRAWAL_FAILED = 18; + // Its RBF replacement failed or was turned down: the original waits for confirmation again + 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; +} + +message WalletEvent { + WALLET_EVENT_TYPE type = 1; + int32 wallet_id = 2; + int64 occurred_at_unix_ms = 3; + oneof payload { + WithdrawalEvent withdrawal = 10; + } +} + +message WithdrawalDestination { + string address = 1; + int64 amount_sats = 2; +} + +message WithdrawalEvent { + int32 request_id = 1; + WITHDRAWAL_REQUEST_STATUS status = 2; + // Unset on WALLET_EVENT_WITHDRAWAL_CREATED and WALLET_EVENT_WITHDRAWAL_SIGNATURE_ADDED + optional WITHDRAWAL_REQUEST_STATUS previous_status = 3; + optional string tx_id = 4; + optional string reference_id = 5; + optional string reject_or_cancel_reason = 6; + // Set on an RBF replacement: the request whose transaction it replaces + optional int32 bumping_request_id = 7; + // Set on a bumped or RBF-cancelled original: the request that replaces it + optional int32 replaced_by_request_id = 8; + // The replacement returns the funds to the wallet instead of paying the destinations + bool is_rbf_cancellation = 9; + int64 amount_sats = 10; + repeated WithdrawalDestination destinations = 11; + // Human signatures collected and required; unset for hot wallets + optional int32 signatures_collected = 12; + optional int32 signatures_required = 13; + // in JSON format + optional string request_metadata = 14; + // Requested fee rate when one was set explicitly + optional double fee_rate_sat_vb = 15; +} diff --git a/src/Rpc/GRPCAuthInterceptor.cs b/src/Rpc/GRPCAuthInterceptor.cs index 350da0ff..6a4a5a74 100644 --- a/src/Rpc/GRPCAuthInterceptor.cs +++ b/src/Rpc/GRPCAuthInterceptor.cs @@ -1,22 +1,69 @@ using Grpc.Core; using Grpc.Core.Interceptors; using NodeGuard.Data.Repositories.Interfaces; +using NodeGuard.Helpers; namespace NodeGuard.Rpc; +/// +/// Requires a valid, unblocked API token in the auth-token header on every call: unary and streaming alike +/// public class GRPCAuthInterceptor : Interceptor { private readonly IAPITokenRepository _apiTokenRepository; - + public GRPCAuthInterceptor(IAPITokenRepository apiTokenRepository) { _apiTokenRepository = apiTokenRepository; } - -public override async Task UnaryServerHandler( - TRequest request, - ServerCallContext context, - UnaryServerMethod continuation) + + public override async Task UnaryServerHandler( + TRequest request, + ServerCallContext context, + UnaryServerMethod continuation) + { + await AuthenticateAsync(context); + return await continuation(request, context); + } + + public override async Task ClientStreamingServerHandler( + IAsyncStreamReader requestStream, + ServerCallContext context, + ClientStreamingServerMethod continuation) + { + await AuthenticateAsync(context); + return await continuation(requestStream, context); + } + + public override async Task ServerStreamingServerHandler( + TRequest request, + IServerStreamWriter responseStream, + ServerCallContext context, + ServerStreamingServerMethod continuation) + { + await AuthenticateAsync(context); + await continuation(request, responseStream, context); + } + + public override async Task DuplexStreamingServerHandler( + IAsyncStreamReader requestStream, + IServerStreamWriter responseStream, + ServerCallContext context, + DuplexStreamingServerMethod continuation) + { + await AuthenticateAsync(context); + await continuation(requestStream, responseStream, context); + } + + /// + /// The id and name of the API token that authenticated the call, or null outside an authenticated call + /// + public static AuthenticatedApiToken? GetApiToken(ServerCallContext context) => + context.UserState.TryGetValue(AuthenticatedApiToken.HttpContextItemKey, out var token) + ? token as AuthenticatedApiToken + : null; + + private async Task AuthenticateAsync(ServerCallContext context) { var token = context.RequestHeaders.FirstOrDefault(x => x.Key == "auth-token")?.Value; if (token == null) @@ -25,13 +72,14 @@ public override async Task UnaryServerHandler( } var apiToken = await _apiTokenRepository.GetByToken(token); - + if (apiToken?.IsBlocked ?? true) { throw new RpcException(new Status(StatusCode.Unauthenticated, "Invalid token")); } - - return await continuation(request, context); + + // Only the id and name go down the call, never the token row. Under ASP.NET Core, UserState is + // HttpContext.Items, so AuditService finds the token under the same key + context.UserState[AuthenticatedApiToken.HttpContextItemKey] = new AuthenticatedApiToken(apiToken.Id, apiToken.Name); } - -} \ No newline at end of file +} diff --git a/src/Rpc/NodeGuardService.cs b/src/Rpc/NodeGuardService.cs index 67566843..4003ad9c 100644 --- a/src/Rpc/NodeGuardService.cs +++ b/src/Rpc/NodeGuardService.cs @@ -73,6 +73,9 @@ Task GetNewWalletAddress(GetNewWalletAddressRequest Task RequestSwapOut(RequestSwapOutRequest request, ServerCallContext context); Task GetSwapOut(GetSwapOutRequest request, ServerCallContext context); + + Task SubscribeWalletEvents(IAsyncStreamReader requestStream, + IServerStreamWriter responseStream, ServerCallContext context); } /// @@ -104,6 +107,8 @@ public class NodeGuardService : Nodeguard.NodeGuardService.NodeGuardServiceBase, private readonly ISwapOutRepository _swapOutRepository; private readonly IAuditService _auditService; private readonly ISparkWalletService _sparkWallet; + private readonly IWalletEventHub _walletEventHub; + private readonly TimeProvider _timeProvider; public NodeGuardService(ILogger logger, ILiquidityRuleRepository liquidityRuleRepository, @@ -127,9 +132,13 @@ public NodeGuardService(ILogger logger, ISwapsService swapsService, ISwapOutRepository swapOutRepository, IAuditService auditService, - ISparkWalletService sparkWallet + ISparkWalletService sparkWallet, + IWalletEventHub walletEventHub, + TimeProvider timeProvider ) { + _walletEventHub = walletEventHub; + _timeProvider = timeProvider; _sparkWallet = sparkWallet; _swapsService = swapsService; _swapOutRepository = swapOutRepository; @@ -1320,23 +1329,6 @@ public override async Task GetAvailableUtxos(GetAvailableUtxos }; } - private WITHDRAWAL_REQUEST_STATUS GetStatus(WalletWithdrawalRequestStatus status) - { - return status switch - { - WalletWithdrawalRequestStatus.Cancelled => WITHDRAWAL_REQUEST_STATUS.WithdrawalCancelled, - WalletWithdrawalRequestStatus.Failed => WITHDRAWAL_REQUEST_STATUS.WithdrawalFailed, - WalletWithdrawalRequestStatus.FinalizingPSBT => WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingApproval, - WalletWithdrawalRequestStatus.OnChainConfirmationPending => WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingConfirmation, - WalletWithdrawalRequestStatus.OnChainConfirmed => WITHDRAWAL_REQUEST_STATUS.WithdrawalSettled, - WalletWithdrawalRequestStatus.Pending => WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingApproval, - WalletWithdrawalRequestStatus.PSBTSignaturesPending => WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingApproval, - WalletWithdrawalRequestStatus.Rejected => WITHDRAWAL_REQUEST_STATUS.WithdrawalRejected, - WalletWithdrawalRequestStatus.Bumped => WITHDRAWAL_REQUEST_STATUS.WithdrawalBumped, - _ => throw new ArgumentOutOfRangeException(nameof(status), status, "Unknown status") - }; - } - private async Task GetWithdrawalsRequestStatusResponse(List withdrawalRequests) { var withdrawalsResponses = new List(); @@ -1352,7 +1344,7 @@ private async Task GetWithdrawalsRequestSta withdrawalsResponses.Add(new WithdrawalRequest { RequestId = withdrawalRequest.Id, - Status = GetStatus(withdrawalRequest.Status), + Status = WithdrawalEventMapper.ToProtoStatus(withdrawalRequest.Status), RejectOrCancelReason = withdrawalRequest.RejectCancelDescription ?? "", ReferenceId = withdrawalRequest.ReferenceId ?? "", Confirmations = confirmations, @@ -1646,6 +1638,59 @@ public override async Task SetChannelFeePolicy(SetC return new SetChannelFeePolicyResponse(); } + public override async Task SubscribeWalletEvents(IAsyncStreamReader requestStream, + IServerStreamWriter responseStream, ServerCallContext context) + { + var cancellationToken = context.CancellationToken; + + if (!await requestStream.MoveNext(cancellationToken) + || requestStream.Current.MessageCase != WalletEventsClientMessage.MessageOneofCase.Subscribe) + { + throw new RpcException(new Status(StatusCode.InvalidArgument, "The first message must be a subscribe request")); + } + + var subscribe = requestStream.Current.Subscribe; + var wallet = await _walletRepository.GetById(subscribe.WalletId); + if (wallet == null) + throw new RpcException(new Status(StatusCode.NotFound, $"Wallet {subscribe.WalletId} not found")); + RefuseSparkWallet(wallet); + + var types = subscribe.EventTypes.ToHashSet(); + var subscriber = GRPCAuthInterceptor.GetApiToken(context)?.Name ?? context.Peer; + + using var subscription = _walletEventHub.Subscribe(wallet.Id, subscriber); + + await responseStream.WriteAsync(new WalletEvent + { + Type = WALLET_EVENT_TYPE.WalletEventSubscribed, + WalletId = wallet.Id, + OccurredAtUnixMs = _timeProvider.GetUtcNow().ToUnixTimeMilliseconds() + }); + + try + { + await foreach (var walletEvent in subscription.Reader.ReadAllAsync(cancellationToken)) + { + if (types.Count > 0 && !types.Contains(walletEvent.Type)) + continue; + + await responseStream.WriteAsync(walletEvent); + } + } + catch (WalletEventSubscriberTooSlowException e) + { + throw new RpcException(new Status(StatusCode.ResourceExhausted, e.Message)); + } + catch (WalletEventHubStoppingException e) + { + throw new RpcException(new Status(StatusCode.Unavailable, e.Message)); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // The client went away + } + } + /// /// Spark wallets (SPARK_SIGNER=wallet) have no on-chain keys: the methods that take an on-chain wallet refuse them /// diff --git a/src/Services/WalletEventHub.cs b/src/Services/WalletEventHub.cs new file mode 100644 index 00000000..06850f32 --- /dev/null +++ b/src/Services/WalletEventHub.cs @@ -0,0 +1,168 @@ +/* + * 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 System.Threading.Channels; +using Nodeguard; + +namespace NodeGuard.Services; + +/// +/// The subscriber could not keep up: its buffer filled, so it was dropped rather than block the publisher +/// +public class WalletEventSubscriberTooSlowException(int capacity) + : Exception($"The subscriber fell {capacity} events behind and was disconnected; resubscribe and reconcile"); + +/// +/// NodeGuard is shutting down and closed every subscription +/// +public class WalletEventHubStoppingException() : Exception("NodeGuard is shutting down; resubscribe"); + +/// +/// One open subscription to a wallet's events. Dispose it to unsubscribe. +/// +public sealed class WalletEventSubscription : IDisposable +{ + private readonly Channel _channel; + private readonly Action _unsubscribe; + + internal WalletEventSubscription(int walletId, string? subscriber, int capacity, + Action unsubscribe) + { + WalletId = walletId; + Subscriber = subscriber; + _unsubscribe = unsubscribe; + _channel = Channel.CreateBounded(new BoundedChannelOptions(capacity) + { + SingleReader = true, + FullMode = BoundedChannelFullMode.Wait + }); + } + + public Guid Id { get; } = Guid.NewGuid(); + + public int WalletId { get; } + + /// + /// Who subscribed (e.g. the API token name), for logs + /// + public string? Subscriber { get; } + + public ChannelReader Reader => _channel.Reader; + + internal bool TryWrite(WalletEvent walletEvent) => _channel.Writer.TryWrite(walletEvent); + + internal void Complete(Exception? error = null) => _channel.Writer.TryComplete(error); + + public void Dispose() + { + _unsubscribe(this); + Complete(); + } +} + +/// +/// In-process fan-out of wallet events to the gRPC streams subscribed to each wallet. Live only: nothing is stored, +/// and an event published while nobody listens is dropped. +/// +public interface IWalletEventHub +{ + WalletEventSubscription Subscribe(int walletId, string? subscriber = null); + + bool HasSubscribers(int walletId); + + /// + /// Hands the event to every subscriber of its wallet without blocking: a subscriber whose buffer is full is + /// disconnected with + /// + void Publish(WalletEvent walletEvent); +} + +public class WalletEventHub : IWalletEventHub +{ + public const int SubscriberCapacity = 1024; + + private readonly ConcurrentDictionary> _subscriptions = new(); + private readonly ILogger _logger; + private readonly int _capacity; + + public WalletEventHub(ILogger logger, IHostApplicationLifetime lifetime) + : this(logger, lifetime, SubscriberCapacity) + { + } + + internal WalletEventHub(ILogger logger, IHostApplicationLifetime lifetime, int capacity) + { + _logger = logger; + _capacity = capacity; + lifetime.ApplicationStopping.Register(CompleteAll); + } + + public WalletEventSubscription Subscribe(int walletId, string? subscriber = null) + { + var subscription = new WalletEventSubscription(walletId, subscriber, _capacity, Unsubscribe); + _subscriptions.GetOrAdd(walletId, _ => new ConcurrentDictionary()) + [subscription.Id] = subscription; + + _logger.LogInformation("Wallet events: {Subscriber} subscribed to wallet {WalletId} ({SubscriptionId})", + subscriber, walletId, subscription.Id); + + return subscription; + } + + public bool HasSubscribers(int walletId) => + _subscriptions.TryGetValue(walletId, out var subscriptions) && !subscriptions.IsEmpty; + + 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; + + _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)); + } + } + + private void Unsubscribe(WalletEventSubscription subscription) + { + if (_subscriptions.TryGetValue(subscription.WalletId, out var subscriptions) + && subscriptions.TryRemove(subscription.Id, out _)) + { + _logger.LogInformation("Wallet events: {Subscriber} unsubscribed from wallet {WalletId} ({SubscriptionId})", + subscription.Subscriber, subscription.WalletId, subscription.Id); + } + } + + private void CompleteAll() + { + foreach (var subscription in _subscriptions.Values.SelectMany(x => x.Values).ToList()) + { + Unsubscribe(subscription); + subscription.Complete(new WalletEventHubStoppingException()); + } + } +} diff --git a/src/Services/WithdrawalEventPublisher.cs b/src/Services/WithdrawalEventPublisher.cs new file mode 100644 index 00000000..034069f4 --- /dev/null +++ b/src/Services/WithdrawalEventPublisher.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 Microsoft.EntityFrameworkCore; +using NodeGuard.Data; +using NodeGuard.Data.Models; +using NodeGuard.Helpers; +using Nodeguard; + +namespace NodeGuard.Services; + +/// +/// Turns persisted withdrawal request changes into wallet events. Called by the withdrawal repositories after a +/// successful save; best effort: it never throws, and does no work for a wallet nobody subscribes to. +/// +public interface IWithdrawalEventPublisher +{ + /// + /// Reads the stored status and TxId of a request that is about to be updated, for + /// . Null, without touching the database, when nobody listens to its wallet or the + /// request was never saved; also null if the read fails. + /// + WithdrawalStateBeforeUpdate? ReadBeforeUpdate(WalletWithdrawalRequest request); + + /// + /// Publishes the event a saved update stands for, comparing with the state read by + /// . Does nothing when is null. + /// + void PublishUpdated(WithdrawalStateBeforeUpdate? before, WalletWithdrawalRequest request); + + /// + /// A request was created. must carry its destinations and its wallet with keys. + /// + void PublishCreated(WalletWithdrawalRequest request); + + void PublishSignatureAdded(int walletId, int requestId); + + void PublishTransition(int walletId, int requestId, + WalletWithdrawalRequestStatus previousStatus, string? previousTxId, + WalletWithdrawalRequestStatus status, string? txId); +} + +/// +/// What a withdrawal request looked like in the database right before an update +/// +public readonly record struct WithdrawalStateBeforeUpdate(int WalletId, int RequestId, + WalletWithdrawalRequestStatus Status, string? TxId); + +public class WithdrawalEventPublisher : IWithdrawalEventPublisher +{ + private readonly IWalletEventHub _hub; + private readonly IDbContextFactory _dbContextFactory; + private readonly TimeProvider _timeProvider; + private readonly ILogger _logger; + + public WithdrawalEventPublisher(IWalletEventHub hub, + IDbContextFactory dbContextFactory, + TimeProvider timeProvider, + ILogger logger) + { + _hub = hub; + _dbContextFactory = dbContextFactory; + _timeProvider = timeProvider; + _logger = logger; + } + + private bool IsWatched(int walletId) => _hub.HasSubscribers(walletId); + + public WithdrawalStateBeforeUpdate? ReadBeforeUpdate(WalletWithdrawalRequest request) + { + if (request.Id <= 0 || !IsWatched(request.WalletId)) + return null; + + try + { + using var applicationDbContext = _dbContextFactory.CreateDbContext(); + + var stored = applicationDbContext.WalletWithdrawalRequests + .AsNoTracking() + .Where(x => x.Id == request.Id) + .Select(x => new { x.Status, x.TxId }) + .SingleOrDefault(); + + return stored == null + ? null + : new WithdrawalStateBeforeUpdate(request.WalletId, request.Id, stored.Status, stored.TxId); + } + catch (Exception e) + { + _logger.LogError(e, "Wallet events: could not read withdrawal request {RequestId} before its update", + request.Id); + return null; + } + } + + public void PublishUpdated(WithdrawalStateBeforeUpdate? before, WalletWithdrawalRequest request) + { + if (before is not { } previous) + return; + + PublishTransition(previous.WalletId, previous.RequestId, previous.Status, previous.TxId, + request.Status, request.TxId); + } + + public void PublishCreated(WalletWithdrawalRequest request) + { + if (!IsWatched(request.WalletId)) + return; + + Publish(request.WalletId, request.Id, WALLET_EVENT_TYPE.WalletEventWithdrawalCreated, + () => WithdrawalEventMapper.ToWithdrawalEvent(request)); + } + + public void PublishSignatureAdded(int walletId, int requestId) + { + if (!IsWatched(walletId)) + return; + + Publish(walletId, requestId, WALLET_EVENT_TYPE.WalletEventWithdrawalSignatureAdded, + () => LoadEvent(requestId, previousStatus: null, lookUpReplacement: false)); + } + + public void PublishTransition(int walletId, int requestId, + WalletWithdrawalRequestStatus previousStatus, string? previousTxId, + WalletWithdrawalRequestStatus status, string? txId) + { + if (!IsWatched(walletId)) + return; + + var type = WithdrawalEventMapper.TransitionEventType(previousStatus, previousTxId, status, txId); + if (type == null) + return; + + var lookUpReplacement = type is WALLET_EVENT_TYPE.WalletEventWithdrawalBumped + or WALLET_EVENT_TYPE.WalletEventWithdrawalCancelled; + + Publish(walletId, requestId, type.Value, () => LoadEvent(requestId, previousStatus, lookUpReplacement)); + } + + private void Publish(int walletId, int requestId, WALLET_EVENT_TYPE type, Func buildPayload) + { + try + { + var payload = buildPayload(); + if (payload == null) + { + _logger.LogWarning("Wallet events: withdrawal request {RequestId} not found, {Type} not published", + requestId, type); + return; + } + + _hub.Publish(new WalletEvent + { + Type = type, + WalletId = walletId, + OccurredAtUnixMs = _timeProvider.GetUtcNow().ToUnixTimeMilliseconds(), + Withdrawal = payload + }); + } + catch (Exception e) + { + _logger.LogError(e, "Wallet events: could not publish {Type} for withdrawal request {RequestId}", + type, requestId); + } + } + + /// + /// Synchronous on purpose: is, and the + /// event has to be built before the next change of the same request is published + /// + private WithdrawalEvent? LoadEvent(int requestId, WalletWithdrawalRequestStatus? previousStatus, bool lookUpReplacement) + { + using var applicationDbContext = _dbContextFactory.CreateDbContext(); + + var request = applicationDbContext.WalletWithdrawalRequests + .AsNoTracking() + .Include(x => x.Wallet).ThenInclude(x => x.Keys) + .Include(x => x.WalletWithdrawalRequestPSBTs) + .Include(x => x.WalletWithdrawalRequestDestinations) + .AsSplitQuery() + .SingleOrDefault(x => x.Id == requestId); + + if (request == null) + return null; + + int? replacedBy = null; + if (lookUpReplacement) + { + replacedBy = applicationDbContext.WalletWithdrawalRequests + .Where(x => x.BumpingWalletWithdrawalRequestId == requestId) + .OrderByDescending(x => x.Id) + .Select(x => (int?)x.Id) + .FirstOrDefault(); + } + + return WithdrawalEventMapper.ToWithdrawalEvent(request, previousStatus, replacedBy); + } +} diff --git a/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestPsbtRepositoryTests.cs b/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestPsbtRepositoryTests.cs index b4399bf7..103d5ac8 100644 --- a/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestPsbtRepositoryTests.cs +++ b/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestPsbtRepositoryTests.cs @@ -21,9 +21,11 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging.Abstractions; using NBitcoin; +using Key = NBitcoin.Key; using NodeGuard.Data.Models; using NodeGuard.Data.Repositories.Interfaces; using NodeGuard.Helpers; +using NodeGuard.Services; namespace NodeGuard.Data.Repositories; @@ -50,9 +52,11 @@ private Mock> SetupDbContextFactory() } private static WalletWithdrawalRequestPsbtRepository CreateRepository( - Mock> factory, Mock>? generic = null) + Mock> factory, Mock>? generic = null, + IWithdrawalEventPublisher? publisher = null) => new((generic ?? new Mock>()).Object, - NullLogger.Instance, factory.Object); + NullLogger.Instance, factory.Object, + publisher ?? Mock.Of()); private static string UnsignedPsbt(int seed) { @@ -183,4 +187,73 @@ public async Task AddAsync_Approval_WhenRequestHasTwoTemplates_IsRejected() (await verify.WalletWithdrawalRequests.SingleAsync(x => x.Id == requestId)).Status .Should().Be(WalletWithdrawalRequestStatus.Pending, "a rejected approval must not advance the request"); } + + [Fact] + public async Task AddAsync_HumanApproval_PublishesSignatureAdded() + { + var network = CurrentNetworkHelper.GetCurrentNetwork(); + var keyA = new Key(); + var keyB = new Key(); + var redeem = PayToMultiSigTemplate.Instance.GenerateScriptPubKey(2, keyA.PubKey, keyB.PubKey); + var funding = network.CreateTransaction(); + funding.Outputs.Add(new TxOut(Money.Coins(1m), redeem.WitHash.ScriptPubKey)); + var coin = new Coin(funding, 0U).ToScriptCoin(redeem); + var spend = network.CreateTransaction(); + spend.Inputs.Add(new TxIn(coin.Outpoint)); + spend.Outputs.Add(new TxOut(Money.Coins(0.5m), new Key().PubKey.GetAddress(ScriptPubKeyType.Segwit, network))); + var template = PSBT.FromTransaction(spend, network).AddCoins(coin); + var approval = template.Clone(); + approval.SignWithKeys(keyA); + + var factory = SetupDbContextFactory(); + var generic = new Mock>(); + generic.Setup(x => x.AddAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync((true, null)); + var publisher = new Mock(); + int requestId; + await using (var context = await factory.Object.CreateDbContextAsync()) + { + var request = new WalletWithdrawalRequest + { + Description = "approval publishes", + Status = WalletWithdrawalRequestStatus.Pending, + WalletId = 7, + WalletWithdrawalRequestPSBTs = [new() { IsTemplatePSBT = true, PSBT = template.ToBase64() }], + }; + await context.WalletWithdrawalRequests.AddAsync(request); + await context.SaveChangesAsync(); + requestId = request.Id; + } + + var result = await CreateRepository(factory, generic, publisher.Object).AddAsync(new WalletWithdrawalRequestPSBT + { + WalletWithdrawalRequestId = requestId, + PSBT = approval.ToBase64(), + SignerId = "approver", + }); + + result.Item1.Should().BeTrue(result.Item2); + publisher.Verify(x => x.PublishSignatureAdded(7, requestId), Times.Once); + } + + [Fact] + public async Task AddAsync_Template_DoesNotPublishASignature() + { + var factory = SetupDbContextFactory(); + var publisher = new Mock(); + int requestId; + await using (var context = await factory.Object.CreateDbContextAsync()) + { + requestId = await SeedRequestAsync(context); + } + + await CreateRepository(factory, publisher: publisher.Object).AddAsync(new WalletWithdrawalRequestPSBT + { + WalletWithdrawalRequestId = requestId, + IsTemplatePSBT = true, + PSBT = UnsignedPsbt(1), + }); + + publisher.Verify(x => x.PublishSignatureAdded(It.IsAny(), It.IsAny()), Times.Never); + } } diff --git a/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestRepositoryTests.cs b/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestRepositoryTests.cs new file mode 100644 index 00000000..fe9fe6f3 --- /dev/null +++ b/test/NodeGuard.Tests/Data/Repositories/WalletWithdrawalRequestRepositoryTests.cs @@ -0,0 +1,127 @@ +/* + * 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 AutoMapper; +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using NodeGuard.Automapper; +using NodeGuard.Data.Models; +using NodeGuard.Services; +using NSubstitute; + +namespace NodeGuard.Data.Repositories; + +public class WalletWithdrawalRequestRepositoryTests +{ + private const int WalletId = 3; + private const string TxId = "4f7c3a1b2d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8"; + + private readonly DbContextOptions _options = new DbContextOptionsBuilder() + .UseInMemoryDatabase("WalletWithdrawalRequestRepositoryTests" + Guid.NewGuid()) + .Options; + private readonly IWithdrawalEventPublisher _publisher = Substitute.For(); + private readonly WalletWithdrawalRequestRepository _repository; + + public WalletWithdrawalRequestRepositoryTests() + { + var factory = Substitute.For>(); + factory.CreateDbContext().Returns(_ => new ApplicationDbContext(_options)); + factory.CreateDbContextAsync(Arg.Any()).Returns(_ => new ApplicationDbContext(_options)); + var mapper = new MapperConfiguration(config => { config.AddProfile(); }).CreateMapper(); + + _repository = new WalletWithdrawalRequestRepository( + new Repository(NullLogger.Instance), + NullLogger.Instance, + factory, + mapper, + notificationService: null!, + Substitute.For(), + _publisher); + } + + private WalletWithdrawalRequest Seed(WalletWithdrawalRequestStatus status, string? txId = null) + { + using var context = new ApplicationDbContext(_options); + var request = new WalletWithdrawalRequest + { + Description = "event diff", + WalletId = WalletId, + Status = status, + TxId = txId, + }; + context.WalletWithdrawalRequests.Add(request); + context.SaveChanges(); + context.Entry(request).State = EntityState.Detached; + return request; + } + + [Fact] + public void Update_ReadsTheStateBeforeTheWriteAndPublishesItAfter() + { + var request = Seed(WalletWithdrawalRequestStatus.FinalizingPSBT); + var before = new WithdrawalStateBeforeUpdate(WalletId, request.Id, WalletWithdrawalRequestStatus.FinalizingPSBT, null); + WalletWithdrawalRequestStatus? storedWhenRead = null; + _publisher.ReadBeforeUpdate(request).Returns(_ => + { + using var context = new ApplicationDbContext(_options); + storedWhenRead = context.WalletWithdrawalRequests.AsNoTracking().Single(x => x.Id == request.Id).Status; + return before; + }); + + request.Status = WalletWithdrawalRequestStatus.OnChainConfirmationPending; + request.TxId = TxId; + var (ok, _) = _repository.Update(request); + + ok.Should().BeTrue(); + storedWhenRead.Should().Be(WalletWithdrawalRequestStatus.FinalizingPSBT, "the state is read before the write"); + _publisher.Received(1).PublishUpdated(before, request); + } + + [Fact] + public void Update_LeavesTheSubscriberCheckToThePublisher() + { + var request = Seed(WalletWithdrawalRequestStatus.OnChainConfirmationPending, TxId); + _publisher.ReadBeforeUpdate(request).Returns((WithdrawalStateBeforeUpdate?)null); + + request.Status = WalletWithdrawalRequestStatus.OnChainConfirmed; + _repository.Update(request).Item1.Should().BeTrue(); + + _publisher.Received(1).ReadBeforeUpdate(request); + _publisher.Received(1).PublishUpdated(null, request); + } + + [Fact] + public void Update_FailedWrite_PublishesNothing() + { + var missing = new WalletWithdrawalRequest + { + Id = 9999, + Description = "never saved", + WalletId = WalletId, + Status = WalletWithdrawalRequestStatus.Cancelled + }; + _publisher.ReadBeforeUpdate(missing) + .Returns(new WithdrawalStateBeforeUpdate(WalletId, missing.Id, WalletWithdrawalRequestStatus.Pending, null)); + + _repository.Update(missing).Item1.Should().BeFalse(); + + _publisher.DidNotReceiveWithAnyArgs().PublishUpdated(default, default!); + } +} diff --git a/test/NodeGuard.Tests/E2E/PsbtApprovalBindingE2ETests.cs b/test/NodeGuard.Tests/E2E/PsbtApprovalBindingE2ETests.cs index 6982bcd2..2beab6b9 100644 --- a/test/NodeGuard.Tests/E2E/PsbtApprovalBindingE2ETests.cs +++ b/test/NodeGuard.Tests/E2E/PsbtApprovalBindingE2ETests.cs @@ -29,6 +29,7 @@ using NodeGuard.Data; using NodeGuard.Data.Models; using NodeGuard.Data.Repositories; +using NodeGuard.Services; using Npgsql; using Xunit.Abstractions; @@ -248,7 +249,8 @@ private static WalletWithdrawalRequestPsbtRepository CreatePsbtRepository() => new( new Repository(NullLogger.Instance), NullLogger.Instance, - DbContextFactory()); + DbContextFactory(), + Mock.Of()); private static async Task GetTemplatePsbtAsync(int requestId) { diff --git a/test/NodeGuard.Tests/E2E/WalletEventsE2ETests.cs b/test/NodeGuard.Tests/E2E/WalletEventsE2ETests.cs new file mode 100644 index 00000000..f5987000 --- /dev/null +++ b/test/NodeGuard.Tests/E2E/WalletEventsE2ETests.cs @@ -0,0 +1,291 @@ +/* + * 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 Grpc.Core; +using NBitcoin; +using NBitcoin.RPC; +using Nodeguard; +using Xunit.Abstractions; +using Channel = System.Threading.Channels.Channel; + +namespace NodeGuard.Tests.E2E; + +/// +/// End-to-end coverage for SubscribeWalletEvents against a LIVE NodeGuard + bitcoind, driven over gRPC: a hot-wallet +/// withdrawal is followed from creation to confirmation on the stream, and an RBF bump links the original and its +/// replacement. Shared plumbing in ; gated by . Confirmation +/// needs MonitorWithdrawalsJob to run promptly (MONITOR_WITHDRAWALS_CRON is 10s in the e2e stack). +/// +[Trait("Category", "E2E")] +[Collection("E2E")] +public class WalletEventsE2ETests : E2ETestBase +{ + private const long WithdrawalAmountSats = 1_000_000; + private const int OriginalFeeRateSatPerVb = 2; + private const int BumpedFeeRateSatPerVb = 10; + private const long ProbeAmountSats = 2_000_000; + + public WalletEventsE2ETests(ITestOutputHelper output) : base(output) + { + } + + [E2EFact] + public async Task SubscribeWalletEvents_FollowsAHotWithdrawalFromCreationToConfirmation() + { + var client = CreateClient(out var headers); + var rpc = CreateBitcoindRpc(); + var walletId = await EnsureHotWalletReadyAsync(client, headers); + await using var events = await WalletEventStream.OpenAsync(client, headers, walletId, _output); + + var withdrawal = await RequestHotWithdrawalAsync(client, headers, walletId, await rpc.GetNewAddressAsync(), + "E2E wallet events"); + + var created = await events.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalCreated); + created.Withdrawal.AmountSats.Should().Be(WithdrawalAmountSats); + created.Withdrawal.Destinations.Should().ContainSingle(d => d.AmountSats == WithdrawalAmountSats); + + var broadcast = await events.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalBroadcast); + broadcast.Withdrawal.TxId.Should().Be(withdrawal.Txid); + broadcast.Withdrawal.Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingConfirmation); + (await rpc.GetRawTransactionAsync(uint256.Parse(withdrawal.Txid), throwIfNotFound: false)) + .Should().NotBeNull("the broadcast event follows the real broadcast"); + + await MineAsync(rpc, 6); + + var confirmed = await events.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalConfirmed, + TimeSpan.FromMinutes(3)); + confirmed.Withdrawal.Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalSettled); + confirmed.Withdrawal.PreviousStatus.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingConfirmation); + + var seen = events.Seen(withdrawal.RequestId); + seen.Should().ContainInOrder( + WALLET_EVENT_TYPE.WalletEventWithdrawalCreated, + WALLET_EVENT_TYPE.WalletEventWithdrawalSigning, + WALLET_EVENT_TYPE.WalletEventWithdrawalBroadcast, + WALLET_EVENT_TYPE.WalletEventWithdrawalConfirmed); + seen.SkipWhile(t => t != WALLET_EVENT_TYPE.WalletEventWithdrawalBroadcast).Skip(1) + .Should().Equal([WALLET_EVENT_TYPE.WalletEventWithdrawalConfirmed], + "nothing may move a broadcast withdrawal backwards before it confirms"); + } + + [E2EFact] + public async Task SubscribeWalletEvents_LinksABumpedWithdrawalAndItsReplacement() + { + var client = CreateClient(out var headers); + var rpc = CreateBitcoindRpc(); + var walletId = await EnsureHotWalletReadyAsync(client, headers); + await using var events = await WalletEventStream.OpenAsync(client, headers, walletId, _output); + + var withdrawal = await RequestHotWithdrawalAsync(client, headers, walletId, await rpc.GetNewAddressAsync(), + "E2E wallet events bump"); + await events.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalBroadcast); + + var bump = await client.BumpWithdrawalAsync(new BumpWithdrawalRequest + { + RequestId = withdrawal.RequestId, + MempoolFeeRate = FEES_TYPE.CustomFee, + CustomFeeRate = BumpedFeeRateSatPerVb, + }, headers); + _output.WriteLine($"bump request {bump.RequestId} → txid {bump.Txid}"); + + var replacementCreated = await events.NextAsync(bump.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalCreated); + replacementCreated.Withdrawal.BumpingRequestId.Should().Be(withdrawal.RequestId); + replacementCreated.Withdrawal.IsRbfCancellation.Should().BeFalse(); + + var bumped = await events.NextAsync(withdrawal.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalBumped); + bumped.Withdrawal.ReplacedByRequestId.Should().Be(bump.RequestId); + bumped.Withdrawal.Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalBumped); + + var replacementBroadcast = await events.NextAsync(bump.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalBroadcast); + replacementBroadcast.Withdrawal.TxId.Should().Be(bump.Txid); + + // Confirm so the hot wallet's UTXOs are free for the next test + await MineAsync(rpc, 6); + await events.NextAsync(bump.RequestId, WALLET_EVENT_TYPE.WalletEventWithdrawalConfirmed, TimeSpan.FromMinutes(3)); + } + + [E2EFact] + public async Task SubscribeWalletEvents_RefusesCallsWithoutAToken() + { + var client = CreateClient(out _); + + using var call = client.SubscribeWalletEvents(new Metadata()); + var act = async () => + { + await call.RequestStream.WriteAsync(new WalletEventsClientMessage + { + Subscribe = new SubscribeWalletEventsRequest { WalletId = 1 } + }); + await call.ResponseStream.MoveNext(); + }; + + (await act.Should().ThrowAsync()).Which.StatusCode.Should().Be(StatusCode.Unauthenticated); + } + + [E2EFact] + public async Task SubscribeWalletEvents_UnknownWallet_IsNotFound() + { + var client = CreateClient(out var headers); + + using var call = client.SubscribeWalletEvents(headers); + await call.RequestStream.WriteAsync(new WalletEventsClientMessage + { + Subscribe = new SubscribeWalletEventsRequest { WalletId = int.MaxValue } + }); + var act = () => call.ResponseStream.MoveNext(); + + (await act.Should().ThrowAsync()).Which.StatusCode.Should().Be(StatusCode.NotFound); + } + + // ---- plumbing ------------------------------------------------------------------------------------------------ + + /// + /// An open SubscribeWalletEvents call whose events are read in the background, so the test can wait for one + /// + private sealed class WalletEventStream : IAsyncDisposable + { + private readonly AsyncDuplexStreamingCall _call; + private readonly CancellationTokenSource _cts = new(); + private readonly System.Threading.Channels.Channel _received = Channel.CreateUnbounded(); + private readonly List _all = []; + private readonly ITestOutputHelper _output; + private readonly Task _reader; + + private WalletEventStream(AsyncDuplexStreamingCall call, ITestOutputHelper output) + { + _call = call; + _output = output; + _reader = Task.Run(async () => + { + try + { + await foreach (var e in _call.ResponseStream.ReadAllAsync(_cts.Token)) + { + _output.WriteLine($"event {e.Type} request {e.Withdrawal?.RequestId} tx {e.Withdrawal?.TxId}"); + lock (_all) _all.Add(e); + _received.Writer.TryWrite(e); + } + _received.Writer.TryComplete(); + } + catch (Exception ex) + { + _received.Writer.TryComplete(ex); + } + }); + } + + public static async Task OpenAsync(NodeGuardService.NodeGuardServiceClient client, + Metadata headers, int walletId, ITestOutputHelper output) + { + var stream = new WalletEventStream(client.SubscribeWalletEvents(headers), output); + await stream._call.RequestStream.WriteAsync(new WalletEventsClientMessage + { + Subscribe = new SubscribeWalletEventsRequest { WalletId = walletId } + }); + var subscribed = await stream.NextAsync(e => e.Type == WALLET_EVENT_TYPE.WalletEventSubscribed, + TimeSpan.FromSeconds(30), "subscribed"); + subscribed.WalletId.Should().Be(walletId); + return stream; + } + + public Task NextAsync(int requestId, WALLET_EVENT_TYPE type, TimeSpan? timeout = null) => + NextAsync(e => e.Type == type && e.Withdrawal?.RequestId == requestId, + timeout ?? TimeSpan.FromMinutes(2), $"{type} for request {requestId}"); + + public List Seen(int requestId) + { + lock (_all) return _all.Where(e => e.Withdrawal?.RequestId == requestId).Select(e => e.Type).ToList(); + } + + private async Task NextAsync(Func match, TimeSpan timeout, string what) + { + using var cts = new CancellationTokenSource(timeout); + try + { + while (true) + { + var e = await _received.Reader.ReadAsync(cts.Token); + if (match(e)) + return e; + } + } + catch (OperationCanceledException) + { + throw new TimeoutException($"No {what} event within {timeout}"); + } + } + + public async ValueTask DisposeAsync() + { + await _cts.CancelAsync(); + try + { + await _reader; + } + catch + { + // The call was cancelled on purpose + } + + _call.Dispose(); + _cts.Dispose(); + } + } + + /// NodeGuard up and the dev hot wallet spendable (DbInitializer funds it; another e2e may hold it briefly). + private async Task EnsureHotWalletReadyAsync(NodeGuardService.NodeGuardServiceClient client, Metadata headers) + { + var walletId = int.Parse(Env("E2E_HOT_WALLET_ID", "3")); + + await RetryAsync(async () => + { + var resp = await client.GetNodesAsync(new GetNodesRequest(), headers); + if (resp.Nodes.Count == 0) throw new InvalidOperationException("no nodes seeded yet"); + return true; + }, attempts: 90, delay: TimeSpan.FromSeconds(4), what: "GetNodes (NodeGuard readiness)"); + + await RetryAsync(async () => + { + var available = await client.GetAvailableUtxosAsync( + new GetAvailableUtxosRequest { WalletId = walletId, Amount = ProbeAmountSats }, headers); + if (available.Confirmed.Sum(u => u.Amount) < ProbeAmountSats) + throw new InvalidOperationException("hot wallet has no spendable UTXO yet"); + return true; + }, attempts: 60, delay: TimeSpan.FromSeconds(4), what: "GetAvailableUtxos (hot wallet funded)"); + + return walletId; + } + + private async Task RequestHotWithdrawalAsync(NodeGuardService.NodeGuardServiceClient client, + Metadata headers, int walletId, BitcoinAddress destination, string description) + { + var withdrawal = await client.RequestWithdrawalAsync(new RequestWithdrawalRequest + { + WalletId = walletId, + Description = description, + Destinations = { new Destination { Address = destination.ToString(), AmountSats = WithdrawalAmountSats } }, + MempoolFeeRate = FEES_TYPE.CustomFee, + CustomFeeRate = OriginalFeeRateSatPerVb, + }, headers); + _output.WriteLine($"withdrawal request {withdrawal.RequestId} → txid {withdrawal.Txid}"); + withdrawal.IsHotWallet.Should().BeTrue(); + return withdrawal; + } +} diff --git a/test/NodeGuard.Tests/Helpers/WithdrawalEventMapperTests.cs b/test/NodeGuard.Tests/Helpers/WithdrawalEventMapperTests.cs new file mode 100644 index 00000000..2628cf9c --- /dev/null +++ b/test/NodeGuard.Tests/Helpers/WithdrawalEventMapperTests.cs @@ -0,0 +1,126 @@ +/* + * 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 NodeGuard.Data.Models; +using Nodeguard; +using Wallet = NodeGuard.Data.Models.Wallet; +using S = NodeGuard.Data.Models.WalletWithdrawalRequestStatus; +using E = Nodeguard.WALLET_EVENT_TYPE; + +namespace NodeGuard.Helpers; + +public class WithdrawalEventMapperTests +{ + private const string TxId = "4f7c3a1b2d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8"; + + public static TheoryData Transitions => new() + { + { S.FinalizingPSBT, null, S.OnChainConfirmationPending, TxId, E.WalletEventWithdrawalBroadcast }, + { S.PSBTSignaturesPending, null, S.FinalizingPSBT, null, E.WalletEventWithdrawalSigning }, + { S.OnChainConfirmationPending, TxId, S.OnChainConfirmed, TxId, E.WalletEventWithdrawalConfirmed }, + { S.OnChainConfirmationPending, TxId, S.Bumped, TxId, E.WalletEventWithdrawalBumped }, + { S.OnChainConfirmationPending, TxId, S.Cancelled, TxId, E.WalletEventWithdrawalCancelled }, + { S.Pending, null, S.Cancelled, null, E.WalletEventWithdrawalCancelled }, + { S.PSBTSignaturesPending, null, S.Rejected, null, E.WalletEventWithdrawalRejected }, + { S.FinalizingPSBT, null, S.Failed, null, E.WalletEventWithdrawalFailed }, + // A failure after the broadcast keeps the TxId: still a failure, not a second broadcast + { S.OnChainConfirmationPending, TxId, S.Failed, TxId, E.WalletEventWithdrawalFailed }, + { S.Bumped, TxId, S.OnChainConfirmationPending, TxId, E.WalletEventWithdrawalReplacementReverted }, + { S.Cancelled, TxId, S.OnChainConfirmationPending, TxId, E.WalletEventWithdrawalReplacementReverted }, + { S.Pending, null, S.PSBTSignaturesPending, null, E.WalletEventWithdrawalStatusChanged }, + // Nothing a subscriber cares about changed + { S.Pending, null, S.Pending, null, null }, + { S.OnChainConfirmationPending, TxId, S.OnChainConfirmationPending, TxId, null }, + }; + + [Theory] + [MemberData(nameof(Transitions))] + public void TransitionEventType_MapsEachTransition(S previous, string? previousTxId, S status, string? txId, E? expected) + { + WithdrawalEventMapper.TransitionEventType(previous, previousTxId, status, txId).Should().Be(expected); + } + + [Fact] + public void ToWithdrawalEvent_CarriesTheRequestDetails() + { + var request = new WalletWithdrawalRequest + { + Id = 42, + Status = S.Cancelled, + TxId = TxId, + ReferenceId = "ref-42", + RejectCancelDescription = "Cancelled by RBF replacement request 43", + RequestMetadata = "{\"k\":\"v\"}", + BumpingWalletWithdrawalRequestId = 41, + IsRbfCancellation = true, + CustomFeeRate = 12.5m, + Wallet = new Wallet { IsHotWallet = true }, + WalletWithdrawalRequestDestinations = + [ + new WalletWithdrawalRequestDestination { Address = "bcrt1qdest1", Amount = 0.001m }, + new WalletWithdrawalRequestDestination { Address = "bcrt1qdest2", Amount = 0.0025m } + ] + }; + + var e = WithdrawalEventMapper.ToWithdrawalEvent(request, previousStatus: S.OnChainConfirmationPending, + replacedByRequestId: 43); + + e.RequestId.Should().Be(42); + e.Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalCancelled); + e.PreviousStatus.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingConfirmation); + e.TxId.Should().Be(TxId); + e.ReferenceId.Should().Be("ref-42"); + e.RejectOrCancelReason.Should().Be("Cancelled by RBF replacement request 43"); + e.RequestMetadata.Should().Be("{\"k\":\"v\"}"); + e.BumpingRequestId.Should().Be(41); + e.ReplacedByRequestId.Should().Be(43); + e.IsRbfCancellation.Should().BeTrue(); + e.FeeRateSatVb.Should().Be(12.5); + e.AmountSats.Should().Be(350_000); + e.Destinations.Select(d => (d.Address, d.AmountSats)) + .Should().Equal(("bcrt1qdest1", 100_000L), ("bcrt1qdest2", 250_000L)); + e.HasSignaturesCollected.Should().BeFalse("hot wallets have no human signers"); + e.HasSignaturesRequired.Should().BeFalse(); + } + + [Fact] + public void ToWithdrawalEvent_ColdWallet_CountsHumanSignatures() + { + var request = new WalletWithdrawalRequest + { + Id = 7, + Status = S.PSBTSignaturesPending, + Wallet = new Wallet { IsHotWallet = false, MofN = 2 }, + WalletWithdrawalRequestPSBTs = + [ + new WalletWithdrawalRequestPSBT { IsTemplatePSBT = true, PSBT = "template" }, + new WalletWithdrawalRequestPSBT { PSBT = "signed-by-a" } + ] + }; + + var e = WithdrawalEventMapper.ToWithdrawalEvent(request); + + e.SignaturesCollected.Should().Be(1); + e.SignaturesRequired.Should().Be(2); + e.HasPreviousStatus.Should().BeFalse(); + e.HasTxId.Should().BeFalse(); + e.HasReplacedByRequestId.Should().BeFalse(); + } +} diff --git a/test/NodeGuard.Tests/Rpc/GRPCAuthInterceptorTests.cs b/test/NodeGuard.Tests/Rpc/GRPCAuthInterceptorTests.cs index cc57dee9..4025f5ee 100644 --- a/test/NodeGuard.Tests/Rpc/GRPCAuthInterceptorTests.cs +++ b/test/NodeGuard.Tests/Rpc/GRPCAuthInterceptorTests.cs @@ -3,6 +3,7 @@ using Grpc.Core; using NodeGuard.Data.Models; using NodeGuard.Data.Repositories.Interfaces; +using NodeGuard.Helpers; namespace NodeGuard.Rpc; @@ -105,4 +106,84 @@ await act .ThrowAsync() .WithMessage("Status(StatusCode=\"Unauthenticated\", Detail=\"Invalid token\")"); } -} \ No newline at end of file + + private static Mock TokenRepository(APIToken? token) + { + var repository = new Mock(); + repository.Setup(x => x.GetByToken(It.IsAny())).ReturnsAsync(token); + return repository; + } + + [Theory] + [InlineData(null, "No token provided")] + [InlineData("unknown", "Invalid token")] + [InlineData("blocked", "Invalid token")] + public async Task AuthInterceptor_DuplexStreaming_RejectsBeforeTheHandlerRuns(string? header, string detail) + { + var token = header == "blocked" ? new APIToken { Name = "blocked", IsBlocked = true } : null; + var context = TestServerCallContext.Create(header == null ? null : new Metadata { { "auth-token", header } }); + var interceptor = new GRPCAuthInterceptor(TokenRepository(token).Object); + var called = false; + DuplexStreamingServerMethod continuation = (_, _, _) => + { + called = true; + return Task.CompletedTask; + }; + + var act = () => interceptor.DuplexStreamingServerHandler(new TestAsyncStreamReader(), + new TestServerStreamWriter(), context, continuation); + + await act.Should().ThrowAsync() + .WithMessage($"Status(StatusCode=\"Unauthenticated\", Detail=\"{detail}\")"); + called.Should().BeFalse(); + } + + [Fact] + public async Task AuthInterceptor_DuplexStreaming_ValidToken_RunsTheHandlerWithTheToken() + { + var token = new APIToken { Id = 7, Name = "integrator" }; + var context = TestServerCallContext.Create(new Metadata { { "auth-token", "valid" } }); + var interceptor = new GRPCAuthInterceptor(TokenRepository(token).Object); + AuthenticatedApiToken? seen = null; + DuplexStreamingServerMethod continuation = (_, _, ctx) => + { + seen = GRPCAuthInterceptor.GetApiToken(ctx); + return Task.CompletedTask; + }; + + await interceptor.DuplexStreamingServerHandler(new TestAsyncStreamReader(), + new TestServerStreamWriter(), context, continuation); + + seen.Should().Be(new AuthenticatedApiToken(7, "integrator")); + } + + [Fact] + public async Task AuthInterceptor_ValidToken_KeepsOnlyTheTokenIdAndName() + { + const string secret = "the-token-value"; + var token = new APIToken { Id = 7, Name = "integrator", TokenHash = secret }; + var context = TestServerCallContext.Create(new Metadata { { "auth-token", secret } }); + var interceptor = new GRPCAuthInterceptor(TokenRepository(token).Object); + + await interceptor.UnaryServerHandler(string.Empty, context, (_, _) => Task.FromResult("response")); + + context.UserState[AuthenticatedApiToken.HttpContextItemKey].Should().Be(new AuthenticatedApiToken(7, "integrator")); + context.UserState.Values.Should().NotContain(v => v is APIToken || (v is string && (string)v == secret), + "the token row and its value must not travel down the call"); + } + + [Fact] + public async Task AuthInterceptor_ServerAndClientStreaming_WithoutToken_AreRejected() + { + var interceptor = new GRPCAuthInterceptor(TokenRepository(null).Object); + + var serverStreaming = () => interceptor.ServerStreamingServerHandler(string.Empty, + new TestServerStreamWriter(), TestServerCallContext.Create(), (_, _, _) => Task.CompletedTask); + var clientStreaming = () => interceptor.ClientStreamingServerHandler(new TestAsyncStreamReader(), + TestServerCallContext.Create(), (_, _) => Task.FromResult("response")); + + (await serverStreaming.Should().ThrowAsync()).Which.StatusCode.Should().Be(StatusCode.Unauthenticated); + (await clientStreaming.Should().ThrowAsync()).Which.StatusCode.Should().Be(StatusCode.Unauthenticated); + } +} + diff --git a/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs b/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs index 3e186b99..d56e066d 100644 --- a/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs +++ b/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs @@ -29,7 +29,9 @@ using NodeGuard.Services.Spark; using Grpc.Core; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using NBitcoin; using NBXplorer.DerivationStrategy; using NBXplorer.Models; @@ -84,7 +86,8 @@ private NodeGuardService CreateNodeGuardService( ISwapsService? swapsService = null, ISwapOutRepository? swapOutRepository = null, IAuditService? auditService = null, - ISparkWalletService? sparkWallet = null) + ISparkWalletService? sparkWallet = null, + IWalletEventHub? walletEventHub = null) { return new NodeGuardService( logger ?? _logger.Object, @@ -109,7 +112,9 @@ private NodeGuardService CreateNodeGuardService( swapsService ?? new Mock().Object, swapOutRepository ?? new Mock().Object, auditService ?? new Mock().Object, - sparkWallet ?? new Mock().Object); + sparkWallet ?? new Mock().Object, + walletEventHub ?? new Mock().Object, + TimeProvider.System); } [Fact] @@ -2575,5 +2580,144 @@ public async Task GetSwapOut_UnknownOrMissingId_IsRefused() (await unknown.Should().ThrowAsync()).Which.StatusCode.Should().Be(StatusCode.NotFound); (await missing.Should().ThrowAsync()).Which.StatusCode.Should().Be(StatusCode.InvalidArgument); } + + // ---- SubscribeWalletEvents ---------------------------------------------------------------------- + + private sealed class WalletEventsCall + { + public required NodeGuardService Service { get; init; } + public required WalletEventHub Hub { get; init; } + public required CancellationTokenSource Stopping { get; init; } + public TestAsyncStreamReader Requests { get; } = new(); + public TestServerStreamWriter Responses { get; } = new(); + public CancellationTokenSource ClientCancellation { get; } = new(); + + public Task Start() => Service.SubscribeWalletEvents(Requests, Responses, + TestServerCallContext.Create(cancellationToken: ClientCancellation.Token)); + } + + private WalletEventsCall WalletEventsCallFor(params Wallet[] wallets) + { + var walletRepository = new Mock(); + foreach (var wallet in wallets) + walletRepository.Setup(x => x.GetById(wallet.Id)).ReturnsAsync(wallet); + + var stopping = new CancellationTokenSource(); + var lifetime = new Mock(); + lifetime.Setup(x => x.ApplicationStopping).Returns(stopping.Token); + var hub = new WalletEventHub(NullLogger.Instance, lifetime.Object); + + return new WalletEventsCall + { + Service = CreateNodeGuardService(walletRepository: walletRepository.Object, walletEventHub: hub), + Hub = hub, + Stopping = stopping + }; + } + + private static WalletEventsClientMessage Subscribe(int walletId, params WALLET_EVENT_TYPE[] types) => new() + { + Subscribe = new SubscribeWalletEventsRequest { WalletId = walletId, EventTypes = { types } } + }; + + private static WalletEvent WithdrawalEvent(int walletId, WALLET_EVENT_TYPE type, int requestId) => new() + { + Type = type, + WalletId = walletId, + Withdrawal = new WithdrawalEvent { RequestId = requestId } + }; + + [Fact] + public async Task SubscribeWalletEvents_FirstMessageMustBeSubscribe() + { + var call = WalletEventsCallFor(); + call.Requests.Complete(); + + var act = () => call.Start(); + + (await act.Should().ThrowAsync()).Which.StatusCode.Should().Be(StatusCode.InvalidArgument); + } + + [Fact] + public async Task SubscribeWalletEvents_UnknownWallet_IsNotFound() + { + var call = WalletEventsCallFor(); + call.Requests.Add(Subscribe(404)); + + var act = () => call.Start(); + + (await act.Should().ThrowAsync()).Which.StatusCode.Should().Be(StatusCode.NotFound); + call.Hub.HasSubscribers(404).Should().BeFalse(); + } + + [Fact] + public async Task SubscribeWalletEvents_SparkWallet_IsRefused() + { + var call = WalletEventsCallFor(new Wallet { Id = 3, Kind = WalletKind.Spark }); + call.Requests.Add(Subscribe(3)); + + var act = () => call.Start(); + + (await act.Should().ThrowAsync()).Which.StatusCode.Should().Be(StatusCode.FailedPrecondition); + } + + [Fact] + public async Task SubscribeWalletEvents_StreamsTheWalletsEventsUntilTheClientLeaves() + { + var call = WalletEventsCallFor(new Wallet { Id = 1 }, new Wallet { Id = 2 }); + call.Requests.Add(Subscribe(1)); + var running = call.Start(); + + var first = await call.Responses.ReadNextAsync(); + first.Type.Should().Be(WALLET_EVENT_TYPE.WalletEventSubscribed); + first.WalletId.Should().Be(1); + call.Hub.HasSubscribers(1).Should().BeTrue(); + + call.Hub.Publish(WithdrawalEvent(2, WALLET_EVENT_TYPE.WalletEventWithdrawalCreated, 20)); + call.Hub.Publish(WithdrawalEvent(1, WALLET_EVENT_TYPE.WalletEventWithdrawalCreated, 10)); + call.Hub.Publish(WithdrawalEvent(1, WALLET_EVENT_TYPE.WalletEventWithdrawalBroadcast, 10)); + + (await call.Responses.ReadNextAsync()).Type.Should().Be(WALLET_EVENT_TYPE.WalletEventWithdrawalCreated); + var broadcast = await call.Responses.ReadNextAsync(); + broadcast.Type.Should().Be(WALLET_EVENT_TYPE.WalletEventWithdrawalBroadcast); + broadcast.Withdrawal.RequestId.Should().Be(10); + (await call.Responses.NothingMoreWrittenAsync()).Should().BeTrue("wallet 2's event is not for this call"); + + await call.ClientCancellation.CancelAsync(); + await running.WaitAsync(TimeSpan.FromSeconds(5)); + call.Hub.HasSubscribers(1).Should().BeFalse("the subscription ends with the call"); + } + + [Fact] + public async Task SubscribeWalletEvents_EventTypeFilter_SkipsOtherTypes() + { + var call = WalletEventsCallFor(new Wallet { Id = 1 }); + call.Requests.Add(Subscribe(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.WalletEventWithdrawalBroadcast, 10)); + call.Hub.Publish(WithdrawalEvent(1, WALLET_EVENT_TYPE.WalletEventWithdrawalConfirmed, 10)); + + (await call.Responses.ReadNextAsync()).Type.Should().Be(WALLET_EVENT_TYPE.WalletEventWithdrawalConfirmed); + (await call.Responses.NothingMoreWrittenAsync()).Should().BeTrue(); + + await call.ClientCancellation.CancelAsync(); + await running.WaitAsync(TimeSpan.FromSeconds(5)); + } + + [Fact] + public async Task SubscribeWalletEvents_Shutdown_EndsTheCallAsUnavailable() + { + var call = WalletEventsCallFor(new Wallet { Id = 1 }); + call.Requests.Add(Subscribe(1)); + var running = call.Start(); + (await call.Responses.ReadNextAsync()).Type.Should().Be(WALLET_EVENT_TYPE.WalletEventSubscribed); + + await call.Stopping.CancelAsync(); + + (await running.Invoking(t => t.WaitAsync(TimeSpan.FromSeconds(5))).Should().ThrowAsync()) + .Which.StatusCode.Should().Be(StatusCode.Unavailable); + } } } diff --git a/test/NodeGuard.Tests/Rpc/TestStreams.cs b/test/NodeGuard.Tests/Rpc/TestStreams.cs new file mode 100644 index 00000000..9b309c16 --- /dev/null +++ b/test/NodeGuard.Tests/Rpc/TestStreams.cs @@ -0,0 +1,88 @@ +/* + * 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.Threading.Channels; +using Grpc.Core; +using Channel = System.Threading.Channels.Channel; + +namespace NodeGuard.Rpc; + +/// +/// Server-side response stream that records what the handler writes, so a test can await each message +/// +public class TestServerStreamWriter : IServerStreamWriter where T : class +{ + private readonly Channel _written = Channel.CreateUnbounded(); + + public WriteOptions? WriteOptions { get; set; } + + public Task WriteAsync(T message) + { + _written.Writer.TryWrite(message); + return Task.CompletedTask; + } + + public async Task ReadNextAsync(TimeSpan? timeout = null) + { + using var cts = new CancellationTokenSource(timeout ?? TimeSpan.FromSeconds(5)); + return await _written.Reader.ReadAsync(cts.Token); + } + + /// + /// True when nothing else was written within + /// + public async Task NothingMoreWrittenAsync(TimeSpan? wait = null) + { + using var cts = new CancellationTokenSource(wait ?? TimeSpan.FromMilliseconds(200)); + try + { + return !await _written.Reader.WaitToReadAsync(cts.Token); + } + catch (OperationCanceledException) + { + return true; + } + } +} + +/// +/// Server-side request stream fed by the test: sends a client message, +/// half-closes the call +/// +public class TestAsyncStreamReader : IAsyncStreamReader where T : class +{ + private readonly Channel _messages = Channel.CreateUnbounded(); + + public T Current { get; private set; } = null!; + + public void Add(T message) => _messages.Writer.TryWrite(message); + + public void Complete() => _messages.Writer.TryComplete(); + + public async Task MoveNext(CancellationToken cancellationToken) + { + if (await _messages.Reader.WaitToReadAsync(cancellationToken) && _messages.Reader.TryRead(out var message)) + { + Current = message; + return true; + } + + return false; + } +} diff --git a/test/NodeGuard.Tests/Services/WalletEventHubTests.cs b/test/NodeGuard.Tests/Services/WalletEventHubTests.cs new file mode 100644 index 00000000..2604d35c --- /dev/null +++ b/test/NodeGuard.Tests/Services/WalletEventHubTests.cs @@ -0,0 +1,131 @@ +/* + * 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; +using NSubstitute; + +namespace NodeGuard.Services; + +public class WalletEventHubTests +{ + private readonly CancellationTokenSource _stopping = new(); + + private WalletEventHub CreateHub(int capacity = WalletEventHub.SubscriberCapacity) + { + var lifetime = Substitute.For(); + lifetime.ApplicationStopping.Returns(_stopping.Token); + return new WalletEventHub(NullLogger.Instance, lifetime, capacity); + } + + private static WalletEvent Event(int walletId, int requestId = 1) => new() + { + Type = WALLET_EVENT_TYPE.WalletEventWithdrawalCreated, + WalletId = walletId, + Withdrawal = new WithdrawalEvent { RequestId = requestId } + }; + + [Fact] + public void Publish_ReachesEverySubscriberOfThatWalletOnly() + { + var hub = CreateHub(); + using var first = hub.Subscribe(1); + using var second = hub.Subscribe(1); + using var otherWallet = hub.Subscribe(2); + + hub.Publish(Event(1)); + + first.Reader.TryRead(out var a).Should().BeTrue(); + second.Reader.TryRead(out var b).Should().BeTrue(); + a!.WalletId.Should().Be(1); + b!.WalletId.Should().Be(1); + otherWallet.Reader.TryRead(out _).Should().BeFalse(); + } + + [Fact] + public void Publish_WithoutSubscribers_IsANoOp() + { + var hub = CreateHub(); + + var act = () => hub.Publish(Event(1)); + + act.Should().NotThrow(); + hub.HasSubscribers(1).Should().BeFalse(); + } + + [Fact] + public void Dispose_Unsubscribes() + { + var hub = CreateHub(); + var subscription = hub.Subscribe(1); + hub.HasSubscribers(1).Should().BeTrue(); + + subscription.Dispose(); + + hub.HasSubscribers(1).Should().BeFalse(); + subscription.Reader.Completion.IsCompleted.Should().BeTrue(); + } + + [Fact] + public async Task Publish_SubscriberThatFallsBehind_IsDisconnectedWithoutAffectingTheOthers() + { + var hub = CreateHub(capacity: 2); + using var slow = hub.Subscribe(1); + using var fast = hub.Subscribe(1); + + for (var i = 1; i <= 3; i++) + { + hub.Publish(Event(1, i)); + fast.Reader.TryRead(out var received).Should().BeTrue(); + received!.Withdrawal.RequestId.Should().Be(i); + } + + // The two buffered events are still delivered, then the disconnection surfaces + var buffered = new List(); + var act = async () => + { + await foreach (var e in slow.Reader.ReadAllAsync()) + buffered.Add(e.Withdrawal.RequestId); + }; + await act.Should().ThrowAsync(); + buffered.Should().Equal(1, 2); + + hub.HasSubscribers(1).Should().BeTrue("the subscriber that kept up stays subscribed"); + hub.Publish(Event(1, 4)); + fast.Reader.TryRead(out var fourth).Should().BeTrue(); + fourth!.Withdrawal.RequestId.Should().Be(4); + } + + [Fact] + public async Task ApplicationStopping_ClosesEverySubscription() + { + var hub = CreateHub(); + using var first = hub.Subscribe(1); + using var second = hub.Subscribe(2); + + await _stopping.CancelAsync(); + + await first.Invoking(s => s.Reader.Completion).Should().ThrowAsync(); + await second.Invoking(s => s.Reader.Completion).Should().ThrowAsync(); + hub.HasSubscribers(1).Should().BeFalse(); + hub.HasSubscribers(2).Should().BeFalse(); + } +} diff --git a/test/NodeGuard.Tests/Services/WithdrawalEventPublisherTests.cs b/test/NodeGuard.Tests/Services/WithdrawalEventPublisherTests.cs new file mode 100644 index 00000000..4f890b51 --- /dev/null +++ b/test/NodeGuard.Tests/Services/WithdrawalEventPublisherTests.cs @@ -0,0 +1,286 @@ +/* + * 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.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using NodeGuard.Data; +using NodeGuard.Data.Models; +using Nodeguard; +using Wallet = NodeGuard.Data.Models.Wallet; +using NSubstitute; + +namespace NodeGuard.Services; + +public class WithdrawalEventPublisherTests +{ + private const int WalletId = 5; + private const long Now = 1_700_000_000_000; + private const string TxId = "4f7c3a1b2d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8"; + + private sealed class FixedTime : TimeProvider + { + public override DateTimeOffset GetUtcNow() => DateTimeOffset.FromUnixTimeMilliseconds(Now); + } + + private readonly IWalletEventHub _hub = Substitute.For(); + private readonly IDbContextFactory _factory = Substitute.For>(); + private readonly WithdrawalEventPublisher _publisher; + private readonly DbContextOptions _options = new DbContextOptionsBuilder() + .UseInMemoryDatabase("WithdrawalEventPublisherTests" + Guid.NewGuid()) + .Options; + + public WithdrawalEventPublisherTests() + { + using (var context = new ApplicationDbContext(_options)) + { + context.Wallets.Add(new Wallet { Id = WalletId, Name = "cold", MofN = 2, IsHotWallet = false }); + context.SaveChanges(); + } + + _factory.CreateDbContext().Returns(_ => new ApplicationDbContext(_options)); + _hub.HasSubscribers(WalletId).Returns(true); + _publisher = new WithdrawalEventPublisher(_hub, _factory, new FixedTime(), NullLogger.Instance); + } + + private int Seed(WalletWithdrawalRequest request) + { + using var context = new ApplicationDbContext(_options); + request.WalletId = WalletId; + request.Description ??= "publisher test"; + context.WalletWithdrawalRequests.Add(request); + context.SaveChanges(); + return request.Id; + } + + private WalletEvent SinglePublishedEvent() + { + var calls = _hub.ReceivedCalls().Where(c => c.GetMethodInfo().Name == nameof(IWalletEventHub.Publish)).ToList(); + calls.Should().ContainSingle(); + return (WalletEvent)calls[0].GetArguments()[0]!; + } + + [Fact] + public void PublishTransition_UnwatchedWallet_DoesNothing() + { + _hub.HasSubscribers(WalletId).Returns(false); + + _publisher.PublishTransition(WalletId, 1, WalletWithdrawalRequestStatus.FinalizingPSBT, null, + WalletWithdrawalRequestStatus.OnChainConfirmationPending, TxId); + + _factory.DidNotReceive().CreateDbContext(); + _hub.DidNotReceive().Publish(Arg.Any()); + } + + [Fact] + public void PublishTransition_NothingChanged_PublishesNothing() + { + _publisher.PublishTransition(WalletId, 1, WalletWithdrawalRequestStatus.Pending, null, + WalletWithdrawalRequestStatus.Pending, null); + + _hub.DidNotReceive().Publish(Arg.Any()); + } + + [Fact] + public void PublishTransition_Broadcast_PublishesTheStoredSnapshot() + { + var id = Seed(new WalletWithdrawalRequest + { + Status = WalletWithdrawalRequestStatus.OnChainConfirmationPending, + TxId = TxId, + ReferenceId = "ref", + WalletWithdrawalRequestDestinations = [new() { Address = "bcrt1qdest", Amount = 0.01m }] + }); + + _publisher.PublishTransition(WalletId, id, WalletWithdrawalRequestStatus.FinalizingPSBT, null, + WalletWithdrawalRequestStatus.OnChainConfirmationPending, TxId); + + var e = SinglePublishedEvent(); + e.Type.Should().Be(WALLET_EVENT_TYPE.WalletEventWithdrawalBroadcast); + e.WalletId.Should().Be(WalletId); + e.OccurredAtUnixMs.Should().Be(Now); + e.Withdrawal.RequestId.Should().Be(id); + e.Withdrawal.TxId.Should().Be(TxId); + e.Withdrawal.ReferenceId.Should().Be("ref"); + e.Withdrawal.Status.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingConfirmation); + e.Withdrawal.PreviousStatus.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingApproval); + e.Withdrawal.AmountSats.Should().Be(1_000_000); + e.Withdrawal.HasReplacedByRequestId.Should().BeFalse(); + } + + [Fact] + public void PublishTransition_Bumped_NamesTheLatestReplacement() + { + var originalId = Seed(new WalletWithdrawalRequest { Status = WalletWithdrawalRequestStatus.Bumped, TxId = TxId }); + Seed(new WalletWithdrawalRequest + { + Status = WalletWithdrawalRequestStatus.Cancelled, BumpingWalletWithdrawalRequestId = originalId + }); + var latestReplacementId = Seed(new WalletWithdrawalRequest + { + Status = WalletWithdrawalRequestStatus.PSBTSignaturesPending, BumpingWalletWithdrawalRequestId = originalId + }); + + _publisher.PublishTransition(WalletId, originalId, WalletWithdrawalRequestStatus.OnChainConfirmationPending, TxId, + WalletWithdrawalRequestStatus.Bumped, TxId); + + var e = SinglePublishedEvent(); + e.Type.Should().Be(WALLET_EVENT_TYPE.WalletEventWithdrawalBumped); + e.Withdrawal.ReplacedByRequestId.Should().Be(latestReplacementId); + } + + [Fact] + public void PublishSignatureAdded_CountsTheHumanSignatures() + { + var id = Seed(new WalletWithdrawalRequest + { + Status = WalletWithdrawalRequestStatus.PSBTSignaturesPending, + WalletWithdrawalRequestPSBTs = + [ + new() { IsTemplatePSBT = true, PSBT = "template" }, + new() { PSBT = "signed-by-a" } + ] + }); + + _publisher.PublishSignatureAdded(WalletId, id); + + var e = SinglePublishedEvent(); + e.Type.Should().Be(WALLET_EVENT_TYPE.WalletEventWithdrawalSignatureAdded); + e.Withdrawal.SignaturesCollected.Should().Be(1); + e.Withdrawal.SignaturesRequired.Should().Be(2); + e.Withdrawal.HasPreviousStatus.Should().BeFalse(); + } + + [Fact] + public void PublishCreated_UsesTheRequestInHand() + { + var request = new WalletWithdrawalRequest + { + Id = 99, + WalletId = WalletId, + Status = WalletWithdrawalRequestStatus.Pending, + Wallet = new Wallet { Id = WalletId, MofN = 2 }, + WalletWithdrawalRequestDestinations = [new() { Address = "bcrt1qdest", Amount = 0.02m }] + }; + + _publisher.PublishCreated(request); + + _factory.DidNotReceive().CreateDbContext(); + var e = SinglePublishedEvent(); + e.Type.Should().Be(WALLET_EVENT_TYPE.WalletEventWithdrawalCreated); + e.Withdrawal.RequestId.Should().Be(99); + e.Withdrawal.AmountSats.Should().Be(2_000_000); + } + + [Fact] + public void Publish_DatabaseFailure_IsSwallowed() + { + _factory.CreateDbContext().Returns(_ => throw new InvalidOperationException("database down")); + + var act = () => _publisher.PublishTransition(WalletId, 1, WalletWithdrawalRequestStatus.FinalizingPSBT, null, + WalletWithdrawalRequestStatus.OnChainConfirmationPending, TxId); + + act.Should().NotThrow(); + _hub.DidNotReceive().Publish(Arg.Any()); + } + + [Fact] + public void ReadBeforeUpdate_UnwatchedWallet_DoesNotReadTheDatabase() + { + _hub.HasSubscribers(WalletId).Returns(false); + var id = Seed(new WalletWithdrawalRequest { Status = WalletWithdrawalRequestStatus.FinalizingPSBT }); + _factory.ClearReceivedCalls(); + + var before = _publisher.ReadBeforeUpdate(new WalletWithdrawalRequest { Id = id, WalletId = WalletId }); + + before.Should().BeNull(); + _factory.DidNotReceive().CreateDbContext(); + } + + [Fact] + public void ReadBeforeUpdate_WatchedWallet_ReturnsTheStoredState() + { + var id = Seed(new WalletWithdrawalRequest { Status = WalletWithdrawalRequestStatus.OnChainConfirmationPending, TxId = TxId }); + + // The request in hand already carries the new values; the stored ones are what the update changes + var before = _publisher.ReadBeforeUpdate(new WalletWithdrawalRequest + { + Id = id, + WalletId = WalletId, + Status = WalletWithdrawalRequestStatus.OnChainConfirmed, + TxId = TxId + }); + + before.Should().Be(new WithdrawalStateBeforeUpdate(WalletId, id, + WalletWithdrawalRequestStatus.OnChainConfirmationPending, TxId)); + } + + [Fact] + public void ReadBeforeUpdate_UnsavedRequest_ReturnsNull() + { + _publisher.ReadBeforeUpdate(new WalletWithdrawalRequest { WalletId = WalletId }).Should().BeNull(); + + _factory.DidNotReceive().CreateDbContext(); + } + + [Fact] + public void ReadBeforeUpdate_DatabaseFailure_ReturnsNull() + { + _factory.CreateDbContext().Returns(_ => throw new InvalidOperationException("database down")); + + var act = () => _publisher.ReadBeforeUpdate(new WalletWithdrawalRequest { Id = 1, WalletId = WalletId }); + + act.Should().NotThrow().Which.Should().BeNull(); + } + + [Fact] + public void PublishUpdated_PublishesTheTransitionFromTheStateBefore() + { + var id = Seed(new WalletWithdrawalRequest { Status = WalletWithdrawalRequestStatus.OnChainConfirmationPending, TxId = TxId }); + + _publisher.PublishUpdated( + new WithdrawalStateBeforeUpdate(WalletId, id, WalletWithdrawalRequestStatus.FinalizingPSBT, null), + new WalletWithdrawalRequest + { + Id = id, + WalletId = WalletId, + Status = WalletWithdrawalRequestStatus.OnChainConfirmationPending, + TxId = TxId + }); + + var e = SinglePublishedEvent(); + e.Type.Should().Be(WALLET_EVENT_TYPE.WalletEventWithdrawalBroadcast); + e.Withdrawal.PreviousStatus.Should().Be(WITHDRAWAL_REQUEST_STATUS.WithdrawalPendingApproval); + } + + [Fact] + public void PublishUpdated_NothingReadBefore_PublishesNothing() + { + _publisher.PublishUpdated(null, new WalletWithdrawalRequest + { + Id = 1, + WalletId = WalletId, + Status = WalletWithdrawalRequestStatus.OnChainConfirmed, + TxId = TxId + }); + + _factory.DidNotReceive().CreateDbContext(); + _hub.DidNotReceive().Publish(Arg.Any()); + } +}