Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

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

gRPC uses a stateless `auth-token` header validated by [src/Rpc/GRPCAuthInterceptor.cs](src/Rpc/GRPCAuthInterceptor.cs) against the `APIToken` table. 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<T>` plus per-entity repos in [src/Data/Repositories/](src/Data/Repositories/). Both `AddDbContext<ApplicationDbContext>` (transient) **and** `AddDbContextFactory<ApplicationDbContext>` are registered in `Program.cs` — **prefer the factory inside Quartz jobs and singletons**, the transient context is for short request-scoped work. Queries use `UseQuerySplittingBehavior(SingleQuery)` deliberately.

Expand Down
12 changes: 10 additions & 2 deletions src/Data/Repositories/WalletWithdrawalRequestPsbtRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
using Microsoft.EntityFrameworkCore;
using NBitcoin;
using NodeGuard.Helpers;
using NodeGuard.Services;
using Npgsql;

namespace NodeGuard.Data.Repositories
Expand All @@ -37,11 +38,14 @@ public class WalletWithdrawalRequestPsbtRepository : IWalletWithdrawalRequestPsb
private readonly IRepository<WalletWithdrawalRequestPSBT> _repository;
private readonly ILogger<WalletWithdrawalRequestPsbtRepository> _logger;
private readonly IDbContextFactory<ApplicationDbContext> _dbContextFactory;
private readonly IWithdrawalEventPublisher _withdrawalEventPublisher;

public WalletWithdrawalRequestPsbtRepository(IRepository<WalletWithdrawalRequestPSBT> repository,
ILogger<WalletWithdrawalRequestPsbtRepository> logger,
IDbContextFactory<ApplicationDbContext> dbContextFactory)
IDbContextFactory<ApplicationDbContext> dbContextFactory,
IWithdrawalEventPublisher withdrawalEventPublisher)
{
_withdrawalEventPublisher = withdrawalEventPublisher;
_repository = repository;
_logger = logger;
_dbContextFactory = dbContextFactory;
Expand Down Expand Up @@ -115,7 +119,11 @@ public async Task<List<WalletWithdrawalRequestPSBT>> 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;
}

/// <summary>
Expand Down
19 changes: 17 additions & 2 deletions src/Data/Repositories/WalletWithdrawalRequestRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<WalletWithdrawalRequest> repository,
ILogger<WalletWithdrawalRequestRepository> logger,
IDbContextFactory<ApplicationDbContext> dbContextFactory,
IMapper mapper,
NotificationService notificationService,
INBXplorerService nBXplorerService
INBXplorerService nBXplorerService,
IWithdrawalEventPublisher withdrawalEventPublisher
)
{
_withdrawalEventPublisher = withdrawalEventPublisher;
_repository = repository;
_logger = logger;
_dbContextFactory = dbContextFactory;
Expand Down Expand Up @@ -266,6 +269,9 @@ public async Task<List<WalletWithdrawalRequest>> GetAllUnsignedPendingRequests()


var valueTuple = await _repository.AddAsync(type, applicationDbContext);
if (valueTuple.Item1)
_withdrawalEventPublisher.PublishCreated(type);

if (!wallet.IsHotWallet)
await _notificationService.NotifyRequestSigners(type.WalletId, "/withdrawals");

Expand Down Expand Up @@ -300,10 +306,19 @@ public async Task<List<WalletWithdrawalRequest>> 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<WalletWithdrawalRequest, WalletWithdrawalRequest>(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<FMUTXO> utxos)
Expand Down
30 changes: 30 additions & 0 deletions src/Helpers/AuthenticatedApiToken.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>Identifies the API token that authenticated a call, without its secret value.</summary>
public sealed record AuthenticatedApiToken(int Id, string Name)
{
/// <summary>
/// Key under which the authenticating token is stored in <see cref="Microsoft.AspNetCore.Http.HttpContext.Items"/>,
/// so <see cref="NodeGuard.Services.AuditService"/> records it on every audit of the call.
/// </summary>
public const string HttpContextItemKey = "NodeGuard.ApiToken";
}
125 changes: 125 additions & 0 deletions src/Helpers/WithdrawalEventMapper.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Maps withdrawal requests and their status transitions to the gRPC wallet event shapes
/// </summary>
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")
};
}

/// <summary>
/// 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)
/// </summary>
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
};
}

/// <summary>
/// Builds the event payload. Signature counts need <see cref="WalletWithdrawalRequest.Wallet"/> with its keys and
/// the request's PSBTs loaded; amounts need its destinations.
/// </summary>
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;
}
}
7 changes: 7 additions & 0 deletions src/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ public static async Task Main(string[] args)
builder.Services.AddTransient<ISparkSwapService, SparkSwapService>();
builder.Services.AddSingleton<ISparkGuardrails, SparkGuardrails>();
builder.Services.AddHostedService<SparkStartupService>();
builder.Services.AddSingleton<IWalletEventHub, WalletEventHub>();
builder.Services.AddTransient<IWithdrawalEventPublisher, WithdrawalEventPublisher>();
builder.Services.AddTransient<IRebalanceService, RebalanceService>();
builder.Services.AddTransient<IRoutingEngineSnapshotService, RoutingEngineSnapshotService>();
builder.Services.AddScoped<IAuditService, AuditService>();
Expand Down Expand Up @@ -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);
Expand Down
88 changes: 88 additions & 0 deletions src/Proto/nodeguard.proto
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
}
Loading
Loading