diff --git a/.vscode/launch.json b/.vscode/launch.json index cd50561b4..98f6d467d 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -61,7 +61,11 @@ "ROUTING_ENGINE_ENABLED": "true", "AUTO_CHANNEL_OPEN_ENABLED": "true", "AUTO_CHANNEL_OPEN_MIN_EARNED_FEE_SATS": "1", - "AUTO_CHANNEL_OPEN_MIN_REFUSALS": "3" + "AUTO_CHANNEL_OPEN_MIN_REFUSALS": "1", + "AUTO_CHANNEL_OPEN_LOOKBACK_DAYS": "30", + "AUTO_CHANNEL_OPEN_SHORTAGE_HOURS": "24", + "AUTO_CHANNEL_OPEN_LOW_OUTBOUND_PCT": "50", + "AUTO_CHANNEL_OPEN_PEER_COOLDOWN_HOURS": "1" }, "sourceFileMap": { "/Views": "${workspaceFolder}/Views" diff --git a/docker/loop/docker-compose.yml b/docker/loop/docker-compose.yml index d052cca38..b46d24c56 100644 --- a/docker/loop/docker-compose.yml +++ b/docker/loop/docker-compose.yml @@ -6,7 +6,7 @@ x-loop-service: &loop-service x-loopd-service: &loopd-service <<: *loop-service - image: lightninglabs/loop:v0.31.2-beta + image: lightninglabs/loop:v0.36.0-beta services: loopserver: diff --git a/docs/auto-channel-open.md b/docs/auto-channel-open.md index 147b96426..e9ea3465b 100644 --- a/docs/auto-channel-open.md +++ b/docs/auto-channel-open.md @@ -1,6 +1,6 @@ # Auto channel open -Auto channel open proposes a new channel to a peer when two things are true: the route to that peer has been earning us fees, and we have recently been turning payments to it away for lack of outbound liquidity. The channel always has the same size, set per node. +Auto channel open proposes a new channel to a peer when two things are true: the route to that peer has been earning us fees, and we have recently been turning payments to it away for lack of outbound liquidity. The channel always has the same size, set per node. Peers we want channels with regardless, such as a swap service, can be [reserved](#reserved-peers) a share of the budget. [`AutoChannelOpenJob`](../src/Jobs/AutoChannelOpenJob.cs) runs every 30 minutes (every minute in a dev environment) as part of the routing engine (see [routing-engine.md](routing-engine.md)). It writes recommendations, which an operator promotes from the Routing Management page. In **Auto** mode the job promotes them itself. Either way a promotion only creates a channel open request: funding still goes through the usual approval and signing flow. @@ -39,7 +39,18 @@ Promoting creates a `ChannelOperationRequest` to open a public channel to the pe - With a **hot wallet** that needs no human signature, the template PSBT is built and `ChannelOpenJob` is scheduled straight away. If the template can't be built (no spendable coins), the request fails. - Otherwise the request stays **Pending** for the wallet's signers, like any other channel open. -**The fee the channel opens at.** A new channel arrives with all its balance on our side, so at the node's default fee it would become the cheapest route to a peer we already know is in demand. It opens instead at the highest fee rate we currently charge on our channels to that peer, with the base fee of that same channel. The policy is captured with the evidence on every run, and the channel opens at the one captured last, without asking LND again at promotion. +**The fee the channel opens at.** A new channel arrives with all its balance on our side, so at the node's default fee it would become the cheapest route to a peer we already know is in demand. It opens instead at the highest fee rate we currently charge on our channels to that peer, with the base fee of that same channel. The policy is captured with the evidence on every run, and the channel opens at the one captured last, without asking LND again at promotion. The one exception is a reserved peer we have no fee to copy from, usually because we have no channel with it yet: its channel opens at the fee rate and base fee set on its reservation. + +## Reserved peers + +Some peers need channels whether or not they earn us anything. A swap service such as Loop is the usual case: our swap-outs are our own payments to it, not forwards, so the route to it never earns fees and never passes check 1. Each node can list such peers on the Nodes page (Automatic Channel Opening ▸ Reserved Peers). Each one is a node registered in NodeGuard, picked from a list, with a share of the budget in percent, a fee rate and a base fee. The shares of a node add up to at most 100%. Both fees are required. + +A reserved peer skips the evidence (checks 1, 2 and 5). It qualifies when: +- the usable outbound to it is below `AUTO_CHANNEL_OPEN_LOW_OUTBOUND_PCT` of the capacity we have with it, or we have no channel with it at all; +- it is not on cooldown; +- the node's channel size fits the funding wallet and the budget left for it (see below). + +Reserved peers are evaluated ahead of the others in each run, so the per-run cap can't crowd them out. Their recommendations show a **reserved** badge on the Routing Management page, and the panel shows what each share has committed this period. ## Lifecycle @@ -63,6 +74,13 @@ Each node has a channel open budget: the most it may commit to new channels per What counts as committed is the capacity of every channel open request from the node created in the current period, except those cancelled, rejected or failed. That includes opens created by hand, not only the automatic ones. Within a run, every promotion is deducted before the next plan is checked. +**Reserved shares.** Each reserved peer's share of the budget (its percentage) is set aside for it, and the rest is shared by every other peer: +- An ordinary peer can only use the unreserved part. +- A reserved peer uses its own share first, then the unreserved part. +- Committed sats count against the peer the request opens to, so an open made by hand to a reserved peer uses up its share too. Whatever a reserved peer commits beyond its share comes out of the unreserved part. + +For example, with a 10 BTC budget and Loop reserved at 30%, other peers can commit at most 7 BTC, and Loop up to 3 BTC on its own share plus whatever the others leave of the 7. + ## Settings **Environment** ([`Constants.cs`](../src/Helpers/Constants.cs)): @@ -85,6 +103,7 @@ What counts as committed is the capacity of every channel open request from the - **Funding wallet**: the wallet the channels are paid from. Required. - **Channel size**: the capacity of every recommended channel. Required, at least `MINIMUM_CHANNEL_CAPACITY_SATS`. - **Budget** and **budget refresh interval**. A budget is required. +- **Reserved peers**: a registered node, a share of the budget and an opening fee (rate and base) for each. See [Reserved peers](#reserved-peers). - **Dry run**, shared with the fee engine and the rebalancer. A node without a funding wallet, channel size or budget is skipped, and the job logs why. The Routing Management page shows the size, the budget and what the current period has committed next to the recommendations, and warns when the feature is globally off or the node has no funding wallet. @@ -97,3 +116,4 @@ A node without a funding wallet, channel size or budget is skipped, and the job - **One size for every peer.** The channel doesn't grow with demand. A peer that needs more gets another recommendation once the cooldown has passed and it is short again. - **The swap-out check doesn't see requests still waiting for signatures.** A promoted open counts towards the node's balance only once LND reports it as pending, so opens promoted in earlier runs and not yet funded are left out. - **The budget is checked per recommendation.** In Recommendation mode several open recommendations may together exceed the remaining budget, and promoting from the panel doesn't check the budget again. The next run sees what was committed. +- **A reserved peer's channel is invisible until it opens.** The job reads channels from `ListChannels`, which leaves out pending ones. An automatic open holds its peer until it confirms, but an open made by hand to a reserved peer we had no channel with doesn't: the peer looks channel-less, and is recommended again once its cooldown, if any, has passed. Its share still caps what it can be given. diff --git a/src/Automapper/MapperProfile.cs b/src/Automapper/MapperProfile.cs index 1fa42fa02..7854fbd32 100644 --- a/src/Automapper/MapperProfile.cs +++ b/src/Automapper/MapperProfile.cs @@ -43,6 +43,7 @@ public MapperProfile() .ForMember(x => x.FundsDestinationWallet, opt => opt.Ignore()) .ForMember(x => x.AutoChannelOpenWallet, opt => opt.Ignore()) .ForMember(x => x.ChannelOpenRecommendations, opt => opt.Ignore()) + .ForMember(x => x.ReservedChannelOpenPeers, opt => opt.Ignore()) .ForMember(x => x.Users, opt => opt.Ignore()); CreateMap() diff --git a/src/Data/ApplicationDbContext.cs b/src/Data/ApplicationDbContext.cs index c70e62fb8..4201a6ef5 100644 --- a/src/Data/ApplicationDbContext.cs +++ b/src/Data/ApplicationDbContext.cs @@ -185,6 +185,22 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity() .HasIndex(x => new { x.NodeId, x.PeerPubKey }).IsUnique(); + modelBuilder.Entity() + .HasOne(x => x.Node) + .WithMany(x => x.ReservedChannelOpenPeers) + .HasForeignKey(x => x.NodeId) + .OnDelete(DeleteBehavior.Cascade); + + // Deleting the peer's node drops its reservations too, so none is left pointing nowhere. + modelBuilder.Entity() + .HasOne(x => x.PeerNode) + .WithMany() + .HasForeignKey(x => x.PeerNodeId) + .OnDelete(DeleteBehavior.Cascade); + + modelBuilder.Entity() + .HasIndex(x => new { x.NodeId, x.PeerNodeId }).IsUnique(); + // These default ON: existing rows must be backfilled true (the C# initializer // only affects new in-code instances, not the DB column default / migration backfill). modelBuilder.Entity().Property(x => x.IsDynamicFeeEnabled).HasDefaultValue(false); @@ -239,5 +255,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) public DbSet SparkSignerIdentities { get; set; } public DbSet ChannelOpenRecommendations { get; set; } + + public DbSet ReservedChannelOpenPeers { get; set; } } } diff --git a/src/Data/Models/ChannelOpenRecommendation.cs b/src/Data/Models/ChannelOpenRecommendation.cs index 9d2e5864f..ecffd37d6 100644 --- a/src/Data/Models/ChannelOpenRecommendation.cs +++ b/src/Data/Models/ChannelOpenRecommendation.cs @@ -85,6 +85,10 @@ public class ChannelOpenRecommendation : Entity public long? InheritedFeeRatePpm { get; set; } public long? InheritedBaseFeeMsat { get; set; } + + /// Qualified as a , on outbound alone. With no channel to the + /// peer there is no policy to inherit, and the channel opens at the node's default fee. + public bool IsReservedPeer { get; set; } #endregion Evidence #region Lifecycle diff --git a/src/Data/Models/Node.cs b/src/Data/Models/Node.cs index e3720d813..aeb3d14de 100644 --- a/src/Data/Models/Node.cs +++ b/src/Data/Models/Node.cs @@ -273,6 +273,8 @@ public class Node : Entity public ICollection ChannelOpenRecommendations { get; set; } + public ICollection ReservedChannelOpenPeers { get; set; } + public ICollection ChannelOperationRequestsAsSource { get; set; } public ICollection ChannelOperationRequestsAsDestination { get; set; } diff --git a/src/Data/Models/ReservedChannelOpenPeer.cs b/src/Data/Models/ReservedChannelOpenPeer.cs new file mode 100644 index 000000000..47ab34af6 --- /dev/null +++ b/src/Data/Models/ReservedChannelOpenPeer.cs @@ -0,0 +1,50 @@ +/* + * 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.ComponentModel.DataAnnotations; + +namespace NodeGuard.Data.Models; + +/// +/// A peer that gets its own share of the node's channel open budget, such as a swap service. It skips +/// the earning evidence: it qualifies on low outbound alone, or on having no channel with us at all. +/// Its channel opens at the fee set here whenever we have no fee toward it to copy. +/// The peer is one of the registered nodes, so its name and pubkey are read from there. +/// +/// One row per (, ). Shares of one node sum to at most 100. +/// +/// +public class ReservedChannelOpenPeer : Entity +{ + public int NodeId { get; set; } + public Node? Node { get; set; } + + public int PeerNodeId { get; set; } + public Node? PeerNode { get; set; } + + /// Share of the node's channel open budget reserved for this peer, 1 to 100. + public int BudgetPct { get; set; } + + /// Nullable so a form can leave it unset, required so no row is saved without it. + [Required] + public long? FeeRatePpm { get; set; } + + [Required] + public long? BaseFeeMsat { get; set; } +} diff --git a/src/Data/Repositories/ChannelOpenRecommendationRepository.cs b/src/Data/Repositories/ChannelOpenRecommendationRepository.cs index 8b13b4edf..37698ac1b 100644 --- a/src/Data/Repositories/ChannelOpenRecommendationRepository.cs +++ b/src/Data/Repositories/ChannelOpenRecommendationRepository.cs @@ -51,7 +51,8 @@ public async Task> GetOpenByNode(int nodeId) return await context.ChannelOpenRecommendations .Where(x => x.NodeId == nodeId && x.Status == ChannelOpenRecommendationStatus.Open) - .OrderByDescending(x => x.EarnedFeeSats) + .OrderByDescending(x => x.IsReservedPeer) + .ThenByDescending(x => x.EarnedFeeSats) .ToListAsync(); } @@ -121,6 +122,7 @@ private static void CopyEvidence(ChannelOpenRecommendation from, ChannelOpenReco to.SuggestedCapacitySats = from.SuggestedCapacitySats; to.InheritedFeeRatePpm = from.InheritedFeeRatePpm; to.InheritedBaseFeeMsat = from.InheritedBaseFeeMsat; + to.IsReservedPeer = from.IsReservedPeer; to.LastEvidenceAt = from.LastEvidenceAt; } diff --git a/src/Data/Repositories/ChannelOperationRequestRepository.cs b/src/Data/Repositories/ChannelOperationRequestRepository.cs index ab81310d7..763db06d0 100644 --- a/src/Data/Repositories/ChannelOperationRequestRepository.cs +++ b/src/Data/Repositories/ChannelOperationRequestRepository.cs @@ -235,6 +235,22 @@ public async Task GetOpenSatsCommittedSince(int sourceNodeId, DateTimeOffs .SumAsync(x => (long?)x.SatsAmount) ?? 0; } + public async Task> GetOpenSatsCommittedByPeerSince(int sourceNodeId, DateTimeOffset since) + { + await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); + + return await applicationDbContext.ChannelOperationRequests + .Where(x => x.SourceNodeId == sourceNodeId + && x.RequestType == OperationRequestType.Open + && x.CreationDatetime >= since + && x.Status != ChannelOperationRequestStatus.Cancelled + && x.Status != ChannelOperationRequestStatus.Rejected + && x.Status != ChannelOperationRequestStatus.Failed) + .GroupBy(x => x.DestNode != null ? x.DestNode.PubKey : "") + .Select(g => new { PubKey = g.Key, Sats = g.Sum(x => x.SatsAmount) }) + .ToDictionaryAsync(x => x.PubKey, x => x.Sats); + } + public async Task> GetPendingRequests() { await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); diff --git a/src/Data/Repositories/Interfaces/IChannelOperationRequestRepository.cs b/src/Data/Repositories/Interfaces/IChannelOperationRequestRepository.cs index bffb03780..50085b0ea 100644 --- a/src/Data/Repositories/Interfaces/IChannelOperationRequestRepository.cs +++ b/src/Data/Repositories/Interfaces/IChannelOperationRequestRepository.cs @@ -51,6 +51,12 @@ public interface IChannelOperationRequestRepository : IBitcoinRequestRepository /// Task GetOpenSatsCommittedSince(int sourceNodeId, DateTimeOffset since); + /// + /// split by the peer's pubkey, for the reserved budget shares. + /// A request without a destination node is keyed by the empty string. + /// + Task> GetOpenSatsCommittedByPeerSince(int sourceNodeId, DateTimeOffset since); + Task<(List requests, int totalCount)> GetPaginatedAsync( int pageNumber, int pageSize, diff --git a/src/Data/Repositories/Interfaces/INodeRepository.cs b/src/Data/Repositories/Interfaces/INodeRepository.cs index 9eca83647..cc8e595b1 100644 --- a/src/Data/Repositories/Interfaces/INodeRepository.cs +++ b/src/Data/Repositories/Interfaces/INodeRepository.cs @@ -37,6 +37,11 @@ public interface INodeRepository /// Task> GetNamesByPubKeys(IReadOnlyCollection pubKeys); + /// + /// Every registered node, managed or not, without its relationships. For node pickers. + /// + Task> GetAllForSelection(); + Task> GetAllManagedByUser(string userId); /// diff --git a/src/Data/Repositories/Interfaces/IReservedChannelOpenPeerRepository.cs b/src/Data/Repositories/Interfaces/IReservedChannelOpenPeerRepository.cs new file mode 100644 index 000000000..e17106d1f --- /dev/null +++ b/src/Data/Repositories/Interfaces/IReservedChannelOpenPeerRepository.cs @@ -0,0 +1,34 @@ +/* + * 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 NodeGuard.Data.Models; + +namespace NodeGuard.Data.Repositories.Interfaces; + +public interface IReservedChannelOpenPeerRepository +{ + /// The node's reserved peers, each with its . + Task> GetByNode(int nodeId); + + /// + /// Replaces the node's reserved peers with atomically, so a half-saved list can + /// never push the shares past 100%. + /// + Task<(bool, string?)> ReplaceForNode(int nodeId, IReadOnlyList peers); +} diff --git a/src/Data/Repositories/NodeRepository.cs b/src/Data/Repositories/NodeRepository.cs index ad98352d5..b1542a8c3 100644 --- a/src/Data/Repositories/NodeRepository.cs +++ b/src/Data/Repositories/NodeRepository.cs @@ -73,7 +73,7 @@ public NodeRepository(IRepository repository, .Include(x => x.FundsDestinationWallet) .SingleOrDefaultAsync(x => x.PubKey == key); } - + public async Task GetOrCreateByPubKey(string pubKey, ILightningService lightningService) { @@ -108,11 +108,21 @@ public async Task> GetAll() return await applicationDbContext.Nodes .Include(node => node.Users) - .Include(x=> x.ChannelOperationRequestsAsSource) + .Include(x => x.ChannelOperationRequestsAsSource) .ThenInclude(request => request.Channel) .Include(node => node.ChannelOperationRequestsAsDestination) .ThenInclude(request => request.Channel) - .Include(x=> x.FundsDestinationWallet) + .Include(x => x.FundsDestinationWallet) + .ToListAsync(); + } + + public async Task> GetAllForSelection() + { + await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); + + return await applicationDbContext.Nodes + .AsNoTracking() + .OrderBy(node => node.Name) .ToListAsync(); } @@ -146,15 +156,15 @@ public async Task> GetAllManagedByNodeGuard(bool withDisabled = true) return resultAsync; } - + public async Task> GetAllManagedByUser(string userId) { await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); return await applicationDbContext.Nodes - .Include(x=> x.FundsDestinationWallet) - .Include(x=> x.ChannelOperationRequestsAsDestination) - .Include(x=> x.ChannelOperationRequestsAsSource) + .Include(x => x.FundsDestinationWallet) + .Include(x => x.ChannelOperationRequestsAsDestination) + .Include(x => x.ChannelOperationRequestsAsSource) .Where(node => node.Endpoint != null && node.Users.Any(user => user.Id == userId)) .ToListAsync(); @@ -174,10 +184,10 @@ public async Task> GetAllConfiguredByProvider(SwapProvider provider, query = provider switch { - SwapProvider.Loop => query.Where(node => + SwapProvider.Loop => query.Where(node => !string.IsNullOrEmpty(node.LoopdEndpoint) && !string.IsNullOrEmpty(node.LoopdMacaroon)), - SwapProvider.FortySwap => query.Where(node => + SwapProvider.FortySwap => query.Where(node => !string.IsNullOrEmpty(node.FortySwapEndpoint)), // Spark is NodeGuard's own wallet, not a per-node daemon: any managed LND node can pay into it SwapProvider.Spark => query, @@ -199,7 +209,7 @@ public async Task> GetAllWithAutoLiquidityEnabled() return await applicationDbContext.Nodes .Include(x => x.FundsDestinationWallet) .ThenInclude(x => x.Keys) - .Where(node => !node.IsNodeDisabled && + .Where(node => !node.IsNodeDisabled && node.AutoLiquidityManagementEnabled && node.FundsDestinationWalletId.HasValue) .ToListAsync(); @@ -212,6 +222,8 @@ public async Task> GetAllWithAutoChannelOpenEnabled() return await applicationDbContext.Nodes .Include(x => x.AutoChannelOpenWallet) .ThenInclude(x => x!.Keys) + .Include(x => x.ReservedChannelOpenPeers) + .ThenInclude(x => x.PeerNode) .Where(node => !node.IsNodeDisabled && node.AutoChannelOpenEnabled && node.AutoChannelOpenWalletId.HasValue) diff --git a/src/Data/Repositories/ReservedChannelOpenPeerRepository.cs b/src/Data/Repositories/ReservedChannelOpenPeerRepository.cs new file mode 100644 index 000000000..05fe1de51 --- /dev/null +++ b/src/Data/Repositories/ReservedChannelOpenPeerRepository.cs @@ -0,0 +1,100 @@ +/* + * 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.Models; +using NodeGuard.Data.Repositories.Interfaces; + +namespace NodeGuard.Data.Repositories; + +public class ReservedChannelOpenPeerRepository : IReservedChannelOpenPeerRepository +{ + private readonly IDbContextFactory _dbContextFactory; + private readonly ILogger _logger; + + public ReservedChannelOpenPeerRepository(IDbContextFactory dbContextFactory, + ILogger logger) + { + _dbContextFactory = dbContextFactory; + _logger = logger; + } + + public async Task> GetByNode(int nodeId) + { + await using var context = await _dbContextFactory.CreateDbContextAsync(); + + return await context.ReservedChannelOpenPeers + .Include(x => x.PeerNode) + .Where(x => x.NodeId == nodeId) + .OrderBy(x => x.CreationDatetime) + .ToListAsync(); + } + + public async Task<(bool, string?)> ReplaceForNode(int nodeId, IReadOnlyList peers) + { + await using var context = await _dbContextFactory.CreateDbContextAsync(); + + try + { + // The node row lock makes concurrent replacements take turns: two that both read an empty + // list would both insert, and their shares could add up past 100%. + await using var transaction = context.Database.IsRelational() + ? await context.Database.BeginTransactionAsync() + : null; + if (transaction != null) + { + await context.Database.ExecuteSqlAsync($"SELECT 1 FROM \"Nodes\" WHERE \"Id\" = {nodeId} FOR UPDATE"); + } + + var existing = await context.ReservedChannelOpenPeers + .Where(x => x.NodeId == nodeId) + .ToListAsync(); + context.ReservedChannelOpenPeers.RemoveRange(existing); + + foreach (var peer in peers) + { + var row = new ReservedChannelOpenPeer + { + NodeId = nodeId, + PeerNodeId = peer.PeerNodeId, + BudgetPct = peer.BudgetPct, + FeeRatePpm = peer.FeeRatePpm, + BaseFeeMsat = peer.BaseFeeMsat + }; + row.SetCreationDatetime(); + row.SetUpdateDatetime(); + await context.ReservedChannelOpenPeers.AddAsync(row); + } + + // EF orders a deleted row before the insert that reuses its unique key. + await context.SaveChangesAsync(); + if (transaction != null) + { + await transaction.CommitAsync(); + } + + return (true, null); + } + catch (Exception e) + { + _logger.LogError(e, "Error saving the reserved channel open peers of node {NodeId}", nodeId); + return (false, e.Message); + } + } +} diff --git a/src/Helpers/ValidationHelper.cs b/src/Helpers/ValidationHelper.cs index 3ff4f3254..2e5c2b167 100644 --- a/src/Helpers/ValidationHelper.cs +++ b/src/Helpers/ValidationHelper.cs @@ -181,4 +181,48 @@ public static bool IsValidEmail(string email) return false; } } + + /// + /// The first problem with a node's reserved channel open peers, or null when there is none. + /// + public static string? ValidateReservedChannelOpenPeers(IReadOnlyList peers, int nodeId) + { + foreach (var peer in peers) + { + if (peer.PeerNodeId <= 0) + { + return "Choose a node for every reserved peer"; + } + + if (peer.PeerNodeId == nodeId) + { + return "A node can't be a reserved peer of itself"; + } + + if (peer.BudgetPct is < 1 or > 100) + { + return "Every reserved peer's budget share must be between 1 and 100%"; + } + + if (peer.FeeRatePpm is null || peer.BaseFeeMsat is null) + { + return "Set a fee rate and a base fee for every reserved peer"; + } + + if (peer.FeeRatePpm < 0 || peer.BaseFeeMsat < 0) + { + return "A reserved peer's fee rate and base fee can't be negative"; + } + } + + if (peers.GroupBy(x => x.PeerNodeId).Any(x => x.Count() > 1)) + { + return "A peer is reserved more than once"; + } + + var totalPct = peers.Sum(x => x.BudgetPct); + return totalPct > 100 + ? $"The reserved budget shares add up to {totalPct}%, above 100%" + : null; + } } \ No newline at end of file diff --git a/src/Jobs/AutoChannelOpenJob.cs b/src/Jobs/AutoChannelOpenJob.cs index 4b3c02d01..25aa1a152 100644 --- a/src/Jobs/AutoChannelOpenJob.cs +++ b/src/Jobs/AutoChannelOpenJob.cs @@ -155,8 +155,8 @@ private async Task ProcessNode(Node node, decimal feeRate) return; } - var remainingBudget = await GetRemainingBudget(node, now); - if (remainingBudget <= 0) + var budget = await GetBudget(node, now); + if (budget == null || budget.IsExhausted) { _logger.LogInformation("Node {NodeName}: channel open budget exhausted", node.Name); return; @@ -170,7 +170,7 @@ private async Task ProcessNode(Node node, decimal feeRate) } var walletSpendableSats = await GetWalletSpendableSats(node, feeRate); - var tunables = ChannelOpenInitiatorTunables.FromConstants(node, walletSpendableSats, remainingBudget); + var tunables = ChannelOpenInitiatorTunables.FromConstants(node, walletSpendableSats, budget); var classification = ChannelOpenInitiatorService.Evaluate(peers, tunables); foreach (var rejection in classification.Rejected) @@ -189,24 +189,26 @@ private async Task ProcessNode(Node node, decimal feeRate) // run — otherwise a per-run cap above 1 would commit the budget once per plan. foreach (var plan in classification.Plans) { - if (plan.SuggestedCapacitySats > remainingBudget) + var headroom = budget.HeadroomFor(plan.PeerPubKey); + if (plan.SuggestedCapacitySats > headroom) { - _logger.LogInformation("Node {NodeName}: skipping a {Capacity} sats plan, only {Remaining} sats of budget left", - node.Name, plan.SuggestedCapacitySats, remainingBudget); + _logger.LogInformation("Node {NodeName}: skipping a {Capacity} sats plan to {Peer}, only {Remaining} sats of budget left for it", + node.Name, plan.SuggestedCapacitySats, plan.PeerPubKey, headroom); continue; } if (await RecordAndMaybePromote(node, plan, localBalanceSats)) { - remainingBudget -= plan.SuggestedCapacitySats; + budget.Spend(plan.PeerPubKey, plan.SuggestedCapacitySats); localBalanceSats += plan.SuggestedCapacitySats; } } } /// - /// One snapshot per peer that refused forwards in the shortage window. Every input is fetched once - /// for the whole node, never per channel. + /// One snapshot per peer that refused forwards in the shortage window, and one per reserved peer + /// whatever its evidence, channel or not. Every input is fetched once for the whole node, never per + /// channel. /// private async Task> BuildPeerSnapshots(Node node, DateTimeOffset now) { @@ -221,8 +223,12 @@ private async Task> BuildPeerSnapshots(Node node, DateTimeOff var lastDecisionTask = _recommendationRepository.GetLastDecisionByPeer(node.Id); await Task.WhenAll(refusalsTask, feesTask, outTask, listChannelsTask, policyTask, lastDecisionTask); + // Each reserved peer with the fee its channel opens at when we charge it nothing yet. + var reserved = (node.ReservedChannelOpenPeers ?? []) + .ToDictionary(x => x.PeerNode!.PubKey, x => new LocalOutboundPolicy(x.FeeRatePpm ?? 0, x.BaseFeeMsat ?? 0)); + var refusalsByChanId = refusalsTask.Result; - if (refusalsByChanId.Count == 0) + if (refusalsByChanId.Count == 0 && reserved.Count == 0) { return []; } @@ -242,10 +248,19 @@ private async Task> BuildPeerSnapshots(Node node, DateTimeOff // Fees and refusals on channels that have since closed are dropped with them: only the peer's // current channels map back to a pubkey. - return listChannels.Channels + var channelsByPeer = listChannels.Channels .GroupBy(x => x.RemotePubkey) - .Select(peerChannels => (Peer: peerChannels.Key, Channels: peerChannels.ToList())) - .Where(x => x.Channels.Sum(c => refusalsByChanId.GetValueOrDefault(c.ChanId)) > 0) + .ToDictionary(x => x.Key, x => x.ToList()); + + // A reserved peer with no channel yet still gets a snapshot, empty, so its first channel opens. + foreach (var peer in reserved.Keys.Where(x => !channelsByPeer.ContainsKey(x))) + { + channelsByPeer[peer] = []; + } + + return channelsByPeer + .Select(peerChannels => (Peer: peerChannels.Key, Channels: peerChannels.Value)) + .Where(x => reserved.ContainsKey(x.Peer) || x.Channels.Sum(c => refusalsByChanId.GetValueOrDefault(c.ChanId)) > 0) .Select(x => new PeerSnapshot( PeerPubKey: x.Peer, EarnedFeeSats: x.Channels.Sum(c => feesByChanId.GetValueOrDefault(c.ChanId)) / 1000, @@ -255,12 +270,14 @@ private async Task> BuildPeerSnapshots(Node node, DateTimeOff // most of what local_balance reports. UsableLocalSats: x.Channels.Sum(c => Math.Max(0, c.LocalBalance - c.LocalChanReserveSat)), CapacitySats: x.Channels.Sum(c => c.Capacity), - // The highest rate, with the base fee from that same channel rather than a mix. + // The highest rate, with the base fee from that same channel rather than a mix. A reserved + // peer with none to copy falls back to the fee set on its reservation. OutboundPolicy: x.Channels .Select(c => policyByChanId != null && policyByChanId.TryGetValue(c.ChanId, out var p) ? p : null) .Where(p => p != null) - .MaxBy(p => p!.FeeRatePpm), - OnCooldown: lastDecisionByPeer.TryGetValue(x.Peer, out var last) && last > cooldownCutoff)) + .MaxBy(p => p!.FeeRatePpm) ?? reserved.GetValueOrDefault(x.Peer), + OnCooldown: lastDecisionByPeer.TryGetValue(x.Peer, out var last) && last > cooldownCutoff, + IsReserved: reserved.ContainsKey(x.Peer))) .ToList(); } @@ -282,15 +299,16 @@ private async Task GetWalletSpendableSats(Node node, decimal feeRate) } /// - /// Rolls the budget period over and persists it when elapsed — a Get that writes. + /// Rolls the budget period over and persists it when elapsed — a Get that writes. Null when the node + /// has no budget. /// - private async Task GetRemainingBudget(Node node, DateTimeOffset now) + private async Task GetBudget(Node node, DateTimeOffset now) { var budgetSats = node.AutoChannelOpenBudgetSats ?? 0; if (budgetSats <= 0) { _logger.LogInformation("Node {NodeName}: no channel open budget configured; skipping", node.Name); - return 0; + return null; } var refreshInterval = node.AutoChannelOpenBudgetRefreshInterval @@ -304,9 +322,11 @@ private async Task GetRemainingBudget(Node node, DateTimeOffset now) } var periodStart = node.AutoChannelOpenBudgetStartDatetime ?? now; - var committed = await _channelOperationRequestRepository.GetOpenSatsCommittedSince(node.Id, periodStart); + var committedByPeer = await _channelOperationRequestRepository.GetOpenSatsCommittedByPeerSince(node.Id, periodStart); + var reservedPctByPeer = (node.ReservedChannelOpenPeers ?? []) + .ToDictionary(x => x.PeerNode!.PubKey, x => x.BudgetPct); - return budgetSats - committed; + return ChannelOpenBudget.Build(budgetSats, reservedPctByPeer, committedByPeer); } /// @@ -355,6 +375,7 @@ await _auditService.LogAsync( plan.Refusals, plan.UsableLocalSats, plan.PeerCapacitySats, + plan.IsReservedPeer, Description = $"Channel open recommended to {plan.PeerPubKey} for {plan.SuggestedCapacitySats} sats" }); diff --git a/src/Migrations/20261127161511_AddReservedChannelOpenPeers.Designer.cs b/src/Migrations/20261127161511_AddReservedChannelOpenPeers.Designer.cs new file mode 100644 index 000000000..3dabd0a1f --- /dev/null +++ b/src/Migrations/20261127161511_AddReservedChannelOpenPeers.Designer.cs @@ -0,0 +1,2238 @@ +// +using System; +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using NodeGuard.Data; +using NodeGuard.Helpers; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace NodeGuard.Migrations +{ + [DbContext(typeof(ApplicationDbContext))] + [Migration("20261127161511_AddReservedChannelOpenPeers")] + partial class AddReservedChannelOpenPeers + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.1") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("ApplicationUserNode", b => + { + b.Property("NodesId") + .HasColumnType("integer"); + + b.Property("UsersId") + .HasColumnType("text"); + + b.HasKey("NodesId", "UsersId"); + + b.HasIndex("UsersId"); + + b.ToTable("ApplicationUserNode"); + }); + + modelBuilder.Entity("ChannelOperationRequestFMUTXO", b => + { + b.Property("ChannelOperationRequestsId") + .HasColumnType("integer"); + + b.Property("UtxosId") + .HasColumnType("integer"); + + b.HasKey("ChannelOperationRequestsId", "UtxosId"); + + b.HasIndex("UtxosId"); + + b.ToTable("ChannelOperationRequestFMUTXO"); + }); + + modelBuilder.Entity("FMUTXOWalletWithdrawalRequest", b => + { + b.Property("UTXOsId") + .HasColumnType("integer"); + + b.Property("WalletWithdrawalRequestsId") + .HasColumnType("integer"); + + b.HasKey("UTXOsId", "WalletWithdrawalRequestsId"); + + b.HasIndex("WalletWithdrawalRequestsId"); + + b.ToTable("FMUTXOWalletWithdrawalRequest"); + }); + + modelBuilder.Entity("KeyWallet", b => + { + b.Property("KeysId") + .HasColumnType("integer"); + + b.Property("WalletsId") + .HasColumnType("integer"); + + b.HasKey("KeysId", "WalletsId"); + + b.HasIndex("WalletsId"); + + b.ToTable("KeyWallet"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Discriminator") + .IsRequired() + .HasMaxLength(21) + .HasColumnType("character varying(21)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + + b.HasDiscriminator().HasValue("IdentityUser"); + + b.UseTphMappingStrategy(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProviderKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Name") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.APIToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatorId") + .IsRequired() + .HasColumnType("text"); + + b.Property("ExpirationDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsBlocked") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CreatorId"); + + b.ToTable("ApiTokens"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ActionType") + .HasColumnType("integer"); + + b.Property("Details") + .HasColumnType("text"); + + b.Property("EventType") + .HasColumnType("integer"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("character varying(45)"); + + b.Property("ObjectAffected") + .HasColumnType("integer"); + + b.Property("ObjectId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("Username") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.ToTable("AuditLogs"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Channel", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BtcCloseAddress") + .HasColumnType("text"); + + b.Property("ChanId") + .HasColumnType("numeric(20,0)"); + + b.Property("ClosedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByNodeGuard") + .HasColumnType("boolean"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("DestinationNodeId") + .HasColumnType("integer"); + + b.Property("FundingTx") + .IsRequired() + .HasColumnType("text"); + + b.Property("FundingTxOutputIndex") + .HasColumnType("bigint"); + + b.Property("IsAutoRebalanceEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsAutomatedLiquidityEnabled") + .HasColumnType("boolean"); + + b.Property("IsDynamicFeeEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsPrivate") + .HasColumnType("boolean"); + + b.Property("SatsAmount") + .HasColumnType("bigint"); + + b.Property("SourceNodeId") + .HasColumnType("integer"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("DestinationNodeId"); + + b.HasIndex("SourceNodeId"); + + b.ToTable("Channels"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelFeeState", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ChannelId") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("LastAppliedInboundBaseMsat") + .HasColumnType("integer"); + + b.Property("LastAppliedInboundPpm") + .HasColumnType("integer"); + + b.Property("LastAppliedOutboundBaseFeeMsat") + .HasColumnType("bigint"); + + b.Property("LastAppliedOutboundPpm") + .HasColumnType("bigint"); + + b.Property("LastComputedTarget") + .HasColumnType("double precision"); + + b.Property("LastFeeUpdateAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastObservedRatio") + .HasColumnType("double precision"); + + b.Property("ManagedNodePubKey") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ChannelId", "ManagedNodePubKey") + .IsUnique(); + + b.ToTable("ChannelFeeStates"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOpenRecommendation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ChannelOperationRequestId") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("DismissReason") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("EarnedFeeSats") + .HasColumnType("bigint"); + + b.Property("InheritedBaseFeeMsat") + .HasColumnType("bigint"); + + b.Property("InheritedFeeRatePpm") + .HasColumnType("bigint"); + + b.Property("IsReservedPeer") + .HasColumnType("boolean"); + + b.Property("LastEvidenceAt") + .HasColumnType("timestamp with time zone"); + + b.Property("NodeId") + .HasColumnType("integer"); + + b.Property("PeerCapacitySats") + .HasColumnType("bigint"); + + b.Property("PeerPubKey") + .IsRequired() + .HasMaxLength(66) + .HasColumnType("character varying(66)"); + + b.Property("Refusals") + .HasColumnType("integer"); + + b.Property("SettledOutSats") + .HasColumnType("bigint"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("SuggestedCapacitySats") + .HasColumnType("bigint"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UsableLocalSats") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("ChannelOperationRequestId"); + + b.HasIndex("NodeId", "PeerPubKey") + .IsUnique(); + + b.ToTable("ChannelOpenRecommendations"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOperationRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AmountCryptoUnit") + .HasColumnType("integer"); + + b.Property("Changeless") + .HasColumnType("boolean"); + + b.Property("ChannelId") + .HasColumnType("integer"); + + b.Property("ClosingReason") + .HasColumnType("text"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DestNodeId") + .HasColumnType("integer"); + + b.Property("FeeRate") + .HasColumnType("numeric"); + + b.Property("InitialChannelBaseFeeMsat") + .HasColumnType("bigint"); + + b.Property("InitialChannelFeeRatePpm") + .HasColumnType("bigint"); + + b.Property("IsChannelPrivate") + .HasColumnType("boolean"); + + b.Property("MempoolRecommendedFeesType") + .HasColumnType("integer"); + + b.Property("RequestType") + .HasColumnType("integer"); + + b.Property("SatsAmount") + .HasColumnType("bigint"); + + b.Property("SourceNodeId") + .HasColumnType("integer"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property>("StatusLogs") + .HasColumnType("jsonb"); + + b.Property("TxId") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("text"); + + b.Property("WalletId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ChannelId"); + + b.HasIndex("DestNodeId"); + + b.HasIndex("SourceNodeId"); + + b.HasIndex("UserId"); + + b.HasIndex("WalletId"); + + b.ToTable("ChannelOperationRequests"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOperationRequestPSBT", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ChannelOperationRequestId") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("IsFinalisedPSBT") + .HasColumnType("boolean"); + + b.Property("IsInternalWalletPSBT") + .HasColumnType("boolean"); + + b.Property("IsTemplatePSBT") + .HasColumnType("boolean"); + + b.Property("PSBT") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserSignerId") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ChannelOperationRequestId"); + + b.HasIndex("UserSignerId"); + + b.HasIndex(new[] { "ChannelOperationRequestId" }, "IX_ChannelOperationRequestPSBTs_Template") + .IsUnique() + .HasFilter("\"IsTemplatePSBT\""); + + b.ToTable("ChannelOperationRequestPSBTs"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelRoutingState", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AgeBlocks") + .HasColumnType("bigint"); + + b.Property("ChanIdLnd") + .HasColumnType("numeric(20,0)"); + + b.Property("ChannelId") + .HasColumnType("integer"); + + b.Property("ConsecutiveCategoryCyclesInNewState") + .HasColumnType("bigint"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("EmaLocalRatio") + .HasColumnType("double precision"); + + b.Property("FundingBlockHeight") + .HasColumnType("bigint"); + + b.Property("LastCategorizedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastEvaluatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastKnownLifetime") + .HasColumnType("bigint"); + + b.Property("LastKnownNumUpdates") + .HasColumnType("bigint"); + + b.Property("LastKnownUptime") + .HasColumnType("bigint"); + + b.Property("ManagedNodePubKey") + .IsRequired() + .HasColumnType("text"); + + b.Property("NetFlowRatio") + .HasColumnType("double precision"); + + b.Property("PeerFlowCategory") + .HasColumnType("integer"); + + b.Property("PeerInitiated") + .HasColumnType("boolean"); + + b.Property("PendingCategory") + .HasColumnType("integer"); + + b.Property("PullMsatWindow") + .HasColumnType("bigint"); + + b.Property("PushMsatWindow") + .HasColumnType("bigint"); + + b.Property("TargetLocalRatio") + .HasColumnType("double precision"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ChannelId", "ManagedNodePubKey") + .IsUnique(); + + b.ToTable("ChannelRoutingStates"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.FMUTXO", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("OutputIndex") + .HasColumnType("bigint"); + + b.Property("SatsAmount") + .HasColumnType("bigint"); + + b.Property("TxId") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.ToTable("FMUTXOs"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ForwardingHtlcEvent", b => + { + b.Property("ManagedNodePubKey") + .HasColumnType("text"); + + b.Property("IncomingChannelId") + .HasColumnType("numeric(20,0)"); + + b.Property("OutgoingChannelId") + .HasColumnType("numeric(20,0)"); + + b.Property("IncomingHtlcId") + .HasColumnType("numeric(20,0)"); + + b.Property("OutgoingHtlcId") + .HasColumnType("numeric(20,0)"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("EventCase") + .HasColumnType("integer"); + + b.Property("EventTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("EventType") + .HasColumnType("integer"); + + b.Property("FailureDetail") + .HasColumnType("integer"); + + b.Property("FailureString") + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("FeeMsat") + .HasColumnType("bigint"); + + b.Property("GrossFeeMsat") + .HasColumnType("bigint"); + + b.Property("InboundFeeMsat") + .HasColumnType("bigint"); + + b.Property("InboundFeePpm") + .HasColumnType("bigint"); + + b.Property("IncomingAmountMsat") + .HasColumnType("numeric(20,0)"); + + b.Property("IncomingPeerAlias") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IncomingTimelock") + .HasColumnType("bigint"); + + b.Property("ManagedNodeName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Outcome") + .HasColumnType("integer"); + + b.Property("OutgoingAmountMsat") + .HasColumnType("numeric(20,0)"); + + b.Property("OutgoingPeerAlias") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("OutgoingTimelock") + .HasColumnType("bigint"); + + b.Property("RoutingFeePpm") + .HasColumnType("bigint"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("WireFailureCode") + .HasColumnType("integer"); + + b.HasKey("ManagedNodePubKey", "IncomingChannelId", "OutgoingChannelId", "IncomingHtlcId", "OutgoingHtlcId"); + + b.HasIndex("CreationDatetime"); + + b.HasIndex("EventTimestamp"); + + b.ToTable("ForwardingHtlcEvents"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.InternalWallet", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("DerivationPath") + .IsRequired() + .HasColumnType("text"); + + b.Property("MasterFingerprint") + .HasColumnType("text"); + + b.Property("MnemonicString") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("XPUB") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("InternalWallets"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Key", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("InternalWalletId") + .HasColumnType("integer"); + + b.Property("IsArchived") + .HasColumnType("boolean"); + + b.Property("IsBIP39ImportedKey") + .HasColumnType("boolean"); + + b.Property("IsCompromised") + .HasColumnType("boolean"); + + b.Property("MasterFingerprint") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("Path") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("text"); + + b.Property("XPUB") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("InternalWalletId"); + + b.HasIndex("UserId"); + + b.ToTable("Keys"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.LiquidityRule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ChannelId") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("IsReverseSwapWalletRule") + .HasColumnType("boolean"); + + b.Property("MinimumLocalBalance") + .HasColumnType("numeric"); + + b.Property("MinimumRemoteBalance") + .HasColumnType("numeric"); + + b.Property("NodeId") + .HasColumnType("integer"); + + b.Property("RebalanceTarget") + .HasColumnType("numeric"); + + b.Property("ReverseSwapAddress") + .HasColumnType("text"); + + b.Property("ReverseSwapWalletId") + .HasColumnType("integer"); + + b.Property("SwapWalletId") + .HasColumnType("integer"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ChannelId") + .IsUnique(); + + b.HasIndex("NodeId"); + + b.HasIndex("ReverseSwapWalletId"); + + b.HasIndex("SwapWalletId"); + + b.ToTable("LiquidityRules"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Node", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AllowPositiveInboundFees") + .HasColumnType("boolean"); + + b.Property("AutoChannelOpenBudgetRefreshInterval") + .HasColumnType("interval"); + + b.Property("AutoChannelOpenBudgetSats") + .HasColumnType("bigint"); + + b.Property("AutoChannelOpenBudgetStartDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("AutoChannelOpenEnabled") + .HasColumnType("boolean"); + + b.Property("AutoChannelOpenMode") + .HasColumnType("integer"); + + b.Property("AutoChannelOpenSizeSats") + .HasColumnType("bigint"); + + b.Property("AutoChannelOpenWalletId") + .HasColumnType("integer"); + + b.Property("AutoLiquidityManagementEnabled") + .HasColumnType("boolean"); + + b.Property("AutoRebalanceEnabled") + .HasColumnType("boolean"); + + b.Property("AutosweepEnabled") + .HasColumnType("boolean"); + + b.Property("ChannelAdminMacaroon") + .HasColumnType("text"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DynamicFeeManagementEnabled") + .HasColumnType("boolean"); + + b.Property("Endpoint") + .HasColumnType("text"); + + b.Property("FortySwapEndpoint") + .HasColumnType("text"); + + b.Property("FortySwapMaxAmountSats") + .HasColumnType("bigint"); + + b.Property("FortySwapMaxSwapRoutingFeeRatio") + .HasColumnType("numeric"); + + b.Property("FortySwapMaxSwapsInFlight") + .HasColumnType("integer"); + + b.Property("FortySwapMinAmountSats") + .HasColumnType("bigint"); + + b.Property("FortySwapWeight") + .HasColumnType("integer"); + + b.Property("FundsDestinationWalletId") + .HasColumnType("integer"); + + b.Property("IsNodeDisabled") + .HasColumnType("boolean"); + + b.Property("LoopMaxSwapRoutingFeeRatio") + .HasColumnType("numeric"); + + b.Property("LoopMaxSwapsInFlight") + .HasColumnType("integer"); + + b.Property("LoopSwapMaxAmountSats") + .HasColumnType("bigint"); + + b.Property("LoopSwapMinAmountSats") + .HasColumnType("bigint"); + + b.Property("LoopSwapWeight") + .HasColumnType("integer"); + + b.Property("LoopdCert") + .HasColumnType("text"); + + b.Property("LoopdEndpoint") + .HasColumnType("text"); + + b.Property("LoopdMacaroon") + .HasColumnType("text"); + + b.Property("MaxRebalanceCostToEarnRatio") + .HasColumnType("double precision"); + + b.Property("MaxRebalancesInFlight") + .HasColumnType("integer"); + + b.Property("MinimumBalanceThresholdSats") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("PubKey") + .IsRequired() + .HasColumnType("text"); + + b.Property("RebalanceBudgetRefreshInterval") + .HasColumnType("interval"); + + b.Property("RebalanceBudgetSats") + .HasColumnType("bigint"); + + b.Property("RebalanceBudgetStartDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("RoutingEngineDryRun") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("SparkMaxSwapRoutingFeeRatio") + .HasColumnType("numeric"); + + b.Property("SparkMaxSwapsInFlight") + .HasColumnType("integer"); + + b.Property("SparkPaymentTimeoutMinutes") + .HasColumnType("integer"); + + b.Property("SparkSwapMaxAmountSats") + .HasColumnType("bigint"); + + b.Property("SparkSwapMinAmountSats") + .HasColumnType("bigint"); + + b.Property("SparkSwapWeight") + .HasColumnType("integer"); + + b.Property("SparkWalletId") + .HasColumnType("integer"); + + b.Property("SwapBudgetRefreshInterval") + .HasColumnType("interval"); + + b.Property("SwapBudgetSats") + .HasColumnType("bigint"); + + b.Property("SwapBudgetStartDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AutoChannelOpenWalletId"); + + b.HasIndex("FundsDestinationWalletId"); + + b.HasIndex("PubKey") + .IsUnique(); + + b.HasIndex("SparkWalletId"); + + b.ToTable("Nodes"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Rebalance", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AmountBackoffRatio") + .HasColumnType("double precision"); + + b.Property("AttemptNumber") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("FeePaidMsat") + .HasColumnType("bigint"); + + b.Property("FeePaidSats") + .HasColumnType("bigint"); + + b.Property("IsManual") + .HasColumnType("boolean"); + + b.Property("MaxAttempts") + .HasColumnType("integer"); + + b.Property("MaxFeePct") + .HasColumnType("double precision"); + + b.Property("NodeId") + .HasColumnType("integer"); + + b.Property("PaymentHashHex") + .HasColumnType("text"); + + b.Property("PaymentRequest") + .HasColumnType("text"); + + b.Property("PreimageHex") + .HasColumnType("text"); + + b.Property("RequestedAmountSats") + .HasColumnType("bigint"); + + b.Property("RetryMaxFeePct") + .HasColumnType("double precision"); + + b.Property("SatsAmount") + .HasColumnType("bigint"); + + b.Property("SourceChanIdLnd") + .HasColumnType("numeric(20,0)"); + + b.Property("SourceChannelId") + .HasColumnType("integer"); + + b.Property("SourceNodePubKey") + .HasColumnType("text"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TargetPubkey") + .HasColumnType("text"); + + b.Property("TimeoutSeconds") + .HasColumnType("integer"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserRequestorId") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("NodeId"); + + b.HasIndex("SourceChannelId"); + + b.HasIndex("UserRequestorId"); + + b.ToTable("Rebalances"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ReservedChannelOpenPeer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BudgetPct") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("NodeId") + .HasColumnType("integer"); + + b.Property("PeerNodeId") + .HasColumnType("integer"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("PeerNodeId"); + + b.HasIndex("NodeId", "PeerNodeId") + .IsUnique(); + + b.ToTable("ReservedChannelOpenPeers"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.SparkSignerIdentity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Account") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("IdentityPublicKey") + .IsRequired() + .HasColumnType("text"); + + b.Property("SeedFingerprint") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("SeedFingerprint", "Account") + .IsUnique(); + + b.ToTable("SparkSignerIdentities"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.SwapOut", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("DestinationAddress") + .HasColumnType("text"); + + b.Property("DestinationWalletId") + .HasColumnType("integer"); + + b.Property("ErrorDetails") + .HasColumnType("text"); + + b.Property("IsManual") + .HasColumnType("boolean"); + + b.Property("LightningFeeSats") + .HasColumnType("bigint"); + + b.Property("NodeId") + .HasColumnType("integer"); + + b.Property("OnChainFeeSats") + .HasColumnType("bigint"); + + b.Property("PaymentHash") + .HasColumnType("text"); + + b.Property("PayoutSats") + .HasColumnType("bigint"); + + b.Property("Provider") + .HasColumnType("integer"); + + b.Property("ProviderId") + .HasColumnType("text"); + + b.Property("ReferenceId") + .HasColumnType("text"); + + b.Property("SatsAmount") + .HasColumnType("bigint"); + + b.Property("ServiceFeeSats") + .HasColumnType("bigint"); + + b.Property("SparkExitDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("SparkIdentity") + .HasColumnType("text"); + + b.Property("SparkLeafIds") + .HasColumnType("text"); + + b.Property("SparkReceivedSats") + .HasColumnType("bigint"); + + b.Property("SparkTransferId") + .HasColumnType("text"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TxId") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserRequestorId") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("DestinationWalletId"); + + b.HasIndex("NodeId"); + + b.HasIndex("ReferenceId") + .IsUnique() + .HasFilter("\"ReferenceId\" IS NOT NULL"); + + b.HasIndex("UserRequestorId"); + + b.ToTable("SwapOuts"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.UTXOTag", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Key") + .IsRequired() + .HasColumnType("text"); + + b.Property("Outpoint") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Key", "Outpoint") + .IsUnique(); + + b.ToTable("UTXOTags"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Wallet", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BIP39Seedphrase") + .HasColumnType("text"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("ImportedOutputDescriptor") + .HasColumnType("text"); + + b.Property("InternalWalletId") + .HasColumnType("integer"); + + b.Property("InternalWalletMasterFingerprint") + .HasColumnType("text"); + + b.Property("InternalWalletSubDerivationPath") + .HasColumnType("text"); + + b.Property("IsArchived") + .HasColumnType("boolean"); + + b.Property("IsBIP39Imported") + .HasColumnType("boolean"); + + b.Property("IsCompromised") + .HasColumnType("boolean"); + + b.Property("IsFinalised") + .HasColumnType("boolean"); + + b.Property("IsHotWallet") + .HasColumnType("boolean"); + + b.Property("IsUnSortedMultiSig") + .HasColumnType("boolean"); + + b.Property("Kind") + .HasColumnType("integer"); + + b.Property("MofN") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ReferenceId") + .HasColumnType("text"); + + b.Property("SparkAccount") + .HasColumnType("integer"); + + b.Property("SparkEncryptedMnemonic") + .HasColumnType("text"); + + b.Property("SparkIdentityPublicKey") + .HasColumnType("text"); + + b.Property("SparkMaxBalanceSats") + .HasColumnType("bigint"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("WalletAddressType") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("InternalWalletId"); + + b.HasIndex("InternalWalletSubDerivationPath", "InternalWalletMasterFingerprint") + .IsUnique(); + + b.ToTable("Wallets"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BumpingWalletWithdrawalRequestId") + .HasColumnType("integer"); + + b.Property("Changeless") + .HasColumnType("boolean"); + + b.Property("CoinSelectionStrategy") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("CustomFeeRate") + .HasColumnType("numeric"); + + b.Property("Description") + .IsRequired() + .HasColumnType("text"); + + b.Property("IsRbfCancellation") + .HasColumnType("boolean"); + + b.Property("MempoolRecommendedFeesType") + .HasColumnType("integer"); + + b.Property("ReferenceId") + .HasColumnType("text"); + + b.Property("RejectCancelDescription") + .HasColumnType("text"); + + b.Property("RequestMetadata") + .HasColumnType("text"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TxId") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserRequestorId") + .HasColumnType("text"); + + b.Property("WalletId") + .HasColumnType("integer"); + + b.Property("WithdrawAllFunds") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("BumpingWalletWithdrawalRequestId"); + + b.HasIndex("UserRequestorId"); + + b.HasIndex("WalletId"); + + b.ToTable("WalletWithdrawalRequests"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequestDestination", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasColumnType("text"); + + b.Property("Amount") + .HasColumnType("numeric"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("WalletWithdrawalRequestId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("WalletWithdrawalRequestId"); + + b.ToTable("WalletWithdrawalRequestDestinations"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequestPSBT", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("IsFinalisedPSBT") + .HasColumnType("boolean"); + + b.Property("IsInternalWalletPSBT") + .HasColumnType("boolean"); + + b.Property("IsTemplatePSBT") + .HasColumnType("boolean"); + + b.Property("PSBT") + .IsRequired() + .HasColumnType("text"); + + b.Property("SignerId") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("WalletWithdrawalRequestId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("SignerId"); + + b.HasIndex("WalletWithdrawalRequestId"); + + b.HasIndex(new[] { "WalletWithdrawalRequestId" }, "IX_WalletWithdrawalRequestPSBTs_Template") + .IsUnique() + .HasFilter("\"IsTemplatePSBT\""); + + b.ToTable("WalletWithdrawalRequestPSBTs"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ApplicationUser", b => + { + b.HasBaseType("Microsoft.AspNetCore.Identity.IdentityUser"); + + b.HasDiscriminator().HasValue("ApplicationUser"); + }); + + modelBuilder.Entity("ApplicationUserNode", b => + { + b.HasOne("NodeGuard.Data.Models.Node", null) + .WithMany() + .HasForeignKey("NodesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", null) + .WithMany() + .HasForeignKey("UsersId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ChannelOperationRequestFMUTXO", b => + { + b.HasOne("NodeGuard.Data.Models.ChannelOperationRequest", null) + .WithMany() + .HasForeignKey("ChannelOperationRequestsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.FMUTXO", null) + .WithMany() + .HasForeignKey("UtxosId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("FMUTXOWalletWithdrawalRequest", b => + { + b.HasOne("NodeGuard.Data.Models.FMUTXO", null) + .WithMany() + .HasForeignKey("UTXOsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.WalletWithdrawalRequest", null) + .WithMany() + .HasForeignKey("WalletWithdrawalRequestsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("KeyWallet", b => + { + b.HasOne("NodeGuard.Data.Models.Key", null) + .WithMany() + .HasForeignKey("KeysId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Wallet", null) + .WithMany() + .HasForeignKey("WalletsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.APIToken", b => + { + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "Creator") + .WithMany() + .HasForeignKey("CreatorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Creator"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Channel", b => + { + b.HasOne("NodeGuard.Data.Models.Node", "DestinationNode") + .WithMany() + .HasForeignKey("DestinationNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Node", "SourceNode") + .WithMany() + .HasForeignKey("SourceNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DestinationNode"); + + b.Navigation("SourceNode"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelFeeState", b => + { + b.HasOne("NodeGuard.Data.Models.Channel", "Channel") + .WithMany() + .HasForeignKey("ChannelId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Channel"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOpenRecommendation", b => + { + b.HasOne("NodeGuard.Data.Models.ChannelOperationRequest", "ChannelOperationRequest") + .WithMany() + .HasForeignKey("ChannelOperationRequestId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("NodeGuard.Data.Models.Node", "Node") + .WithMany("ChannelOpenRecommendations") + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ChannelOperationRequest"); + + b.Navigation("Node"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOperationRequest", b => + { + b.HasOne("NodeGuard.Data.Models.Channel", "Channel") + .WithMany("ChannelOperationRequests") + .HasForeignKey("ChannelId"); + + b.HasOne("NodeGuard.Data.Models.Node", "DestNode") + .WithMany("ChannelOperationRequestsAsDestination") + .HasForeignKey("DestNodeId"); + + b.HasOne("NodeGuard.Data.Models.Node", "SourceNode") + .WithMany("ChannelOperationRequestsAsSource") + .HasForeignKey("SourceNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "User") + .WithMany("ChannelOperationRequests") + .HasForeignKey("UserId"); + + b.HasOne("NodeGuard.Data.Models.Wallet", "Wallet") + .WithMany("ChannelOperationRequestsAsSource") + .HasForeignKey("WalletId"); + + b.Navigation("Channel"); + + b.Navigation("DestNode"); + + b.Navigation("SourceNode"); + + b.Navigation("User"); + + b.Navigation("Wallet"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOperationRequestPSBT", b => + { + b.HasOne("NodeGuard.Data.Models.ChannelOperationRequest", "ChannelOperationRequest") + .WithMany("ChannelOperationRequestPsbts") + .HasForeignKey("ChannelOperationRequestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "UserSigner") + .WithMany() + .HasForeignKey("UserSignerId"); + + b.Navigation("ChannelOperationRequest"); + + b.Navigation("UserSigner"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelRoutingState", b => + { + b.HasOne("NodeGuard.Data.Models.Channel", "Channel") + .WithMany() + .HasForeignKey("ChannelId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Channel"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Key", b => + { + b.HasOne("NodeGuard.Data.Models.InternalWallet", "InternalWallet") + .WithMany() + .HasForeignKey("InternalWalletId"); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "User") + .WithMany("Keys") + .HasForeignKey("UserId"); + + b.Navigation("InternalWallet"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.LiquidityRule", b => + { + b.HasOne("NodeGuard.Data.Models.Channel", "Channel") + .WithMany("LiquidityRules") + .HasForeignKey("ChannelId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Node", "Node") + .WithMany() + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Wallet", "ReverseSwapWallet") + .WithMany("LiquidityRulesAsReverseSwapWallet") + .HasForeignKey("ReverseSwapWalletId"); + + b.HasOne("NodeGuard.Data.Models.Wallet", "SwapWallet") + .WithMany("LiquidityRulesAsSwapWallet") + .HasForeignKey("SwapWalletId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Channel"); + + b.Navigation("Node"); + + b.Navigation("ReverseSwapWallet"); + + b.Navigation("SwapWallet"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Node", b => + { + b.HasOne("NodeGuard.Data.Models.Wallet", "AutoChannelOpenWallet") + .WithMany() + .HasForeignKey("AutoChannelOpenWalletId"); + + b.HasOne("NodeGuard.Data.Models.Wallet", "FundsDestinationWallet") + .WithMany() + .HasForeignKey("FundsDestinationWalletId"); + + b.HasOne("NodeGuard.Data.Models.Wallet", null) + .WithMany() + .HasForeignKey("SparkWalletId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("AutoChannelOpenWallet"); + + b.Navigation("FundsDestinationWallet"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Rebalance", b => + { + b.HasOne("NodeGuard.Data.Models.Node", "Node") + .WithMany() + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Channel", "SourceChannel") + .WithMany() + .HasForeignKey("SourceChannelId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "UserRequestor") + .WithMany() + .HasForeignKey("UserRequestorId"); + + b.Navigation("Node"); + + b.Navigation("SourceChannel"); + + b.Navigation("UserRequestor"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ReservedChannelOpenPeer", b => + { + b.HasOne("NodeGuard.Data.Models.Node", "Node") + .WithMany("ReservedChannelOpenPeers") + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Node", "PeerNode") + .WithMany() + .HasForeignKey("PeerNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Node"); + + b.Navigation("PeerNode"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.SwapOut", b => + { + b.HasOne("NodeGuard.Data.Models.Wallet", "DestinationWallet") + .WithMany("SwapOuts") + .HasForeignKey("DestinationWalletId"); + + b.HasOne("NodeGuard.Data.Models.Node", "Node") + .WithMany("SwapOuts") + .HasForeignKey("NodeId"); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "UserRequestor") + .WithMany() + .HasForeignKey("UserRequestorId"); + + b.Navigation("DestinationWallet"); + + b.Navigation("Node"); + + b.Navigation("UserRequestor"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Wallet", b => + { + b.HasOne("NodeGuard.Data.Models.InternalWallet", "InternalWallet") + .WithMany() + .HasForeignKey("InternalWalletId"); + + b.Navigation("InternalWallet"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequest", b => + { + b.HasOne("NodeGuard.Data.Models.WalletWithdrawalRequest", "BumpingWalletWithdrawalRequest") + .WithMany() + .HasForeignKey("BumpingWalletWithdrawalRequestId"); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "UserRequestor") + .WithMany("WalletWithdrawalRequests") + .HasForeignKey("UserRequestorId"); + + b.HasOne("NodeGuard.Data.Models.Wallet", "Wallet") + .WithMany() + .HasForeignKey("WalletId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("BumpingWalletWithdrawalRequest"); + + b.Navigation("UserRequestor"); + + b.Navigation("Wallet"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequestDestination", b => + { + b.HasOne("NodeGuard.Data.Models.WalletWithdrawalRequest", "WalletWithdrawalRequest") + .WithMany("WalletWithdrawalRequestDestinations") + .HasForeignKey("WalletWithdrawalRequestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("WalletWithdrawalRequest"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequestPSBT", b => + { + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "Signer") + .WithMany() + .HasForeignKey("SignerId"); + + b.HasOne("NodeGuard.Data.Models.WalletWithdrawalRequest", "WalletWithdrawalRequest") + .WithMany("WalletWithdrawalRequestPSBTs") + .HasForeignKey("WalletWithdrawalRequestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Signer"); + + b.Navigation("WalletWithdrawalRequest"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Channel", b => + { + b.Navigation("ChannelOperationRequests"); + + b.Navigation("LiquidityRules"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOperationRequest", b => + { + b.Navigation("ChannelOperationRequestPsbts"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Node", b => + { + b.Navigation("ChannelOpenRecommendations"); + + b.Navigation("ChannelOperationRequestsAsDestination"); + + b.Navigation("ChannelOperationRequestsAsSource"); + + b.Navigation("ReservedChannelOpenPeers"); + + b.Navigation("SwapOuts"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Wallet", b => + { + b.Navigation("ChannelOperationRequestsAsSource"); + + b.Navigation("LiquidityRulesAsReverseSwapWallet"); + + b.Navigation("LiquidityRulesAsSwapWallet"); + + b.Navigation("SwapOuts"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequest", b => + { + b.Navigation("WalletWithdrawalRequestDestinations"); + + b.Navigation("WalletWithdrawalRequestPSBTs"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ApplicationUser", b => + { + b.Navigation("ChannelOperationRequests"); + + b.Navigation("Keys"); + + b.Navigation("WalletWithdrawalRequests"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Migrations/20261127161511_AddReservedChannelOpenPeers.cs b/src/Migrations/20261127161511_AddReservedChannelOpenPeers.cs new file mode 100644 index 000000000..8c19aa5b7 --- /dev/null +++ b/src/Migrations/20261127161511_AddReservedChannelOpenPeers.cs @@ -0,0 +1,74 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace NodeGuard.Migrations +{ + /// + public partial class AddReservedChannelOpenPeers : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "IsReservedPeer", + table: "ChannelOpenRecommendations", + type: "boolean", + nullable: false, + defaultValue: false); + + migrationBuilder.CreateTable( + name: "ReservedChannelOpenPeers", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + NodeId = table.Column(type: "integer", nullable: false), + PeerNodeId = table.Column(type: "integer", nullable: false), + BudgetPct = table.Column(type: "integer", nullable: false), + CreationDatetime = table.Column(type: "timestamp with time zone", nullable: false), + UpdateDatetime = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ReservedChannelOpenPeers", x => x.Id); + table.ForeignKey( + name: "FK_ReservedChannelOpenPeers_Nodes_NodeId", + column: x => x.NodeId, + principalTable: "Nodes", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ReservedChannelOpenPeers_Nodes_PeerNodeId", + column: x => x.PeerNodeId, + principalTable: "Nodes", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_ReservedChannelOpenPeers_NodeId_PeerNodeId", + table: "ReservedChannelOpenPeers", + columns: new[] { "NodeId", "PeerNodeId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ReservedChannelOpenPeers_PeerNodeId", + table: "ReservedChannelOpenPeers", + column: "PeerNodeId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ReservedChannelOpenPeers"); + + migrationBuilder.DropColumn( + name: "IsReservedPeer", + table: "ChannelOpenRecommendations"); + } + } +} diff --git a/src/Migrations/20261202085120_AddReservedChannelOpenPeerFees.Designer.cs b/src/Migrations/20261202085120_AddReservedChannelOpenPeerFees.Designer.cs new file mode 100644 index 000000000..afb3640c6 --- /dev/null +++ b/src/Migrations/20261202085120_AddReservedChannelOpenPeerFees.Designer.cs @@ -0,0 +1,2244 @@ +// +using System; +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using NodeGuard.Data; +using NodeGuard.Helpers; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace NodeGuard.Migrations +{ + [DbContext(typeof(ApplicationDbContext))] + [Migration("20261202085120_AddReservedChannelOpenPeerFees")] + partial class AddReservedChannelOpenPeerFees + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.1") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("ApplicationUserNode", b => + { + b.Property("NodesId") + .HasColumnType("integer"); + + b.Property("UsersId") + .HasColumnType("text"); + + b.HasKey("NodesId", "UsersId"); + + b.HasIndex("UsersId"); + + b.ToTable("ApplicationUserNode"); + }); + + modelBuilder.Entity("ChannelOperationRequestFMUTXO", b => + { + b.Property("ChannelOperationRequestsId") + .HasColumnType("integer"); + + b.Property("UtxosId") + .HasColumnType("integer"); + + b.HasKey("ChannelOperationRequestsId", "UtxosId"); + + b.HasIndex("UtxosId"); + + b.ToTable("ChannelOperationRequestFMUTXO"); + }); + + modelBuilder.Entity("FMUTXOWalletWithdrawalRequest", b => + { + b.Property("UTXOsId") + .HasColumnType("integer"); + + b.Property("WalletWithdrawalRequestsId") + .HasColumnType("integer"); + + b.HasKey("UTXOsId", "WalletWithdrawalRequestsId"); + + b.HasIndex("WalletWithdrawalRequestsId"); + + b.ToTable("FMUTXOWalletWithdrawalRequest"); + }); + + modelBuilder.Entity("KeyWallet", b => + { + b.Property("KeysId") + .HasColumnType("integer"); + + b.Property("WalletsId") + .HasColumnType("integer"); + + b.HasKey("KeysId", "WalletsId"); + + b.HasIndex("WalletsId"); + + b.ToTable("KeyWallet"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Discriminator") + .IsRequired() + .HasMaxLength(21) + .HasColumnType("character varying(21)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + + b.HasDiscriminator().HasValue("IdentityUser"); + + b.UseTphMappingStrategy(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProviderKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Name") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.APIToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatorId") + .IsRequired() + .HasColumnType("text"); + + b.Property("ExpirationDate") + .HasColumnType("timestamp without time zone"); + + b.Property("IsBlocked") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CreatorId"); + + b.ToTable("ApiTokens"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ActionType") + .HasColumnType("integer"); + + b.Property("Details") + .HasColumnType("text"); + + b.Property("EventType") + .HasColumnType("integer"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("character varying(45)"); + + b.Property("ObjectAffected") + .HasColumnType("integer"); + + b.Property("ObjectId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.Property("Username") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.ToTable("AuditLogs"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Channel", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BtcCloseAddress") + .HasColumnType("text"); + + b.Property("ChanId") + .HasColumnType("numeric(20,0)"); + + b.Property("ClosedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByNodeGuard") + .HasColumnType("boolean"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("DestinationNodeId") + .HasColumnType("integer"); + + b.Property("FundingTx") + .IsRequired() + .HasColumnType("text"); + + b.Property("FundingTxOutputIndex") + .HasColumnType("bigint"); + + b.Property("IsAutoRebalanceEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsAutomatedLiquidityEnabled") + .HasColumnType("boolean"); + + b.Property("IsDynamicFeeEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("IsPrivate") + .HasColumnType("boolean"); + + b.Property("SatsAmount") + .HasColumnType("bigint"); + + b.Property("SourceNodeId") + .HasColumnType("integer"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("DestinationNodeId"); + + b.HasIndex("SourceNodeId"); + + b.ToTable("Channels"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelFeeState", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ChannelId") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("LastAppliedInboundBaseMsat") + .HasColumnType("integer"); + + b.Property("LastAppliedInboundPpm") + .HasColumnType("integer"); + + b.Property("LastAppliedOutboundBaseFeeMsat") + .HasColumnType("bigint"); + + b.Property("LastAppliedOutboundPpm") + .HasColumnType("bigint"); + + b.Property("LastComputedTarget") + .HasColumnType("double precision"); + + b.Property("LastFeeUpdateAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastObservedRatio") + .HasColumnType("double precision"); + + b.Property("ManagedNodePubKey") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ChannelId", "ManagedNodePubKey") + .IsUnique(); + + b.ToTable("ChannelFeeStates"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOpenRecommendation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ChannelOperationRequestId") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("DismissReason") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("EarnedFeeSats") + .HasColumnType("bigint"); + + b.Property("InheritedBaseFeeMsat") + .HasColumnType("bigint"); + + b.Property("InheritedFeeRatePpm") + .HasColumnType("bigint"); + + b.Property("IsReservedPeer") + .HasColumnType("boolean"); + + b.Property("LastEvidenceAt") + .HasColumnType("timestamp with time zone"); + + b.Property("NodeId") + .HasColumnType("integer"); + + b.Property("PeerCapacitySats") + .HasColumnType("bigint"); + + b.Property("PeerPubKey") + .IsRequired() + .HasMaxLength(66) + .HasColumnType("character varying(66)"); + + b.Property("Refusals") + .HasColumnType("integer"); + + b.Property("SettledOutSats") + .HasColumnType("bigint"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("SuggestedCapacitySats") + .HasColumnType("bigint"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UsableLocalSats") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("ChannelOperationRequestId"); + + b.HasIndex("NodeId", "PeerPubKey") + .IsUnique(); + + b.ToTable("ChannelOpenRecommendations"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOperationRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AmountCryptoUnit") + .HasColumnType("integer"); + + b.Property("Changeless") + .HasColumnType("boolean"); + + b.Property("ChannelId") + .HasColumnType("integer"); + + b.Property("ClosingReason") + .HasColumnType("text"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DestNodeId") + .HasColumnType("integer"); + + b.Property("FeeRate") + .HasColumnType("numeric"); + + b.Property("InitialChannelBaseFeeMsat") + .HasColumnType("bigint"); + + b.Property("InitialChannelFeeRatePpm") + .HasColumnType("bigint"); + + b.Property("IsChannelPrivate") + .HasColumnType("boolean"); + + b.Property("MempoolRecommendedFeesType") + .HasColumnType("integer"); + + b.Property("RequestType") + .HasColumnType("integer"); + + b.Property("SatsAmount") + .HasColumnType("bigint"); + + b.Property("SourceNodeId") + .HasColumnType("integer"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property>("StatusLogs") + .HasColumnType("jsonb"); + + b.Property("TxId") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("text"); + + b.Property("WalletId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ChannelId"); + + b.HasIndex("DestNodeId"); + + b.HasIndex("SourceNodeId"); + + b.HasIndex("UserId"); + + b.HasIndex("WalletId"); + + b.ToTable("ChannelOperationRequests"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOperationRequestPSBT", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ChannelOperationRequestId") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("IsFinalisedPSBT") + .HasColumnType("boolean"); + + b.Property("IsInternalWalletPSBT") + .HasColumnType("boolean"); + + b.Property("IsTemplatePSBT") + .HasColumnType("boolean"); + + b.Property("PSBT") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserSignerId") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ChannelOperationRequestId"); + + b.HasIndex("UserSignerId"); + + b.HasIndex(new[] { "ChannelOperationRequestId" }, "IX_ChannelOperationRequestPSBTs_Template") + .IsUnique() + .HasFilter("\"IsTemplatePSBT\""); + + b.ToTable("ChannelOperationRequestPSBTs"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelRoutingState", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AgeBlocks") + .HasColumnType("bigint"); + + b.Property("ChanIdLnd") + .HasColumnType("numeric(20,0)"); + + b.Property("ChannelId") + .HasColumnType("integer"); + + b.Property("ConsecutiveCategoryCyclesInNewState") + .HasColumnType("bigint"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("EmaLocalRatio") + .HasColumnType("double precision"); + + b.Property("FundingBlockHeight") + .HasColumnType("bigint"); + + b.Property("LastCategorizedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastEvaluatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastKnownLifetime") + .HasColumnType("bigint"); + + b.Property("LastKnownNumUpdates") + .HasColumnType("bigint"); + + b.Property("LastKnownUptime") + .HasColumnType("bigint"); + + b.Property("ManagedNodePubKey") + .IsRequired() + .HasColumnType("text"); + + b.Property("NetFlowRatio") + .HasColumnType("double precision"); + + b.Property("PeerFlowCategory") + .HasColumnType("integer"); + + b.Property("PeerInitiated") + .HasColumnType("boolean"); + + b.Property("PendingCategory") + .HasColumnType("integer"); + + b.Property("PullMsatWindow") + .HasColumnType("bigint"); + + b.Property("PushMsatWindow") + .HasColumnType("bigint"); + + b.Property("TargetLocalRatio") + .HasColumnType("double precision"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ChannelId", "ManagedNodePubKey") + .IsUnique(); + + b.ToTable("ChannelRoutingStates"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.FMUTXO", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("OutputIndex") + .HasColumnType("bigint"); + + b.Property("SatsAmount") + .HasColumnType("bigint"); + + b.Property("TxId") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.ToTable("FMUTXOs"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ForwardingHtlcEvent", b => + { + b.Property("ManagedNodePubKey") + .HasColumnType("text"); + + b.Property("IncomingChannelId") + .HasColumnType("numeric(20,0)"); + + b.Property("OutgoingChannelId") + .HasColumnType("numeric(20,0)"); + + b.Property("IncomingHtlcId") + .HasColumnType("numeric(20,0)"); + + b.Property("OutgoingHtlcId") + .HasColumnType("numeric(20,0)"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("EventCase") + .HasColumnType("integer"); + + b.Property("EventTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("EventType") + .HasColumnType("integer"); + + b.Property("FailureDetail") + .HasColumnType("integer"); + + b.Property("FailureString") + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("FeeMsat") + .HasColumnType("bigint"); + + b.Property("GrossFeeMsat") + .HasColumnType("bigint"); + + b.Property("InboundFeeMsat") + .HasColumnType("bigint"); + + b.Property("InboundFeePpm") + .HasColumnType("bigint"); + + b.Property("IncomingAmountMsat") + .HasColumnType("numeric(20,0)"); + + b.Property("IncomingPeerAlias") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("IncomingTimelock") + .HasColumnType("bigint"); + + b.Property("ManagedNodeName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Outcome") + .HasColumnType("integer"); + + b.Property("OutgoingAmountMsat") + .HasColumnType("numeric(20,0)"); + + b.Property("OutgoingPeerAlias") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("OutgoingTimelock") + .HasColumnType("bigint"); + + b.Property("RoutingFeePpm") + .HasColumnType("bigint"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("WireFailureCode") + .HasColumnType("integer"); + + b.HasKey("ManagedNodePubKey", "IncomingChannelId", "OutgoingChannelId", "IncomingHtlcId", "OutgoingHtlcId"); + + b.HasIndex("CreationDatetime"); + + b.HasIndex("EventTimestamp"); + + b.ToTable("ForwardingHtlcEvents"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.InternalWallet", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("DerivationPath") + .IsRequired() + .HasColumnType("text"); + + b.Property("MasterFingerprint") + .HasColumnType("text"); + + b.Property("MnemonicString") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("XPUB") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("InternalWallets"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Key", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("InternalWalletId") + .HasColumnType("integer"); + + b.Property("IsArchived") + .HasColumnType("boolean"); + + b.Property("IsBIP39ImportedKey") + .HasColumnType("boolean"); + + b.Property("IsCompromised") + .HasColumnType("boolean"); + + b.Property("MasterFingerprint") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("Path") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("text"); + + b.Property("XPUB") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("InternalWalletId"); + + b.HasIndex("UserId"); + + b.ToTable("Keys"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.LiquidityRule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ChannelId") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("IsReverseSwapWalletRule") + .HasColumnType("boolean"); + + b.Property("MinimumLocalBalance") + .HasColumnType("numeric"); + + b.Property("MinimumRemoteBalance") + .HasColumnType("numeric"); + + b.Property("NodeId") + .HasColumnType("integer"); + + b.Property("RebalanceTarget") + .HasColumnType("numeric"); + + b.Property("ReverseSwapAddress") + .HasColumnType("text"); + + b.Property("ReverseSwapWalletId") + .HasColumnType("integer"); + + b.Property("SwapWalletId") + .HasColumnType("integer"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ChannelId") + .IsUnique(); + + b.HasIndex("NodeId"); + + b.HasIndex("ReverseSwapWalletId"); + + b.HasIndex("SwapWalletId"); + + b.ToTable("LiquidityRules"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Node", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AllowPositiveInboundFees") + .HasColumnType("boolean"); + + b.Property("AutoChannelOpenBudgetRefreshInterval") + .HasColumnType("interval"); + + b.Property("AutoChannelOpenBudgetSats") + .HasColumnType("bigint"); + + b.Property("AutoChannelOpenBudgetStartDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("AutoChannelOpenEnabled") + .HasColumnType("boolean"); + + b.Property("AutoChannelOpenMode") + .HasColumnType("integer"); + + b.Property("AutoChannelOpenSizeSats") + .HasColumnType("bigint"); + + b.Property("AutoChannelOpenWalletId") + .HasColumnType("integer"); + + b.Property("AutoLiquidityManagementEnabled") + .HasColumnType("boolean"); + + b.Property("AutoRebalanceEnabled") + .HasColumnType("boolean"); + + b.Property("AutosweepEnabled") + .HasColumnType("boolean"); + + b.Property("ChannelAdminMacaroon") + .HasColumnType("text"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DynamicFeeManagementEnabled") + .HasColumnType("boolean"); + + b.Property("Endpoint") + .HasColumnType("text"); + + b.Property("FortySwapEndpoint") + .HasColumnType("text"); + + b.Property("FortySwapMaxAmountSats") + .HasColumnType("bigint"); + + b.Property("FortySwapMaxSwapRoutingFeeRatio") + .HasColumnType("numeric"); + + b.Property("FortySwapMaxSwapsInFlight") + .HasColumnType("integer"); + + b.Property("FortySwapMinAmountSats") + .HasColumnType("bigint"); + + b.Property("FortySwapWeight") + .HasColumnType("integer"); + + b.Property("FundsDestinationWalletId") + .HasColumnType("integer"); + + b.Property("IsNodeDisabled") + .HasColumnType("boolean"); + + b.Property("LoopMaxSwapRoutingFeeRatio") + .HasColumnType("numeric"); + + b.Property("LoopMaxSwapsInFlight") + .HasColumnType("integer"); + + b.Property("LoopSwapMaxAmountSats") + .HasColumnType("bigint"); + + b.Property("LoopSwapMinAmountSats") + .HasColumnType("bigint"); + + b.Property("LoopSwapWeight") + .HasColumnType("integer"); + + b.Property("LoopdCert") + .HasColumnType("text"); + + b.Property("LoopdEndpoint") + .HasColumnType("text"); + + b.Property("LoopdMacaroon") + .HasColumnType("text"); + + b.Property("MaxRebalanceCostToEarnRatio") + .HasColumnType("double precision"); + + b.Property("MaxRebalancesInFlight") + .HasColumnType("integer"); + + b.Property("MinimumBalanceThresholdSats") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("PubKey") + .IsRequired() + .HasColumnType("text"); + + b.Property("RebalanceBudgetRefreshInterval") + .HasColumnType("interval"); + + b.Property("RebalanceBudgetSats") + .HasColumnType("bigint"); + + b.Property("RebalanceBudgetStartDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("RoutingEngineDryRun") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("SparkMaxSwapRoutingFeeRatio") + .HasColumnType("numeric"); + + b.Property("SparkMaxSwapsInFlight") + .HasColumnType("integer"); + + b.Property("SparkPaymentTimeoutMinutes") + .HasColumnType("integer"); + + b.Property("SparkSwapMaxAmountSats") + .HasColumnType("bigint"); + + b.Property("SparkSwapMinAmountSats") + .HasColumnType("bigint"); + + b.Property("SparkSwapWeight") + .HasColumnType("integer"); + + b.Property("SparkWalletId") + .HasColumnType("integer"); + + b.Property("SwapBudgetRefreshInterval") + .HasColumnType("interval"); + + b.Property("SwapBudgetSats") + .HasColumnType("bigint"); + + b.Property("SwapBudgetStartDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AutoChannelOpenWalletId"); + + b.HasIndex("FundsDestinationWalletId"); + + b.HasIndex("PubKey") + .IsUnique(); + + b.HasIndex("SparkWalletId"); + + b.ToTable("Nodes"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Rebalance", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AmountBackoffRatio") + .HasColumnType("double precision"); + + b.Property("AttemptNumber") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("FeePaidMsat") + .HasColumnType("bigint"); + + b.Property("FeePaidSats") + .HasColumnType("bigint"); + + b.Property("IsManual") + .HasColumnType("boolean"); + + b.Property("MaxAttempts") + .HasColumnType("integer"); + + b.Property("MaxFeePct") + .HasColumnType("double precision"); + + b.Property("NodeId") + .HasColumnType("integer"); + + b.Property("PaymentHashHex") + .HasColumnType("text"); + + b.Property("PaymentRequest") + .HasColumnType("text"); + + b.Property("PreimageHex") + .HasColumnType("text"); + + b.Property("RequestedAmountSats") + .HasColumnType("bigint"); + + b.Property("RetryMaxFeePct") + .HasColumnType("double precision"); + + b.Property("SatsAmount") + .HasColumnType("bigint"); + + b.Property("SourceChanIdLnd") + .HasColumnType("numeric(20,0)"); + + b.Property("SourceChannelId") + .HasColumnType("integer"); + + b.Property("SourceNodePubKey") + .HasColumnType("text"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TargetPubkey") + .HasColumnType("text"); + + b.Property("TimeoutSeconds") + .HasColumnType("integer"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserRequestorId") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("NodeId"); + + b.HasIndex("SourceChannelId"); + + b.HasIndex("UserRequestorId"); + + b.ToTable("Rebalances"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ReservedChannelOpenPeer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BaseFeeMsat") + .HasColumnType("bigint"); + + b.Property("BudgetPct") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("FeeRatePpm") + .HasColumnType("bigint"); + + b.Property("NodeId") + .HasColumnType("integer"); + + b.Property("PeerNodeId") + .HasColumnType("integer"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("PeerNodeId"); + + b.HasIndex("NodeId", "PeerNodeId") + .IsUnique(); + + b.ToTable("ReservedChannelOpenPeers"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.SparkSignerIdentity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Account") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("IdentityPublicKey") + .IsRequired() + .HasColumnType("text"); + + b.Property("SeedFingerprint") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("SeedFingerprint", "Account") + .IsUnique(); + + b.ToTable("SparkSignerIdentities"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.SwapOut", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("DestinationAddress") + .HasColumnType("text"); + + b.Property("DestinationWalletId") + .HasColumnType("integer"); + + b.Property("ErrorDetails") + .HasColumnType("text"); + + b.Property("IsManual") + .HasColumnType("boolean"); + + b.Property("LightningFeeSats") + .HasColumnType("bigint"); + + b.Property("NodeId") + .HasColumnType("integer"); + + b.Property("OnChainFeeSats") + .HasColumnType("bigint"); + + b.Property("PaymentHash") + .HasColumnType("text"); + + b.Property("PayoutSats") + .HasColumnType("bigint"); + + b.Property("Provider") + .HasColumnType("integer"); + + b.Property("ProviderId") + .HasColumnType("text"); + + b.Property("ReferenceId") + .HasColumnType("text"); + + b.Property("SatsAmount") + .HasColumnType("bigint"); + + b.Property("ServiceFeeSats") + .HasColumnType("bigint"); + + b.Property("SparkExitDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("SparkIdentity") + .HasColumnType("text"); + + b.Property("SparkLeafIds") + .HasColumnType("text"); + + b.Property("SparkReceivedSats") + .HasColumnType("bigint"); + + b.Property("SparkTransferId") + .HasColumnType("text"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TxId") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserRequestorId") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("DestinationWalletId"); + + b.HasIndex("NodeId"); + + b.HasIndex("ReferenceId") + .IsUnique() + .HasFilter("\"ReferenceId\" IS NOT NULL"); + + b.HasIndex("UserRequestorId"); + + b.ToTable("SwapOuts"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.UTXOTag", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Key") + .IsRequired() + .HasColumnType("text"); + + b.Property("Outpoint") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Key", "Outpoint") + .IsUnique(); + + b.ToTable("UTXOTags"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Wallet", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BIP39Seedphrase") + .HasColumnType("text"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("ImportedOutputDescriptor") + .HasColumnType("text"); + + b.Property("InternalWalletId") + .HasColumnType("integer"); + + b.Property("InternalWalletMasterFingerprint") + .HasColumnType("text"); + + b.Property("InternalWalletSubDerivationPath") + .HasColumnType("text"); + + b.Property("IsArchived") + .HasColumnType("boolean"); + + b.Property("IsBIP39Imported") + .HasColumnType("boolean"); + + b.Property("IsCompromised") + .HasColumnType("boolean"); + + b.Property("IsFinalised") + .HasColumnType("boolean"); + + b.Property("IsHotWallet") + .HasColumnType("boolean"); + + b.Property("IsUnSortedMultiSig") + .HasColumnType("boolean"); + + b.Property("Kind") + .HasColumnType("integer"); + + b.Property("MofN") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ReferenceId") + .HasColumnType("text"); + + b.Property("SparkAccount") + .HasColumnType("integer"); + + b.Property("SparkEncryptedMnemonic") + .HasColumnType("text"); + + b.Property("SparkIdentityPublicKey") + .HasColumnType("text"); + + b.Property("SparkMaxBalanceSats") + .HasColumnType("bigint"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("WalletAddressType") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("InternalWalletId"); + + b.HasIndex("InternalWalletSubDerivationPath", "InternalWalletMasterFingerprint") + .IsUnique(); + + b.ToTable("Wallets"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BumpingWalletWithdrawalRequestId") + .HasColumnType("integer"); + + b.Property("Changeless") + .HasColumnType("boolean"); + + b.Property("CoinSelectionStrategy") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("CustomFeeRate") + .HasColumnType("numeric"); + + b.Property("Description") + .IsRequired() + .HasColumnType("text"); + + b.Property("IsRbfCancellation") + .HasColumnType("boolean"); + + b.Property("MempoolRecommendedFeesType") + .HasColumnType("integer"); + + b.Property("ReferenceId") + .HasColumnType("text"); + + b.Property("RejectCancelDescription") + .HasColumnType("text"); + + b.Property("RequestMetadata") + .HasColumnType("text"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("TxId") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UserRequestorId") + .HasColumnType("text"); + + b.Property("WalletId") + .HasColumnType("integer"); + + b.Property("WithdrawAllFunds") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("BumpingWalletWithdrawalRequestId"); + + b.HasIndex("UserRequestorId"); + + b.HasIndex("WalletId"); + + b.ToTable("WalletWithdrawalRequests"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequestDestination", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasColumnType("text"); + + b.Property("Amount") + .HasColumnType("numeric"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("WalletWithdrawalRequestId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("WalletWithdrawalRequestId"); + + b.ToTable("WalletWithdrawalRequestDestinations"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequestPSBT", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("IsFinalisedPSBT") + .HasColumnType("boolean"); + + b.Property("IsInternalWalletPSBT") + .HasColumnType("boolean"); + + b.Property("IsTemplatePSBT") + .HasColumnType("boolean"); + + b.Property("PSBT") + .IsRequired() + .HasColumnType("text"); + + b.Property("SignerId") + .HasColumnType("text"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("WalletWithdrawalRequestId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("SignerId"); + + b.HasIndex("WalletWithdrawalRequestId"); + + b.HasIndex(new[] { "WalletWithdrawalRequestId" }, "IX_WalletWithdrawalRequestPSBTs_Template") + .IsUnique() + .HasFilter("\"IsTemplatePSBT\""); + + b.ToTable("WalletWithdrawalRequestPSBTs"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ApplicationUser", b => + { + b.HasBaseType("Microsoft.AspNetCore.Identity.IdentityUser"); + + b.HasDiscriminator().HasValue("ApplicationUser"); + }); + + modelBuilder.Entity("ApplicationUserNode", b => + { + b.HasOne("NodeGuard.Data.Models.Node", null) + .WithMany() + .HasForeignKey("NodesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", null) + .WithMany() + .HasForeignKey("UsersId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ChannelOperationRequestFMUTXO", b => + { + b.HasOne("NodeGuard.Data.Models.ChannelOperationRequest", null) + .WithMany() + .HasForeignKey("ChannelOperationRequestsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.FMUTXO", null) + .WithMany() + .HasForeignKey("UtxosId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("FMUTXOWalletWithdrawalRequest", b => + { + b.HasOne("NodeGuard.Data.Models.FMUTXO", null) + .WithMany() + .HasForeignKey("UTXOsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.WalletWithdrawalRequest", null) + .WithMany() + .HasForeignKey("WalletWithdrawalRequestsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("KeyWallet", b => + { + b.HasOne("NodeGuard.Data.Models.Key", null) + .WithMany() + .HasForeignKey("KeysId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Wallet", null) + .WithMany() + .HasForeignKey("WalletsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.APIToken", b => + { + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "Creator") + .WithMany() + .HasForeignKey("CreatorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Creator"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Channel", b => + { + b.HasOne("NodeGuard.Data.Models.Node", "DestinationNode") + .WithMany() + .HasForeignKey("DestinationNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Node", "SourceNode") + .WithMany() + .HasForeignKey("SourceNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DestinationNode"); + + b.Navigation("SourceNode"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelFeeState", b => + { + b.HasOne("NodeGuard.Data.Models.Channel", "Channel") + .WithMany() + .HasForeignKey("ChannelId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Channel"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOpenRecommendation", b => + { + b.HasOne("NodeGuard.Data.Models.ChannelOperationRequest", "ChannelOperationRequest") + .WithMany() + .HasForeignKey("ChannelOperationRequestId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("NodeGuard.Data.Models.Node", "Node") + .WithMany("ChannelOpenRecommendations") + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ChannelOperationRequest"); + + b.Navigation("Node"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOperationRequest", b => + { + b.HasOne("NodeGuard.Data.Models.Channel", "Channel") + .WithMany("ChannelOperationRequests") + .HasForeignKey("ChannelId"); + + b.HasOne("NodeGuard.Data.Models.Node", "DestNode") + .WithMany("ChannelOperationRequestsAsDestination") + .HasForeignKey("DestNodeId"); + + b.HasOne("NodeGuard.Data.Models.Node", "SourceNode") + .WithMany("ChannelOperationRequestsAsSource") + .HasForeignKey("SourceNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "User") + .WithMany("ChannelOperationRequests") + .HasForeignKey("UserId"); + + b.HasOne("NodeGuard.Data.Models.Wallet", "Wallet") + .WithMany("ChannelOperationRequestsAsSource") + .HasForeignKey("WalletId"); + + b.Navigation("Channel"); + + b.Navigation("DestNode"); + + b.Navigation("SourceNode"); + + b.Navigation("User"); + + b.Navigation("Wallet"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOperationRequestPSBT", b => + { + b.HasOne("NodeGuard.Data.Models.ChannelOperationRequest", "ChannelOperationRequest") + .WithMany("ChannelOperationRequestPsbts") + .HasForeignKey("ChannelOperationRequestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "UserSigner") + .WithMany() + .HasForeignKey("UserSignerId"); + + b.Navigation("ChannelOperationRequest"); + + b.Navigation("UserSigner"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelRoutingState", b => + { + b.HasOne("NodeGuard.Data.Models.Channel", "Channel") + .WithMany() + .HasForeignKey("ChannelId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Channel"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Key", b => + { + b.HasOne("NodeGuard.Data.Models.InternalWallet", "InternalWallet") + .WithMany() + .HasForeignKey("InternalWalletId"); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "User") + .WithMany("Keys") + .HasForeignKey("UserId"); + + b.Navigation("InternalWallet"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.LiquidityRule", b => + { + b.HasOne("NodeGuard.Data.Models.Channel", "Channel") + .WithMany("LiquidityRules") + .HasForeignKey("ChannelId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Node", "Node") + .WithMany() + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Wallet", "ReverseSwapWallet") + .WithMany("LiquidityRulesAsReverseSwapWallet") + .HasForeignKey("ReverseSwapWalletId"); + + b.HasOne("NodeGuard.Data.Models.Wallet", "SwapWallet") + .WithMany("LiquidityRulesAsSwapWallet") + .HasForeignKey("SwapWalletId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Channel"); + + b.Navigation("Node"); + + b.Navigation("ReverseSwapWallet"); + + b.Navigation("SwapWallet"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Node", b => + { + b.HasOne("NodeGuard.Data.Models.Wallet", "AutoChannelOpenWallet") + .WithMany() + .HasForeignKey("AutoChannelOpenWalletId"); + + b.HasOne("NodeGuard.Data.Models.Wallet", "FundsDestinationWallet") + .WithMany() + .HasForeignKey("FundsDestinationWalletId"); + + b.HasOne("NodeGuard.Data.Models.Wallet", null) + .WithMany() + .HasForeignKey("SparkWalletId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("AutoChannelOpenWallet"); + + b.Navigation("FundsDestinationWallet"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Rebalance", b => + { + b.HasOne("NodeGuard.Data.Models.Node", "Node") + .WithMany() + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Channel", "SourceChannel") + .WithMany() + .HasForeignKey("SourceChannelId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "UserRequestor") + .WithMany() + .HasForeignKey("UserRequestorId"); + + b.Navigation("Node"); + + b.Navigation("SourceChannel"); + + b.Navigation("UserRequestor"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ReservedChannelOpenPeer", b => + { + b.HasOne("NodeGuard.Data.Models.Node", "Node") + .WithMany("ReservedChannelOpenPeers") + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Node", "PeerNode") + .WithMany() + .HasForeignKey("PeerNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Node"); + + b.Navigation("PeerNode"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.SwapOut", b => + { + b.HasOne("NodeGuard.Data.Models.Wallet", "DestinationWallet") + .WithMany("SwapOuts") + .HasForeignKey("DestinationWalletId"); + + b.HasOne("NodeGuard.Data.Models.Node", "Node") + .WithMany("SwapOuts") + .HasForeignKey("NodeId"); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "UserRequestor") + .WithMany() + .HasForeignKey("UserRequestorId"); + + b.Navigation("DestinationWallet"); + + b.Navigation("Node"); + + b.Navigation("UserRequestor"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Wallet", b => + { + b.HasOne("NodeGuard.Data.Models.InternalWallet", "InternalWallet") + .WithMany() + .HasForeignKey("InternalWalletId"); + + b.Navigation("InternalWallet"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequest", b => + { + b.HasOne("NodeGuard.Data.Models.WalletWithdrawalRequest", "BumpingWalletWithdrawalRequest") + .WithMany() + .HasForeignKey("BumpingWalletWithdrawalRequestId"); + + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "UserRequestor") + .WithMany("WalletWithdrawalRequests") + .HasForeignKey("UserRequestorId"); + + b.HasOne("NodeGuard.Data.Models.Wallet", "Wallet") + .WithMany() + .HasForeignKey("WalletId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("BumpingWalletWithdrawalRequest"); + + b.Navigation("UserRequestor"); + + b.Navigation("Wallet"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequestDestination", b => + { + b.HasOne("NodeGuard.Data.Models.WalletWithdrawalRequest", "WalletWithdrawalRequest") + .WithMany("WalletWithdrawalRequestDestinations") + .HasForeignKey("WalletWithdrawalRequestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("WalletWithdrawalRequest"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequestPSBT", b => + { + b.HasOne("NodeGuard.Data.Models.ApplicationUser", "Signer") + .WithMany() + .HasForeignKey("SignerId"); + + b.HasOne("NodeGuard.Data.Models.WalletWithdrawalRequest", "WalletWithdrawalRequest") + .WithMany("WalletWithdrawalRequestPSBTs") + .HasForeignKey("WalletWithdrawalRequestId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Signer"); + + b.Navigation("WalletWithdrawalRequest"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Channel", b => + { + b.Navigation("ChannelOperationRequests"); + + b.Navigation("LiquidityRules"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ChannelOperationRequest", b => + { + b.Navigation("ChannelOperationRequestPsbts"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Node", b => + { + b.Navigation("ChannelOpenRecommendations"); + + b.Navigation("ChannelOperationRequestsAsDestination"); + + b.Navigation("ChannelOperationRequestsAsSource"); + + b.Navigation("ReservedChannelOpenPeers"); + + b.Navigation("SwapOuts"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.Wallet", b => + { + b.Navigation("ChannelOperationRequestsAsSource"); + + b.Navigation("LiquidityRulesAsReverseSwapWallet"); + + b.Navigation("LiquidityRulesAsSwapWallet"); + + b.Navigation("SwapOuts"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.WalletWithdrawalRequest", b => + { + b.Navigation("WalletWithdrawalRequestDestinations"); + + b.Navigation("WalletWithdrawalRequestPSBTs"); + }); + + modelBuilder.Entity("NodeGuard.Data.Models.ApplicationUser", b => + { + b.Navigation("ChannelOperationRequests"); + + b.Navigation("Keys"); + + b.Navigation("WalletWithdrawalRequests"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Migrations/20261202085120_AddReservedChannelOpenPeerFees.cs b/src/Migrations/20261202085120_AddReservedChannelOpenPeerFees.cs new file mode 100644 index 000000000..fc38e0c67 --- /dev/null +++ b/src/Migrations/20261202085120_AddReservedChannelOpenPeerFees.cs @@ -0,0 +1,40 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace NodeGuard.Migrations +{ + /// + public partial class AddReservedChannelOpenPeerFees : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "BaseFeeMsat", + table: "ReservedChannelOpenPeers", + type: "bigint", + nullable: false, + defaultValue: 0L); + + migrationBuilder.AddColumn( + name: "FeeRatePpm", + table: "ReservedChannelOpenPeers", + type: "bigint", + nullable: false, + defaultValue: 0L); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "BaseFeeMsat", + table: "ReservedChannelOpenPeers"); + + migrationBuilder.DropColumn( + name: "FeeRatePpm", + table: "ReservedChannelOpenPeers"); + } + } +} diff --git a/src/Migrations/ApplicationDbContextModelSnapshot.cs b/src/Migrations/ApplicationDbContextModelSnapshot.cs index 705db302b..1de7ab86c 100644 --- a/src/Migrations/ApplicationDbContextModelSnapshot.cs +++ b/src/Migrations/ApplicationDbContextModelSnapshot.cs @@ -523,6 +523,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("InheritedFeeRatePpm") .HasColumnType("bigint"); + b.Property("IsReservedPeer") + .HasColumnType("boolean"); + b.Property("LastEvidenceAt") .HasColumnType("timestamp with time zone"); @@ -1312,6 +1315,45 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("Rebalances"); }); + modelBuilder.Entity("NodeGuard.Data.Models.ReservedChannelOpenPeer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BaseFeeMsat") + .HasColumnType("bigint"); + + b.Property("BudgetPct") + .HasColumnType("integer"); + + b.Property("CreationDatetime") + .HasColumnType("timestamp with time zone"); + + b.Property("FeeRatePpm") + .HasColumnType("bigint"); + + b.Property("NodeId") + .HasColumnType("integer"); + + b.Property("PeerNodeId") + .HasColumnType("integer"); + + b.Property("UpdateDatetime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("PeerNodeId"); + + b.HasIndex("NodeId", "PeerNodeId") + .IsUnique(); + + b.ToTable("ReservedChannelOpenPeers"); + }); + modelBuilder.Entity("NodeGuard.Data.Models.SparkSignerIdentity", b => { b.Property("Id") @@ -2042,6 +2084,25 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("UserRequestor"); }); + modelBuilder.Entity("NodeGuard.Data.Models.ReservedChannelOpenPeer", b => + { + b.HasOne("NodeGuard.Data.Models.Node", "Node") + .WithMany("ReservedChannelOpenPeers") + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("NodeGuard.Data.Models.Node", "PeerNode") + .WithMany() + .HasForeignKey("PeerNodeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Node"); + + b.Navigation("PeerNode"); + }); + modelBuilder.Entity("NodeGuard.Data.Models.SwapOut", b => { b.HasOne("NodeGuard.Data.Models.Wallet", "DestinationWallet") @@ -2143,6 +2204,8 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("ChannelOperationRequestsAsSource"); + b.Navigation("ReservedChannelOpenPeers"); + b.Navigation("SwapOuts"); }); diff --git a/src/Pages/Nodes.razor b/src/Pages/Nodes.razor index 2c24983fd..15a3f07db 100644 --- a/src/Pages/Nodes.razor +++ b/src/Pages/Nodes.razor @@ -898,6 +898,91 @@ + + + Reserved Peers + + Registered nodes with their own share of the budget, such as a swap service. They skip the earning evidence: a reserved peer gets a channel + whenever its usable outbound is below @Constants.AUTO_CHANNEL_OPEN_LOW_OUTBOUND_PCT%, or we have no channel with it yet. + Other peers can't spend a reserved share. A reserved peer spends its own share first, then the rest of the budget. + The fee rate and base fee are what its channel opens at when we have no channel with it to copy a fee from. + + @foreach (var peer in _reservedPeers) + { + + + + + + + + + + + % + + + + + + + + + + ppm + + + + + + + + + + msat + + + + + + + + } + + @if (_reservedPeers.Count > 0) + { + + Reserved: @(_reservedPeers.Sum(x => x.BudgetPct))% of the budget. Left for other peers: @(Math.Max(0, 100 - _reservedPeers.Sum(x => x.BudgetPct)))%. + + } + } @if (_selectedNodeForLiquidity.DynamicFeeManagementEnabled || _selectedNodeForLiquidity.AutoRebalanceEnabled || _selectedNodeForLiquidity.AutoChannelOpenEnabled) @@ -942,6 +1027,7 @@ @inject SparkSettings SparkSettings @inject ISparkWalletService SparkWallet @inject ISwapOutRepository SwapOutRepository +@inject IReservedChannelOpenPeerRepository ReservedChannelOpenPeerRepository @implements IDisposable @code { private List? _nodes; @@ -1010,6 +1096,10 @@ private int _channelOpenBudgetRefreshDays; private long _channelOpenSizeSats; + // Edited in place and saved as a whole with the modal; the rows are never tracked entities. + private List _reservedPeers = new(); + private List _reservablePeers = new(); + public abstract class NodesColumnName { public static readonly ColumnDefault Name = new("Name"); @@ -1393,6 +1483,12 @@ _channelOpenBudgetSats = node.AutoChannelOpenBudgetSats ?? 0; _channelOpenBudgetRefreshDays = node.AutoChannelOpenBudgetRefreshInterval?.Days ?? 0; _channelOpenSizeSats = node.AutoChannelOpenSizeSats ?? 0; + _reservedPeers = (await ReservedChannelOpenPeerRepository.GetByNode(node.Id)) + .Select(x => new ReservedChannelOpenPeer { PeerNodeId = x.PeerNodeId, BudgetPct = x.BudgetPct, FeeRatePpm = x.FeeRatePpm, BaseFeeMsat = x.BaseFeeMsat }) + .ToList(); + _reservablePeers = (await NodeRepository.GetAllForSelection()) + .Where(x => x.Id != node.Id) + .ToList(); if (_nodeLiquidityModal != null) await _nodeLiquidityModal.Show(); } @@ -1422,6 +1518,12 @@ return; } + if (ValidationHelper.ValidateReservedChannelOpenPeers(_reservedPeers, _selectedNodeForLiquidity.Id) is { } reservedPeersError) + { + ToastService.ShowError(reservedPeersError); + return; + } + if (_selectedNodeForLiquidity.SparkPaymentTimeoutMinutes is < 1 || _selectedNodeForLiquidity.SparkPaymentTimeoutMinutes > SparkSettings.MaxPaymentTimeoutMinutes) { ToastService.ShowError($"The Spark payment timeout must be 1 to {SparkSettings.MaxPaymentTimeoutMinutes} minutes, or empty for the default"); @@ -1455,6 +1557,14 @@ _selectedNodeForLiquidity.AutoChannelOpenSizeSats = _channelOpenSizeSats > 0 ? _channelOpenSizeSats : null; _selectedNodeForLiquidity.UpdateDatetime = DateTimeOffset.Now; + // Saved first: if it fails nothing is saved, and the edits stay on screen for another Save. + var (reservedPeersSaved, _) = await ReservedChannelOpenPeerRepository.ReplaceForNode(_selectedNodeForLiquidity.Id, _reservedPeers); + if (!reservedPeersSaved) + { + ToastService.ShowError("Could not save the reserved peers"); + return; + } + var updateResult = NodeRepository.Update(_selectedNodeForLiquidity); if (!updateResult.Item1) @@ -1490,6 +1600,14 @@ } } + private void AddReservedPeer() => _reservedPeers.Add(new ReservedChannelOpenPeer { BudgetPct = 10 }); + + // On the whole pubkey, which the label truncates. + private static bool ReservablePeerFilter(Node node, string search) + => string.IsNullOrWhiteSpace(search) + || (node.Name?.Contains(search.Trim(), StringComparison.OrdinalIgnoreCase) ?? false) + || node.PubKey.Contains(search.Trim(), StringComparison.OrdinalIgnoreCase); + private void OnSelectedAutoChannelOpenWalletChanged(int walletId) { if (_selectedNodeForLiquidity != null) diff --git a/src/Pages/RoutingManagement.razor b/src/Pages/RoutingManagement.razor index a51b28990..89c311a3b 100644 --- a/src/Pages/RoutingManagement.razor +++ b/src/Pages/RoutingManagement.razor @@ -152,7 +152,7 @@

Channel open recommendations

- Peers that earned us fees and are now refusing forwards for lack of our outbound + Peers that earned us fees and are now refusing forwards for lack of our outbound, and reserved peers short of outbound
@@ -213,6 +213,14 @@ Committed this period @(_channelOpenCommittedSats is { } committed ? $"{Sats(committed)} sats" : "—")
+ @* Reserved peers are edited on the Nodes page too. Spend past a share comes out of the rest. *@ + @foreach (var reserved in _reservedPeers) + { +
+ @ReservedPeerName(reserved) (@reserved.BudgetPct% reserved) + @ReservedShareText(reserved) +
+ }
@if (_recommendations.Count == 0) @@ -241,6 +249,10 @@
@RecommendationPeerName(rec) + @if (rec.IsReservedPeer) + { + reserved + } @StringHelper.TruncateTail(rec.PeerPubKey, 14)
@@ -494,6 +506,7 @@ @inject IChannelRoutingStateRepository ChannelRoutingStateRepository @inject IRebalanceRepository RebalanceRepository @inject IChannelOpenRecommendationRepository ChannelOpenRecommendationRepository +@inject IReservedChannelOpenPeerRepository ReservedChannelOpenPeerRepository @inject IChannelOperationRequestRepository ChannelOperationRequestRepository @inject IChannelOpenPromotionService ChannelOpenPromotionService @inject ISwapOutWarningService SwapOutWarningService @@ -545,6 +558,8 @@ private string? _swapOutWarning; private readonly Dictionary _editedCapacities = new(); private long? _channelOpenCommittedSats; + private List _reservedPeers = new(); + private Dictionary _channelOpenCommittedByPeer = new(); protected override async Task OnInitializedAsync() { @@ -824,8 +839,9 @@ // Independent reads, each on its own DbContext from the factory — one round-trip instead of two. var recommendations = ChannelOpenRecommendationRepository.GetOpenByNode(nodeId); - var committed = ChannelOperationRequestRepository.GetOpenSatsCommittedSince(nodeId, periodStart); - await Task.WhenAll(recommendations, committed); + var committedByPeer = ChannelOperationRequestRepository.GetOpenSatsCommittedByPeerSince(nodeId, periodStart); + var reservedPeers = ReservedChannelOpenPeerRepository.GetByNode(nodeId); + await Task.WhenAll(recommendations, committedByPeer, reservedPeers); // A recommended peer may have no channel NodeGuard tracks, so names come from the Nodes table. var peerNames = await NodeRepository.GetNamesByPubKeys(recommendations.Result.Select(r => r.PeerPubKey).ToList()); @@ -835,7 +851,9 @@ _recommendations = recommendations.Result; _recommendationPeerNames = peerNames; - _channelOpenCommittedSats = committed.Result; + _channelOpenCommittedByPeer = committedByPeer.Result; + _channelOpenCommittedSats = committedByPeer.Result.Values.Sum(); + _reservedPeers = reservedPeers.Result; } catch (Exception ex) { @@ -849,6 +867,16 @@ _recommendationPeerNames = new Dictionary(); _editedCapacities.Clear(); _channelOpenCommittedSats = null; + _reservedPeers = new List(); + _channelOpenCommittedByPeer = new Dictionary(); + } + + private string ReservedShareText(ReservedChannelOpenPeer reserved) + { + if (_selectedNode?.AutoChannelOpenBudgetSats is not > 0 || _channelOpenCommittedSats is null) return "—"; + + var shareSats = _selectedNode.AutoChannelOpenBudgetSats.Value * reserved.BudgetPct / 100; + return $"{Sats(_channelOpenCommittedByPeer.GetValueOrDefault(reserved.PeerNode?.PubKey ?? ""))} / {Sats(shareSats)} sats"; } // Falls back to the truncated pubkey, like the peers table. @@ -857,6 +885,11 @@ ? name : StringHelper.TruncateTail(rec.PeerPubKey, 12); + private static string ReservedPeerName(ReservedChannelOpenPeer reserved) + => string.IsNullOrWhiteSpace(reserved.PeerNode?.Name) + ? StringHelper.TruncateTail(reserved.PeerNode?.PubKey ?? "", 12) + : reserved.PeerNode.Name; + // The suggested capacity is a starting point: an operator edits it here before promoting. private long GetEditedCapacity(ChannelOpenRecommendation rec) => _editedCapacities.TryGetValue(rec.Id, out var edited) ? edited : rec.SuggestedCapacitySats; diff --git a/src/Program.cs b/src/Program.cs index fbeec8dae..d09ff6452 100644 --- a/src/Program.cs +++ b/src/Program.cs @@ -131,6 +131,7 @@ public static async Task Main(string[] args) builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); + builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); diff --git a/src/Services/ChannelOpenBudget.cs b/src/Services/ChannelOpenBudget.cs new file mode 100644 index 000000000..9b9011b0b --- /dev/null +++ b/src/Services/ChannelOpenBudget.cs @@ -0,0 +1,85 @@ +/* + * 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.Services; + +/// +/// What is left of a node's channel open budget for the current period, split into one share per +/// reserved peer and a general part for everyone else. A reserved peer spends its own share first and +/// then the general part; any other peer only ever spends the general part. Pure, no I/O. +/// +public class ChannelOpenBudget +{ + private readonly Dictionary _reservedLeftByPeer; + private long _generalLeft; + + private ChannelOpenBudget(Dictionary reservedLeftByPeer, long generalLeft) + { + _reservedLeftByPeer = reservedLeftByPeer; + _generalLeft = generalLeft; + } + + /// The node's budget for the period. + /// Each reserved peer's share of it, in percent. + /// What the period has already committed, per peer. + public static ChannelOpenBudget Build( + long budgetSats, + IReadOnlyDictionary reservedPctByPeer, + IReadOnlyDictionary committedByPeer) + { + var reservedLeftByPeer = new Dictionary(); + var generalSats = budgetSats; + var generalCommitted = 0L; + + foreach (var (peer, pct) in reservedPctByPeer) + { + var shareSats = budgetSats * Math.Clamp(pct, 0, 100) / 100; + var committed = committedByPeer.GetValueOrDefault(peer); + generalSats -= shareSats; + reservedLeftByPeer[peer] = Math.Max(0, shareSats - committed); + // What a reserved peer spent past its own share came out of the general part. + generalCommitted += Math.Max(0, committed - shareSats); + } + + generalCommitted += committedByPeer + .Where(x => !reservedPctByPeer.ContainsKey(x.Key)) + .Sum(x => x.Value); + + return new ChannelOpenBudget(reservedLeftByPeer, Math.Max(0, generalSats) - generalCommitted); + } + + public bool IsReserved(string peerPubKey) => _reservedLeftByPeer.ContainsKey(peerPubKey); + + public long HeadroomFor(string peerPubKey) => + _reservedLeftByPeer.GetValueOrDefault(peerPubKey) + Math.Max(0, _generalLeft); + + /// Whether any peer, reserved or not, could still be given anything. + public bool IsExhausted => _generalLeft <= 0 && _reservedLeftByPeer.Values.All(x => x <= 0); + + public void Spend(string peerPubKey, long sats) + { + var fromReserved = Math.Min(_reservedLeftByPeer.GetValueOrDefault(peerPubKey), sats); + if (fromReserved > 0) + { + _reservedLeftByPeer[peerPubKey] -= fromReserved; + } + + _generalLeft -= sats - fromReserved; + } +} diff --git a/src/Services/ChannelOpenInitiatorService.cs b/src/Services/ChannelOpenInitiatorService.cs index 94860241b..d1a2d34a6 100644 --- a/src/Services/ChannelOpenInitiatorService.cs +++ b/src/Services/ChannelOpenInitiatorService.cs @@ -25,6 +25,7 @@ namespace NodeGuard.Services; /// /// Everything the planner knows about one peer, aggregated over all our open channels to it. LND /// forwards non-strictly and reports whichever channel it tried last, so the peer is the identity. +/// A reserved peer we have no channel with has a zero capacity and the policy set on its reservation. /// public record PeerSnapshot( string PeerPubKey, @@ -34,7 +35,8 @@ public record PeerSnapshot( long UsableLocalSats, long CapacitySats, LocalOutboundPolicy? OutboundPolicy, - bool OnCooldown); + bool OnCooldown, + bool IsReserved = false); public record ChannelOpenInitiatorTunables( long MinEarnedFeeSats, @@ -42,19 +44,19 @@ public record ChannelOpenInitiatorTunables( int LowOutboundPct, long SizeSats, long WalletSpendableSats, - long RemainingBudgetSats, + ChannelOpenBudget Budget, int MaxPlansPerRun) { public static ChannelOpenInitiatorTunables FromConstants( Node node, long walletSpendableSats, - long remainingBudgetSats) => new( + ChannelOpenBudget budget) => new( MinEarnedFeeSats: Constants.AUTO_CHANNEL_OPEN_MIN_EARNED_FEE_SATS, MinRefusals: Constants.AUTO_CHANNEL_OPEN_MIN_REFUSALS, LowOutboundPct: Constants.AUTO_CHANNEL_OPEN_LOW_OUTBOUND_PCT, SizeSats: node.AutoChannelOpenSizeSats ?? 0, WalletSpendableSats: walletSpendableSats, - RemainingBudgetSats: remainingBudgetSats, + Budget: budget, MaxPlansPerRun: Constants.AUTO_CHANNEL_OPEN_MAX_PLANS_PER_RUN); } @@ -67,6 +69,7 @@ public record ChannelOpenClassification( /// /// Channel-open planner. Pure, no I/O. A peer gets a fixed-size channel when the route to it has /// earned us fees, it refused forwards recently for lack of outbound, and it is still short now. +/// A reserved peer skips the evidence: being short now, or having no channel at all, is enough. /// public static class ChannelOpenInitiatorService { @@ -78,7 +81,8 @@ public static ChannelOpenClassification Evaluate( var rejected = new List(); var now = DateTimeOffset.UtcNow; - foreach (var peer in peers.OrderByDescending(x => x.EarnedFeeSats)) + // Reserved peers first, so a share set aside for them is not lost to the per-run cap. + foreach (var peer in peers.OrderByDescending(x => x.IsReserved).ThenByDescending(x => x.EarnedFeeSats)) { var reason = Reject(peer, t); if (reason != null) @@ -103,8 +107,9 @@ public static ChannelOpenClassification Evaluate( UsableLocalSats = peer.UsableLocalSats, PeerCapacitySats = peer.CapacitySats, SuggestedCapacitySats = t.SizeSats, - InheritedFeeRatePpm = peer.OutboundPolicy!.FeeRatePpm, - InheritedBaseFeeMsat = peer.OutboundPolicy.BaseFeeMsat, + InheritedFeeRatePpm = peer.OutboundPolicy?.FeeRatePpm, + InheritedBaseFeeMsat = peer.OutboundPolicy?.BaseFeeMsat, + IsReservedPeer = peer.IsReserved, Status = ChannelOpenRecommendationStatus.Open, LastEvidenceAt = now }); @@ -120,44 +125,60 @@ public static ChannelOpenClassification Evaluate( return "on cooldown after a recent promotion or dismissal"; } - // Without it the channel can't be priced: at the global default it would undercut what we - // already charge this peer. - if (peer.OutboundPolicy == null) + var reason = peer.IsReserved ? RejectReserved(peer, t) : RejectOnEvidence(peer, t); + if (reason != null) { - return "no outbound fee policy reported for any channel to the peer"; + return reason; } - if (peer.EarnedFeeSats < t.MinEarnedFeeSats) + if (t.SizeSats <= 0) { - return $"earned {peer.EarnedFeeSats} sats, below the {t.MinEarnedFeeSats} sats minimum"; + return "the node has no channel size configured"; } - if (peer.Refusals < t.MinRefusals) + if (t.SizeSats > t.WalletSpendableSats) { - return $"{peer.Refusals} refused forward(s), below the {t.MinRefusals} minimum"; + return $"the funding wallet can fund at most {t.WalletSpendableSats} sats, below the {t.SizeSats} sats size"; } - // The refusals are history; a rebalance or a settled HTLC may have refilled the peer since. - if (peer.UsableLocalSats * 100 >= peer.CapacitySats * t.LowOutboundPct) + var headroom = t.Budget.HeadroomFor(peer.PeerPubKey); + if (t.SizeSats > headroom) { - return $"{peer.UsableLocalSats} of {peer.CapacitySats} sats usable outbound, not below {t.LowOutboundPct}%"; + return $"{headroom} sats of budget left for the peer, below the {t.SizeSats} sats size"; } - if (t.SizeSats <= 0) + return null; + } + + private static string? RejectOnEvidence(PeerSnapshot peer, ChannelOpenInitiatorTunables t) + { + // Without it the channel can't be priced: at the global default it would undercut what we + // already charge this peer. + if (peer.OutboundPolicy == null) { - return "the node has no channel size configured"; + return "no outbound fee policy reported for any channel to the peer"; } - if (t.SizeSats > t.WalletSpendableSats) + if (peer.EarnedFeeSats < t.MinEarnedFeeSats) { - return $"the funding wallet can fund at most {t.WalletSpendableSats} sats, below the {t.SizeSats} sats size"; + return $"earned {peer.EarnedFeeSats} sats, below the {t.MinEarnedFeeSats} sats minimum"; } - if (t.SizeSats > t.RemainingBudgetSats) + if (peer.Refusals < t.MinRefusals) { - return $"{t.RemainingBudgetSats} sats of budget left, below the {t.SizeSats} sats size"; + return $"{peer.Refusals} refused forward(s), below the {t.MinRefusals} minimum"; } - return null; + return RejectNotShortNow(peer, t); } + + // A swap service is paid by our own payments, not forwards, so it never earns the evidence above. + private static string? RejectReserved(PeerSnapshot peer, ChannelOpenInitiatorTunables t) + => peer.CapacitySats == 0 ? null : RejectNotShortNow(peer, t); + + // The refusals are history; a rebalance or a settled HTLC may have refilled the peer since. + private static string? RejectNotShortNow(PeerSnapshot peer, ChannelOpenInitiatorTunables t) + => peer.UsableLocalSats * 100 >= peer.CapacitySats * t.LowOutboundPct + ? $"{peer.UsableLocalSats} of {peer.CapacitySats} sats usable outbound, not below {t.LowOutboundPct}%" + : null; } diff --git a/src/Services/ChannelOpenPromotionService.cs b/src/Services/ChannelOpenPromotionService.cs index 67e6e66cc..3d1cc32f5 100644 --- a/src/Services/ChannelOpenPromotionService.cs +++ b/src/Services/ChannelOpenPromotionService.cs @@ -103,7 +103,8 @@ public ChannelOpenPromotionService( // A second channel to this peer arrives full, so at the global default it would be the // cheapest route to a peer the drain evidence proves is expensive. It opens at the price we // already charge that peer, captured with the evidence and gated on — asking LND again here - // would reprice off gossip and could contradict the number the operator approved. + // would reprice off gossip and could contradict the number the operator approved. A reserved + // peer we had no channel with has no price to copy, so it carries the one set on its reservation. if (recommendation.InheritedFeeRatePpm is null or < 0) { return (false, $"Recommendation {recommendationId} carries no inherited fee policy, so there is no price to open at — it predates fee capture and will be replaced on the next run"); @@ -164,12 +165,15 @@ await _auditService.LogAsync( SuggestedCapacitySats = recommendation.SuggestedCapacitySats, ApprovedCapacitySats = capacitySats, PeerPubKey = recommendation.PeerPubKey, + recommendation.IsReservedPeer, InitialChannelBaseFeeMsat = recommendation.InheritedBaseFeeMsat, InitialChannelFeeRatePpm = recommendation.InheritedFeeRatePpm, Description = $"Channel open request created from recommendation {recommendationId} " + $"({capacitySats} sats, suggested {recommendation.SuggestedCapacitySats} sats, " + $"opening at {recommendation.InheritedFeeRatePpm} ppm / {recommendation.InheritedBaseFeeMsat} msat, " + - $"the most we already charge this peer)" + (recommendation.IsReservedPeer && recommendation.PeerCapacitySats == 0 + ? "the fee set for this reserved peer)" + : "the most we already charge this peer)") }); _logger.LogInformation( @@ -308,8 +312,9 @@ await _auditService.LogAsync( /// /// Summarised onto the request so an approver sees why it exists without leaving that page. /// - private static string BuildDescription(ChannelOpenRecommendation r) => - $"Auto channel open: earned {r.EarnedFeeSats} sats in fees over {r.SettledOutSats} sats routed " + - $"in {Constants.AUTO_CHANNEL_OPEN_LOOKBACK_DAYS}d, {r.Refusals} forward(s) refused for lack of outbound " + - $"in {Constants.AUTO_CHANNEL_OPEN_SHORTAGE_HOURS}h, {r.UsableLocalSats} of {r.PeerCapacitySats} sats usable outbound."; + private static string BuildDescription(ChannelOpenRecommendation r) => r.IsReservedPeer + ? $"Auto channel open to a reserved peer: {r.UsableLocalSats} of {r.PeerCapacitySats} sats usable outbound." + : $"Auto channel open: earned {r.EarnedFeeSats} sats in fees over {r.SettledOutSats} sats routed " + + $"in {Constants.AUTO_CHANNEL_OPEN_LOOKBACK_DAYS}d, {r.Refusals} forward(s) refused for lack of outbound " + + $"in {Constants.AUTO_CHANNEL_OPEN_SHORTAGE_HOURS}h, {r.UsableLocalSats} of {r.PeerCapacitySats} sats usable outbound."; } diff --git a/test/NodeGuard.Tests/Data/Repositories/ChannelOperationRequestRepositoryTests.cs b/test/NodeGuard.Tests/Data/Repositories/ChannelOperationRequestRepositoryTests.cs index 35801e0e6..282b3c43f 100644 --- a/test/NodeGuard.Tests/Data/Repositories/ChannelOperationRequestRepositoryTests.cs +++ b/test/NodeGuard.Tests/Data/Repositories/ChannelOperationRequestRepositoryTests.cs @@ -188,4 +188,40 @@ public async Task GetOpenSatsCommittedSince_ReturnsZero_WhenNothingMatches() // Assert result.Should().Be(0); } + + [Fact] + public async Task GetOpenSatsCommittedByPeerSince_SplitsTheLiveOpensByTheirPeer() + { + // Arrange + var dbContextFactory = SetupDbContextFactory(); + await using var context = await dbContextFactory.Object.CreateDbContextAsync(); + var now = DateTimeOffset.UtcNow; + + await context.Nodes.AddRangeAsync( + new Node { Id = 50, PubKey = "03loop", Name = "loop" }, + new Node { Id = 51, PubKey = "03peer", Name = "peer" }); + var toLoop = Committed(1, 100, ChannelOperationRequestStatus.Pending, now); + toLoop.DestNodeId = 50; + var toLoopAgain = Committed(1, 200, ChannelOperationRequestStatus.OnChainConfirmed, now); + toLoopAgain.DestNodeId = 50; + var toPeer = Committed(1, 400, ChannelOperationRequestStatus.Pending, now); + toPeer.DestNodeId = 51; + var failedToPeer = Committed(1, 800, ChannelOperationRequestStatus.Failed, now); + failedToPeer.DestNodeId = 51; + var noPeer = Committed(1, 1600, ChannelOperationRequestStatus.Pending, now); + noPeer.DestNodeId = null; + await context.ChannelOperationRequests.AddRangeAsync(toLoop, toLoopAgain, toPeer, failedToPeer, noPeer); + await context.SaveChangesAsync(); + + // Act + var result = await BudgetSut(dbContextFactory).GetOpenSatsCommittedByPeerSince(1, now.AddDays(-1)); + + // Assert + result.Should().BeEquivalentTo(new Dictionary + { + ["03loop"] = 300, + ["03peer"] = 400, + [""] = 1600, + }); + } } diff --git a/test/NodeGuard.Tests/Data/Repositories/ReservedChannelOpenPeerRepositoryTests.cs b/test/NodeGuard.Tests/Data/Repositories/ReservedChannelOpenPeerRepositoryTests.cs new file mode 100644 index 000000000..b0c0912ee --- /dev/null +++ b/test/NodeGuard.Tests/Data/Repositories/ReservedChannelOpenPeerRepositoryTests.cs @@ -0,0 +1,82 @@ +/* + * 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; +using NodeGuard.Data.Models; + +namespace NodeGuard.Data.Repositories; + +public class ReservedChannelOpenPeerRepositoryTests +{ + private const int Loop = 10; + private const int Boltz = 11; + + private readonly Random _random = new(); + + private ReservedChannelOpenPeerRepository Repository() + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: "ReservedChannelOpenPeer" + _random.Next()) + .Options; + var factory = new Mock>(); + factory.Setup(x => x.CreateDbContextAsync(default)).ReturnsAsync(() => new ApplicationDbContext(options)); + + using var context = new ApplicationDbContext(options); + context.Nodes.AddRange( + new Node { Id = 1, Name = "alice", PubKey = "alice" }, + new Node { Id = 2, Name = "bob", PubKey = "bob" }, + new Node { Id = Loop, Name = "loop", PubKey = "loop" }, + new Node { Id = Boltz, Name = "boltz", PubKey = "boltz" }); + context.SaveChanges(); + + return new ReservedChannelOpenPeerRepository(factory.Object, Mock.Of>()); + } + + private static ReservedChannelOpenPeer Reserved(int peerNodeId, int pct) + => new() { PeerNodeId = peerNodeId, BudgetPct = pct, FeeRatePpm = 500, BaseFeeMsat = 1_000 }; + + [Fact] + public async Task ReplaceForNode_ReplacesTheWholeListOfThatNodeOnly() + { + var repository = Repository(); + await repository.ReplaceForNode(1, [Reserved(Loop, 20), Reserved(Boltz, 10)]); + await repository.ReplaceForNode(2, [Reserved(Loop, 50)]); + + // Re-adding a peer that is already saved must not trip the unique index. + var (ok, error) = await repository.ReplaceForNode(1, [Reserved(Loop, 30)]); + + ok.Should().BeTrue(error); + (await repository.GetByNode(1)).Should().ContainSingle() + .Which.Should().BeEquivalentTo(new { PeerNodeId = Loop, BudgetPct = 30, FeeRatePpm = 500L, BaseFeeMsat = 1_000L, PeerNode = new { PubKey = "loop" } }); + (await repository.GetByNode(2)).Should().ContainSingle().Which.BudgetPct.Should().Be(50); + } + + [Fact] + public async Task ReplaceForNode_EmptyList_ClearsTheNode() + { + var repository = Repository(); + await repository.ReplaceForNode(1, [Reserved(Loop, 20)]); + + await repository.ReplaceForNode(1, []); + + (await repository.GetByNode(1)).Should().BeEmpty(); + } +} diff --git a/test/NodeGuard.Tests/E2E/AutoChannelOpenE2ETests.cs b/test/NodeGuard.Tests/E2E/AutoChannelOpenE2ETests.cs index 27aeae80c..22dd1cf53 100644 --- a/test/NodeGuard.Tests/E2E/AutoChannelOpenE2ETests.cs +++ b/test/NodeGuard.Tests/E2E/AutoChannelOpenE2ETests.cs @@ -32,6 +32,8 @@ namespace NodeGuard.Tests.E2E; /// to carol is drained, and alice's next payments over the same route are refused at bob's link with /// INSUFFICIENT_BALANCE. Bob is then switched on in Recommendation mode (row recorded, nothing opened) and /// then in Auto mode (request created, channel opened at the price bob already charges carol). +/// Two more scenarios cover reserved peers: one with no channel and no evidence opens at the fee set for it, +/// and one still opens when its share is all the budget has left, while the earning peer is skipped. /// Order-agnostic and self-resetting; serial with the other e2e classes via [Collection("E2E")]. ///
[Trait("Category", "E2E")] @@ -41,6 +43,16 @@ public class AutoChannelOpenE2ETests : RoutingEngineE2EBase private const long SizeSats = 5_000_000; private const long BudgetSats = 50_000_000; + // The size of the alice→bob channel the other scenarios open, so the one left behind serves them + private const long FirstChannelSizeSats = 16_000_000; + private const int FirstChannelReservedPct = 50; + // Unlike anything setup-e2e or LND's defaults give a channel, so only the reservation explains them + private const long ReservedFeeRatePpm = 777; + private const long ReservedBaseFeeMsat = 3_000; + // 90% of it is one channel for the reserved peer; the other 10% is below the size + private const long ReservedShareOnlyBudgetSats = 6_000_000; + private const int ReservedShareOnlyPct = 90; + private const long EarningPaymentSats = 100_000; private const long RefusedPaymentSats = 1_000_000; // Constants reads AUTO_CHANNEL_OPEN_MIN_REFUSALS from the e2e-runner env, so this tracks the compose file @@ -89,7 +101,7 @@ public async Task AutoChannelOpen_EarningRouteRunsOutOfOutbound_RecommendsThenOp // ── Recommendation mode: recorded, nothing opened ──────────────────────────────────── await EnableAsync(scenario.BobNodeId, walletId, AutoChannelOpenMode.Recommendation); - var recommendation = await PollRecommendationAsync(scenario, r => r.Status == ChannelOpenRecommendationStatus.Open, + var recommendation = await PollRecommendationAsync(scenario.BobNodeId, carol.PubKey, r => r.Status == ChannelOpenRecommendationStatus.Open, "AutoChannelOpenJob recorded an open recommendation for carol"); recommendation.SuggestedCapacitySats.Should().Be(SizeSats, "every open uses the node's fixed size"); @@ -104,7 +116,7 @@ public async Task AutoChannelOpen_EarningRouteRunsOutOfOutbound_RecommendsThenOp // ── Auto mode: promoted, request created, channel opened ───────────────────────────── await EnableAsync(scenario.BobNodeId, walletId, AutoChannelOpenMode.Auto); - recommendation = await PollRecommendationAsync(scenario, + recommendation = await PollRecommendationAsync(scenario.BobNodeId, carol.PubKey, r => r.Status == ChannelOpenRecommendationStatus.Promoted, "AutoChannelOpenJob promoted carol's recommendation"); recommendation.ChannelOperationRequestId.Should().NotBeNull("promotion links the request it created"); @@ -162,6 +174,164 @@ public async Task AutoChannelOpen_EarningRouteRunsOutOfOutbound_RecommendsThenOp } } + /// + /// Alice reserves bob with no channel between them and no forwards or refusals anywhere. The job + /// recommends bob as reserved at the fee set on the reservation, and in Auto mode opens the channel + /// at it. Every alice↔bob channel is closed first; the one opened here replaces them. + /// + [E2EFact, Trait("Speed", "Slow")] + public async Task AutoChannelOpen_ReservedPeerWithNoChannel_RecommendsThenOpensAtItsReservedFee() + { + var scenario = await LoadScenarioAsync(); + var (client, headers, rpc) = (scenario.Client, scenario.Headers, scenario.Rpc); + var (alice, bob) = (scenario.Alice, scenario.Bob); + var walletId = int.Parse(Env("E2E_HOT_WALLET_ID", "3")); + + try + { + await ResetAutoChannelOpenAsync(scenario.AliceNodeId, dynamicFees: false); + // No forwards and no refusals: the reservation is the only reason bob can qualify + await ResetRoutingEngineStateAsync(); + + await CloseChannelsAsync(rpc, alice, bob); + // Peers with no channel are not kept connected, and alice can't learn bob's address from gossip + await alice.ConnectAsync(bob.PubKey, $"{bob.Name}:9735"); + await ReserveAsync(scenario.AliceNodeId, scenario.BobNodeId, FirstChannelReservedPct); + + // Earlier scenarios leave unconfirmed change in the hot wallet; the wallet check only counts + // confirmed coins + await MineAsync(rpc, 6); + + // ── Recommendation mode: recorded as reserved, nothing opened ──────────────────────── + await EnableAsync(scenario.AliceNodeId, walletId, AutoChannelOpenMode.Recommendation, FirstChannelSizeSats); + var recommendation = await PollRecommendationAsync(scenario.AliceNodeId, bob.PubKey, + r => r.Status == ChannelOpenRecommendationStatus.Open, + "AutoChannelOpenJob recorded an open recommendation for the reserved bob"); + + recommendation.IsReservedPeer.Should().BeTrue(); + recommendation.SuggestedCapacitySats.Should().Be(FirstChannelSizeSats); + recommendation.EarnedFeeSats.Should().Be(0, "a reserved peer needs no earnings"); + recommendation.Refusals.Should().Be(0, "a reserved peer needs no refusals"); + recommendation.PeerCapacitySats.Should().Be(0, "alice has no channel with bob"); + recommendation.InheritedFeeRatePpm.Should().Be(ReservedFeeRatePpm, "with no channel to copy a price from, the reservation's applies"); + recommendation.InheritedBaseFeeMsat.Should().Be(ReservedBaseFeeMsat); + recommendation.ChannelOperationRequestId.Should().BeNull("Recommendation mode leaves the decision to a person"); + + // ── Auto mode: promoted, request created, channel opened at the reserved fee ───────── + await EnableAsync(scenario.AliceNodeId, walletId, AutoChannelOpenMode.Auto, FirstChannelSizeSats); + recommendation = await PollRecommendationAsync(scenario.AliceNodeId, bob.PubKey, + r => r.Status == ChannelOpenRecommendationStatus.Promoted, + "AutoChannelOpenJob promoted the reserved bob's recommendation"); + recommendation.ChannelOperationRequestId.Should().NotBeNull("promotion links the request it created"); + var requestId = recommendation.ChannelOperationRequestId!.Value; + + await using (var db = CreateDbContext()) + { + var request = await db.ChannelOperationRequests.AsNoTracking().SingleAsync(r => r.Id == requestId); + request.Status.Should().NotBe(ChannelOperationRequestStatus.Failed, + "the promoted request must reach dispatch — check NodeGuard's log for the promotion failure reason"); + request.SourceNodeId.Should().Be(scenario.AliceNodeId); + request.DestNodeId.Should().Be(scenario.BobNodeId); + request.SatsAmount.Should().Be(FirstChannelSizeSats); + request.InitialChannelFeeRatePpm.Should().Be(ReservedFeeRatePpm); + request.InitialChannelBaseFeeMsat.Should().Be(ReservedBaseFeeMsat); + } + + var channelId = (int)await MineUntilChannelOpenedAsync(client, headers, rpc, requestId); + var newScid = await ScidOfAsync(channelId); + + var opened = await PollAsync( + async () => (await alice.ChannelsToAsync(bob.PubKey)).FirstOrDefault(c => c.ChanId == newScid), + c => c is { Active: true }, + attempts: 20, delay: TimeSpan.FromSeconds(3), + what: $"alice's new channel {newScid} to bob is active"); + opened!.Capacity.Should().Be(FirstChannelSizeSats); + opened.Initiator.Should().BeTrue("alice funded it"); + + var newPolicy = await alice.OutboundPolicyAsync(newScid); + newPolicy.Should().NotBeNull(); + newPolicy!.FeePerMil.Should().Be(ReservedFeeRatePpm, "the new channel opens at the fee set for the reserved peer"); + newPolicy.BaseFeeMsat.Should().Be(ReservedBaseFeeMsat); + _output.WriteLine($"[result] channel #{channelId} scid {newScid}: {opened.Capacity} sats at {newPolicy.FeePerMil} ppm / {newPolicy.BaseFeeMsat} msat"); + } + finally + { + await ResetAutoChannelOpenAsync(scenario.AliceNodeId, dynamicFees: scenario.AliceDynamicFees); + } + } + + /// + /// Bob's budget leaves ordinary peers less than one channel, with the rest reserved for alice. Carol + /// earns and refuses exactly as in the first scenario and gets nothing; alice, short of outbound and + /// with no evidence at all, still gets her channel out of her own share. + /// + [E2EFact, Trait("Speed", "Slow")] + public async Task AutoChannelOpen_OnlyTheReservedShareLeft_SkipsTheEarningPeerAndOpensTheReservedOne() + { + var scenario = await LoadScenarioAsync(); + var (client, headers, rpc) = (scenario.Client, scenario.Headers, scenario.Rpc); + var (alice, bob, carol) = (scenario.Alice, scenario.Bob, scenario.Carol); + var walletId = int.Parse(Env("E2E_HOT_WALLET_ID", "3")); + ulong? openedScid = null; + + try + { + await ResetAutoChannelOpenAsync(scenario.BobNodeId, dynamicFees: false); + await ResetRoutingEngineStateAsync(); + + var aliceToBobScid = await ResolveAliceToBobAsync(client, headers, rpc, alice, bob.PubKey); + + // Carol qualifies on evidence, as in the first scenario + await EarnOnBobToCarolAsync(alice, bob, carol, aliceToBobScid); + await DrainUsableLocalAsync(bob, carol); + await SendRefusedPaymentsAsync(alice, bob, carol, aliceToBobScid); + + // Alice qualifies as reserved once bob is short of outbound to her + await DrainUsableLocalAsync(bob, alice); + var aliceScids = (await bob.ChannelsToAsync(alice.PubKey)).Select(c => c.ChanId).ToHashSet(); + var dearest = await DearestPolicyAsync(bob, aliceScids); + await ReserveAsync(scenario.BobNodeId, scenario.AliceNodeId, ReservedShareOnlyPct); + + await MineAsync(rpc, 6); + + await EnableAsync(scenario.BobNodeId, walletId, AutoChannelOpenMode.Auto, budgetSats: ReservedShareOnlyBudgetSats); + var recommendation = await PollRecommendationAsync(scenario.BobNodeId, alice.PubKey, + r => r.Status == ChannelOpenRecommendationStatus.Promoted, + "AutoChannelOpenJob promoted the reserved alice's recommendation"); + + recommendation.IsReservedPeer.Should().BeTrue(); + recommendation.SuggestedCapacitySats.Should().Be(SizeSats); + recommendation.InheritedFeeRatePpm.Should().Be(dearest.FeePerMil, "bob already has a price toward alice to copy"); + recommendation.ChannelOperationRequestId.Should().NotBeNull("promotion links the request it created"); + var requestId = recommendation.ChannelOperationRequestId!.Value; + + var channelId = (int)await MineUntilChannelOpenedAsync(client, headers, rpc, requestId); + openedScid = await ScidOfAsync(channelId); + aliceScids.Should().NotContain(openedScid.Value, "the open buys a new channel, not one we already had"); + + // Read after the open, so the run that promoted alice has long finished with carol + await using (var db = CreateDbContext()) + { + var carolRecommendations = await db.ChannelOpenRecommendations.AsNoTracking() + .CountAsync(r => r.NodeId == scenario.BobNodeId && r.PeerPubKey == carol.PubKey); + carolRecommendations.Should().Be(0, + $"the {ReservedShareOnlyBudgetSats * (100 - ReservedShareOnlyPct) / 100} sats outside alice's share don't fund a {SizeSats} sats channel"); + } + + _output.WriteLine($"[result] channel #{channelId} scid {openedScid} opened to the reserved alice; carol skipped"); + } + finally + { + await ResetAutoChannelOpenAsync(scenario.BobNodeId, dynamicFees: scenario.BobDynamicFees); + + // Outbound from bob to alice would skew the rebalance scenarios + if (openedScid != null) + { + await CloseChannelsAsync(rpc, bob, alice, openedScid); + } + } + } + private sealed record Scenario( Nodeguard.NodeGuardService.NodeGuardServiceClient Client, Grpc.Core.Metadata Headers, @@ -169,8 +339,10 @@ private sealed record Scenario( LndTestClient Alice, LndTestClient Bob, LndTestClient Carol, + int AliceNodeId, int BobNodeId, int CarolNodeId, + bool AliceDynamicFees, bool BobDynamicFees); private async Task LoadScenarioAsync() @@ -184,6 +356,7 @@ private async Task LoadScenarioAsync() _output.WriteLine($"alice={aliceNode.PubKey} bob={bobNode.PubKey} carol={carolNode.PubKey}"); await using var db = CreateDbContext(); + var aliceRow = await db.Nodes.AsNoTracking().SingleAsync(n => n.PubKey == aliceNode.PubKey); var bobRow = await db.Nodes.AsNoTracking().SingleAsync(n => n.PubKey == bobNode.PubKey); var carolNodeId = await db.Nodes.AsNoTracking().Where(n => n.PubKey == carolNode.PubKey) .Select(n => n.Id).SingleAsync(); @@ -193,7 +366,7 @@ private async Task LoadScenarioAsync() LndTestClient.FromEnv("alice", aliceNode.PubKey), LndTestClient.FromEnv("bob", bobNode.PubKey), LndTestClient.FromEnv("carol", carolNode.PubKey), - bobRow.Id, carolNodeId, bobRow.DynamicFeeManagementEnabled); + aliceRow.Id, bobRow.Id, carolNodeId, aliceRow.DynamicFeeManagementEnabled, bobRow.DynamicFeeManagementEnabled); } /// @@ -334,7 +507,8 @@ private static async Task DearestPolicyAsync(LndTestClient bob return dearest!; } - private static async Task EnableAsync(int nodeId, int walletId, AutoChannelOpenMode mode) + private static async Task EnableAsync(int nodeId, int walletId, AutoChannelOpenMode mode, + long sizeSats = SizeSats, long budgetSats = BudgetSats) { await using var db = CreateDbContext(); var updated = await db.Nodes @@ -343,24 +517,76 @@ private static async Task EnableAsync(int nodeId, int walletId, AutoChannelOpenM .SetProperty(n => n.AutoChannelOpenEnabled, true) .SetProperty(n => n.AutoChannelOpenMode, mode) .SetProperty(n => n.AutoChannelOpenWalletId, (int?)walletId) - .SetProperty(n => n.AutoChannelOpenSizeSats, (long?)SizeSats) - .SetProperty(n => n.AutoChannelOpenBudgetSats, (long?)BudgetSats) + .SetProperty(n => n.AutoChannelOpenSizeSats, (long?)sizeSats) + .SetProperty(n => n.AutoChannelOpenBudgetSats, (long?)budgetSats) // Null start ⇒ a fresh period, so opens from other scenarios don't count against it .SetProperty(n => n.AutoChannelOpenBudgetStartDatetime, (DateTimeOffset?)null) .SetProperty(n => n.AutoChannelOpenBudgetRefreshInterval, (TimeSpan?)null) .SetProperty(n => n.RoutingEngineDryRun, false)); - updated.Should().Be(1, "bob should be seeded"); + updated.Should().Be(1, "the node should be seeded"); + } + + private static async Task ReserveAsync(int nodeId, int peerNodeId, int budgetPct) + { + await using var db = CreateDbContext(); + var now = DateTimeOffset.UtcNow; + db.ReservedChannelOpenPeers.Add(new ReservedChannelOpenPeer + { + NodeId = nodeId, + PeerNodeId = peerNodeId, + BudgetPct = budgetPct, + FeeRatePpm = ReservedFeeRatePpm, + BaseFeeMsat = ReservedBaseFeeMsat, + CreationDatetime = now, + UpdateDatetime = now + }); + await db.SaveChangesAsync(); + } + + private static async Task ScidOfAsync(int channelId) + { + await using var db = CreateDbContext(); + return await db.Channels.AsNoTracking().Where(c => c.Id == channelId).Select(c => c.ChanId).SingleAsync(); + } + + /// + /// Closes the channels between two nodes, whoever opened them — all of them, or just + /// — and mines until LND no longer lists them. + /// + private async Task CloseChannelsAsync(NBitcoin.RPC.RPCClient rpc, LndTestClient node, LndTestClient peer, ulong? onlyScid = null) + { + async Task> ReadAsync() + => (await node.ChannelsToAsync(peer.PubKey)).Where(c => onlyScid == null || c.ChanId == onlyScid).ToList(); + + var channels = await ReadAsync(); + foreach (var channel in channels) + { + _output.WriteLine($"[close] {node.Name}↔{peer.Name} scid {channel.ChanId} ({channel.Capacity} sats)"); + await node.CloseChannelAsync(channel.ChannelPoint); + } + + if (channels.Count == 0) return; + + await PollAsync( + async () => + { + await MineAsync(rpc, 3); + return (await ReadAsync()).Count; + }, + left => left == 0, + attempts: 20, delay: TimeSpan.FromSeconds(3), + what: $"the closed {node.Name}↔{peer.Name} channel(s) are gone from LND"); } private async Task PollRecommendationAsync( - Scenario scenario, Func done, string what) + int nodeId, string peerPubKey, Func done, string what) { var recommendation = await PollAsync( async () => { await using var db = CreateDbContext(); var row = await db.ChannelOpenRecommendations.AsNoTracking() - .FirstOrDefaultAsync(r => r.NodeId == scenario.BobNodeId && r.PeerPubKey == scenario.Carol.PubKey); + .FirstOrDefaultAsync(r => r.NodeId == nodeId && r.PeerPubKey == peerPubKey); if (row != null) _output.WriteLine($"[recommendation] #{row.Id} status={row.Status} earned={row.EarnedFeeSats} refusals={row.Refusals} usable={row.UsableLocalSats}/{row.PeerCapacitySats} request={row.ChannelOperationRequestId}"); return row; @@ -373,9 +599,9 @@ private async Task PollRecommendationAsync( } /// - /// Switches bob's channel opener off and clears his recommendations — on the way in so an earlier run's - /// Promoted row can't put carol on cooldown, and on the way out so nothing opens under the next scenario. - /// The fee engine stays off during the run so bob's price toward carol can't move under the assertions. + /// Switches a node's channel opener off and clears its recommendations and reserved peers — on the way in + /// so an earlier run's Promoted row can't put a peer on cooldown, and on the way out so nothing opens under + /// the next scenario. The fee engine stays off during the run so prices can't move under the assertions. /// private static async Task ResetAutoChannelOpenAsync(int nodeId, bool dynamicFees) { @@ -387,6 +613,7 @@ await db.Nodes .SetProperty(n => n.AutoChannelOpenMode, AutoChannelOpenMode.Recommendation) .SetProperty(n => n.DynamicFeeManagementEnabled, dynamicFees)); await db.ChannelOpenRecommendations.Where(r => r.NodeId == nodeId).ExecuteDeleteAsync(); + await db.ReservedChannelOpenPeers.Where(r => r.NodeId == nodeId).ExecuteDeleteAsync(); } // Same quantity as the job's LocalChanReserveSat, off the non-deprecated field diff --git a/test/NodeGuard.Tests/E2E/LndTestClient.cs b/test/NodeGuard.Tests/E2E/LndTestClient.cs index c724b562a..9d5188ed9 100644 --- a/test/NodeGuard.Tests/E2E/LndTestClient.cs +++ b/test/NodeGuard.Tests/E2E/LndTestClient.cs @@ -188,6 +188,20 @@ public async Task OpenChannelAsync(string peerPubKey, long localSa }, _auth); } + // Cooperative, so the peer must be online. Returns once the closing tx is BROADCAST — the caller mines. + public async Task CloseChannelAsync(string channelPoint) + { + var parts = channelPoint.Split(':'); + using var call = Lightning.CloseChannel(new CloseChannelRequest + { + ChannelPoint = new ChannelPoint { FundingTxidStr = parts[0], OutputIndex = uint.Parse(parts[1]) }, + // No fee rate of our own: the peer proposes its estimate, and one far below it caps what we + // accept at 3x ours and fails the close. Both nodes estimate off the same bitcoind. + MaxFeePerVbyte = 100, + }, _auth); + await call.ResponseStream.MoveNext(CancellationToken.None); + } + public async Task AddInvoiceAsync(long amtSats) { var resp = await Lightning.AddInvoiceAsync(new Invoice { Value = amtSats }, _auth); diff --git a/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs b/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs index 8137b750a..7182e856f 100644 --- a/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs +++ b/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs @@ -46,6 +46,9 @@ public class AutoChannelOpenJobTests private const string SecondPeer = "03peer2"; private const ulong SecondPeerChanId = 1002; private const long SizeSats = 5_000_000; + private const string ReservedPeer = "03loop"; + private const long ReservedFeeRatePpm = 750; + private const long ReservedBaseFeeMsat = 2_000; private readonly Mock> _logger = new(); private readonly Mock _nodeRepository = new(); @@ -106,7 +109,8 @@ private Node ArrangeQualifyingPeer( long committedSats = 0, bool dryRun = false, long[]? walletUtxoSats = null, - bool secondPeer = false) + bool secondPeer = false, + int reservedPct = 0) { var node = new Node { @@ -121,6 +125,10 @@ private Node ArrangeQualifyingPeer( AutoChannelOpenBudgetSats = budgetSats, AutoChannelOpenBudgetStartDatetime = DateTimeOffset.UtcNow.AddHours(-1), RoutingEngineDryRun = dryRun, + // No channel to the reserved peer: it only ever qualifies as reserved. + ReservedChannelOpenPeers = reservedPct > 0 + ? [new ReservedChannelOpenPeer { NodeId = NodeId, PeerNode = new Node { PubKey = ReservedPeer }, BudgetPct = reservedPct, FeeRatePpm = ReservedFeeRatePpm, BaseFeeMsat = ReservedBaseFeeMsat }] + : [], }; _nodeRepository.Setup(x => x.GetAllWithAutoChannelOpenEnabled()).ReturnsAsync(new List { node }); @@ -130,8 +138,8 @@ private Node ArrangeQualifyingPeer( _recommendationRepository.Setup(x => x.GetLastDecisionByPeer(NodeId)) .ReturnsAsync(new Dictionary()); _channelOperationRequestRepository - .Setup(x => x.GetOpenSatsCommittedSince(NodeId, It.IsAny())) - .ReturnsAsync(committedSats); + .Setup(x => x.GetOpenSatsCommittedByPeerSince(NodeId, It.IsAny())) + .ReturnsAsync(new Dictionary { ["03elsewhere"] = committedSats }); // Each channel alone falls short of both gates; only the peer-level sums clear them. var minFeeMsat = Constants.AUTO_CHANNEL_OPEN_MIN_EARNED_FEE_SATS * 1000; @@ -539,4 +547,50 @@ public async Task Execute_AutoModeWithoutAutomaticSwapOut_PromotesWithoutReading VerifyPromoted(Times.Once()); _swapOutWarningService.Verify(x => x.LocalBalanceSatsAsync(It.IsAny()), Times.Never); } + + // ── Reserved peers ───────────────────────────────────────────────────────────────── + + [Fact] + public async Task Execute_ReservedPeerWithNoChannel_IsRecordedAsReservedAtTheFeeOfItsReservation() + { + ArrangeQualifyingPeer(reservedPct: 20); + + await Run(); + + _recommendationRepository.Verify(x => x.Upsert(It.Is(r => + r.PeerPubKey == ReservedPeer + && r.IsReservedPeer + && r.PeerCapacitySats == 0 + && r.SuggestedCapacitySats == SizeSats + && r.InheritedFeeRatePpm == ReservedFeeRatePpm + && r.InheritedBaseFeeMsat == ReservedBaseFeeMsat)), Times.Once); + _recommendationRepository.Verify(x => x.Upsert(It.Is(r => r.PeerPubKey == Peer && !r.IsReservedPeer)), Times.Once); + } + + [Fact] + public async Task Execute_NoRefusalsAnywhere_StillEvaluatesTheReservedPeer() + { + ArrangeQualifyingPeer(reservedPct: 20); + _forwardingHtlcEventRepository + .Setup(x => x.GetInsufficientBalanceCountsByChannel(NodePubKey, It.IsAny())) + .ReturnsAsync(new Dictionary()); + + await Run(); + + VerifyRecorded(Times.Once()); + _recommendationRepository.Verify(x => x.Upsert(It.Is(r => r.PeerPubKey == ReservedPeer)), Times.Once); + } + + [Fact] + public async Task Execute_ReservedShareLeavesTooLittleForOthers_PromotesOnlyTheReservedPeer() + { + // A budget for two channels, 60% reserved: what is left for other peers is short of one channel. + ArrangeQualifyingPeer(mode: AutoChannelOpenMode.Auto, budgetSats: SizeSats * 2, reservedPct: 60); + + await Run(); + + VerifyRecorded(Times.Once()); + _recommendationRepository.Verify(x => x.Upsert(It.Is(r => r.PeerPubKey == ReservedPeer)), Times.Once); + VerifyPromoted(Times.Once()); + } } diff --git a/test/NodeGuard.Tests/Services/ChannelOpenBudgetTests.cs b/test/NodeGuard.Tests/Services/ChannelOpenBudgetTests.cs new file mode 100644 index 000000000..20884ffdb --- /dev/null +++ b/test/NodeGuard.Tests/Services/ChannelOpenBudgetTests.cs @@ -0,0 +1,107 @@ +/* + * 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; + +namespace NodeGuard.Services; + +public class ChannelOpenBudgetTests +{ + private const string Loop = "03loop"; + private const string Other = "03other"; + + private static ChannelOpenBudget Build(long budgetSats, int loopPct = 0, Dictionary? committed = null) + => ChannelOpenBudget.Build( + budgetSats, + loopPct > 0 ? new Dictionary { [Loop] = loopPct } : new Dictionary(), + committed ?? new Dictionary()); + + [Fact] + public void Build_NoReservedPeers_LeavesTheBudgetMinusWhatWasCommitted() + { + var budget = Build(10_000_000, committed: new() { [Other] = 3_000_000, [""] = 1_000_000 }); + + budget.HeadroomFor(Other).Should().Be(6_000_000); + budget.IsReserved(Other).Should().BeFalse(); + } + + [Fact] + public void Build_ReservedShare_IsOutOfReachOfOtherPeers() + { + var budget = Build(10_000_000, loopPct: 30); + + budget.HeadroomFor(Other).Should().Be(7_000_000); + budget.HeadroomFor(Loop).Should().Be(10_000_000); + } + + [Fact] + public void Build_ReservedPeerOverItsShare_TookTheExcessFromTheRest() + { + var budget = Build(10_000_000, loopPct: 30, committed: new() { [Loop] = 4_000_000 }); + + budget.HeadroomFor(Loop).Should().Be(6_000_000); + budget.HeadroomFor(Other).Should().Be(6_000_000); + } + + [Fact] + public void Build_OtherPeersOverspent_StillLeaveTheReservedShare() + { + // Opens made by hand can overshoot what is left for other peers; the reserved share survives. + var budget = Build(10_000_000, loopPct: 30, committed: new() { [Other] = 9_000_000 }); + + budget.HeadroomFor(Other).Should().Be(0); + budget.HeadroomFor(Loop).Should().Be(3_000_000); + budget.IsExhausted.Should().BeFalse(); + } + + [Fact] + public void Spend_ReservedPeer_DrawsOnItsShareBeforeTheRest() + { + var budget = Build(10_000_000, loopPct: 30); + + budget.Spend(Loop, 2_000_000); + budget.HeadroomFor(Other).Should().Be(7_000_000); + + budget.Spend(Loop, 2_000_000); + budget.HeadroomFor(Other).Should().Be(6_000_000); + budget.HeadroomFor(Loop).Should().Be(6_000_000); + } + + [Fact] + public void Spend_OtherPeer_NeverTouchesTheReservedShare() + { + var budget = Build(10_000_000, loopPct: 30); + + budget.Spend(Other, 7_000_000); + + budget.HeadroomFor(Other).Should().Be(0); + budget.HeadroomFor(Loop).Should().Be(3_000_000); + } + + [Fact] + public void IsExhausted_OnlyOnceEveryPartIsSpent() + { + var budget = Build(10_000_000, loopPct: 30, committed: new() { [Other] = 7_000_000 }); + budget.IsExhausted.Should().BeFalse(); + + budget.Spend(Loop, 3_000_000); + + budget.IsExhausted.Should().BeTrue(); + } +} diff --git a/test/NodeGuard.Tests/Services/ChannelOpenInitiatorServiceTests.cs b/test/NodeGuard.Tests/Services/ChannelOpenInitiatorServiceTests.cs index 4f0a6a3bf..013dcbd02 100644 --- a/test/NodeGuard.Tests/Services/ChannelOpenInitiatorServiceTests.cs +++ b/test/NodeGuard.Tests/Services/ChannelOpenInitiatorServiceTests.cs @@ -32,9 +32,12 @@ public class ChannelOpenInitiatorServiceTests LowOutboundPct: 20, SizeSats: Size, WalletSpendableSats: 100_000_000, - RemainingBudgetSats: 100_000_000, + Budget: Budget(100_000_000), MaxPlansPerRun: 5); + private static ChannelOpenBudget Budget(long sats, Dictionary? reservedPct = null) + => ChannelOpenBudget.Build(sats, reservedPct ?? new Dictionary(), new Dictionary()); + /// Clears every gate by default; each test breaks exactly one. private static PeerSnapshot Peer( string pubKey = "03peer", @@ -44,9 +47,20 @@ private static PeerSnapshot Peer( long capacitySats = 10_000_000, LocalOutboundPolicy? policy = null, bool noPolicy = false, - bool onCooldown = false) + bool onCooldown = false, + bool reserved = false) => new(pubKey, earnedFeeSats, 4_000_000, refusals, usableLocalSats, capacitySats, - noPolicy ? null : policy ?? new LocalOutboundPolicy(1_200, 1_000), onCooldown); + noPolicy ? null : policy ?? new LocalOutboundPolicy(1_200, 1_000), onCooldown, reserved); + + /// A reserved peer with none of the earning evidence, short of outbound. + private static PeerSnapshot ReservedPeer( + string pubKey = "03loop", + long usableLocalSats = 1_999_999, + long capacitySats = 10_000_000, + bool noPolicy = false, + bool onCooldown = false) + => Peer(pubKey, earnedFeeSats: 0, refusals: 0, usableLocalSats: usableLocalSats, capacitySats: capacitySats, + noPolicy: noPolicy, onCooldown: onCooldown, reserved: true); private static ChannelOpenClassification Evaluate(PeerSnapshot peer, ChannelOpenInitiatorTunables? t = null) => ChannelOpenInitiatorService.Evaluate([peer], t ?? Tunables); @@ -111,7 +125,7 @@ public void Evaluate_WalletCannotFundTheSize_IsRejectedRatherThanShrunk() [Fact] public void Evaluate_BudgetCannotCoverTheSize_IsRejectedRatherThanShrunk() { - var result = Evaluate(Peer(), Tunables with { RemainingBudgetSats = Size - 1 }); + var result = Evaluate(Peer(), Tunables with { Budget = Budget(Size - 1) }); result.Plans.Should().BeEmpty(); result.Rejected.Should().ContainSingle().Which.Reason.Should().Contain("budget"); @@ -132,4 +146,66 @@ public void Evaluate_MorePeersThanTheRunCap_KeepsTheHighestEarners() result.Plans.Select(x => x.PeerPubKey).Should().Equal("03high", "03mid"); result.Rejected.Should().ContainSingle().Which.PeerPubKey.Should().Be("03low"); } + + // ── Reserved peers ───────────────────────────────────────────────────────────────── + + [Fact] + public void Evaluate_ReservedPeerShortOfOutbound_IsPlannedWithoutAnyEvidence() + { + var result = Evaluate(ReservedPeer()); + + var plan = result.Plans.Should().ContainSingle().Subject; + plan.IsReservedPeer.Should().BeTrue(); + plan.SuggestedCapacitySats.Should().Be(Size); + plan.InheritedFeeRatePpm.Should().Be(1_200); + } + + [Fact] + public void Evaluate_ReservedPeerWithNoChannel_IsPlannedAtThePolicyItCarries() + { + // The job hands a channel-less reserved peer the fee set on its reservation. + var result = Evaluate(ReservedPeer(usableLocalSats: 0, capacitySats: 0)); + + var plan = result.Plans.Should().ContainSingle().Subject; + plan.IsReservedPeer.Should().BeTrue(); + plan.PeerCapacitySats.Should().Be(0); + plan.InheritedFeeRatePpm.Should().Be(1_200); + plan.InheritedBaseFeeMsat.Should().Be(1_000); + } + + [Fact] + public void Evaluate_ReservedPeerWithOutboundAtTheThreshold_IsRejected() + { + var result = Evaluate(ReservedPeer(usableLocalSats: 2_000_000)); + + result.Plans.Should().BeEmpty(); + result.Rejected.Should().ContainSingle().Which.Reason.Should().Contain("usable outbound"); + } + + [Fact] + public void Evaluate_ReservedPeerOnCooldown_IsRejected() + => Evaluate(ReservedPeer(onCooldown: true)).Plans.Should().BeEmpty(); + + [Fact] + public void Evaluate_ReservedPeer_GoesAheadOfHigherEarnersUnderTheRunCap() + { + var peers = new[] { Peer("03high", earnedFeeSats: 90_000), ReservedPeer() }; + + var result = ChannelOpenInitiatorService.Evaluate(peers, Tunables with { MaxPlansPerRun = 1 }); + + result.Plans.Should().ContainSingle().Which.PeerPubKey.Should().Be("03loop"); + } + + [Fact] + public void Evaluate_OrdinaryPeer_CannotSpendAReservedShare() + { + // A budget for two channels, 60% reserved: what is left for other peers is short of one channel. + var budget = Budget(Size * 2, new Dictionary { ["03loop"] = 60 }); + var peers = new[] { Peer("03peer"), ReservedPeer() }; + + var result = ChannelOpenInitiatorService.Evaluate(peers, Tunables with { Budget = budget }); + + result.Plans.Should().ContainSingle().Which.PeerPubKey.Should().Be("03loop"); + result.Rejected.Should().ContainSingle().Which.Reason.Should().Contain("budget"); + } } diff --git a/test/NodeGuard.Tests/Services/ChannelOpenPromotionServiceTests.cs b/test/NodeGuard.Tests/Services/ChannelOpenPromotionServiceTests.cs index 245d0e84e..5712c7cf1 100644 --- a/test/NodeGuard.Tests/Services/ChannelOpenPromotionServiceTests.cs +++ b/test/NodeGuard.Tests/Services/ChannelOpenPromotionServiceTests.cs @@ -343,6 +343,57 @@ public async Task Promote_PeerChargedZeroPpm_OpensAtZeroRatherThanRefusing() captured.InitialChannelBaseFeeMsat.Should().Be(1_000); } + [Fact] + public async Task Promote_ReservedPeerWithNoFee_IsRefused() + { + // The job always gives a reserved peer a fee, copied or the one set on its reservation, so a row + // without one is refused like any other rather than opened at the node's default. + ArrangePromotable(); + _recommendationRepository + .Setup(x => x.GetById(RecommendationId)) + .ReturnsAsync(() => + { + var reserved = Recommendation(); + reserved.IsReservedPeer = true; + reserved.InheritedFeeRatePpm = null; + reserved.InheritedBaseFeeMsat = null; + return reserved; + }); + + var (ok, error) = await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + ok.Should().BeFalse(); + error.Should().Contain("no inherited fee policy"); + _channelOperationRequestRepository.Verify(x => x.AddAsync(It.IsAny()), Times.Never); + } + + [Fact] + public async Task Promote_ReservedPeer_OpensAtTheFeeItCarries() + { + ArrangePromotable(); + _recommendationRepository + .Setup(x => x.GetById(RecommendationId)) + .ReturnsAsync(() => + { + var reserved = Recommendation(); + reserved.IsReservedPeer = true; + reserved.InheritedFeeRatePpm = 750; + reserved.InheritedBaseFeeMsat = 2_000; + return reserved; + }); + ChannelOperationRequest? captured = null; + _channelOperationRequestRepository + .Setup(x => x.AddAsync(It.IsAny())) + .ReturnsAsync((ChannelOperationRequest r) => { r.Id = 500; captured = r; return (true, (string?)null); }); + + var (ok, _) = await BuildService().Promote(RecommendationId, 5_000_000, userId: "u1"); + + ok.Should().BeTrue(); + captured!.InitialChannelFeeRatePpm.Should().Be(750); + captured.InitialChannelBaseFeeMsat.Should().Be(2_000); + captured.Description.Should().Contain("reserved peer"); + } + // ── Promote: dispatch ────────────────────────────────────────────────────────────── [Fact] diff --git a/test/NodeGuard.Tests/ValidationHelperTests.cs b/test/NodeGuard.Tests/ValidationHelperTests.cs index 885de2d67..c8aeef60c 100644 --- a/test/NodeGuard.Tests/ValidationHelperTests.cs +++ b/test/NodeGuard.Tests/ValidationHelperTests.cs @@ -16,6 +16,8 @@ * along with this program. If not, see http://www.gnu.org/licenses/. */ +using FluentAssertions; +using NodeGuard.Data.Models; using NodeGuard.Helpers; namespace NodeGuard.Tests; @@ -40,6 +42,64 @@ public void ValidateXPUBTest(string xpub, bool expected) Assert.Equal(expected, actual); } + private const int Loop = 10; + private const int Boltz = 11; + private const int OwnNode = 1; + + private static ReservedChannelOpenPeer Reserved(int peerNodeId, int pct = 20, long? feeRatePpm = 500, long? baseFeeMsat = 1_000) + => new() { PeerNodeId = peerNodeId, BudgetPct = pct, FeeRatePpm = feeRatePpm, BaseFeeMsat = baseFeeMsat }; + + [Fact] + public void ValidateReservedChannelOpenPeers_ZeroFees_Pass() + => ValidationHelper.ValidateReservedChannelOpenPeers([Reserved(Loop, feeRatePpm: 0, baseFeeMsat: 0)], OwnNode) + .Should().BeNull(); + + [Theory] + [InlineData(null, 1_000L)] + [InlineData(500L, null)] + public void ValidateReservedChannelOpenPeers_FeeLeftUnset_Fails(long? feeRatePpm, long? baseFeeMsat) + => ValidationHelper.ValidateReservedChannelOpenPeers([Reserved(Loop, feeRatePpm: feeRatePpm, baseFeeMsat: baseFeeMsat)], OwnNode) + .Should().Contain("Set a fee rate and a base fee"); + + [Theory] + [InlineData(-1L, 1_000L)] + [InlineData(500L, -1L)] + public void ValidateReservedChannelOpenPeers_NegativeFee_Fails(long? feeRatePpm, long? baseFeeMsat) + => ValidationHelper.ValidateReservedChannelOpenPeers([Reserved(Loop, feeRatePpm: feeRatePpm, baseFeeMsat: baseFeeMsat)], OwnNode) + .Should().Contain("can't be negative"); + + [Fact] + public void ValidateReservedChannelOpenPeers_SharesUpToAHundredPercent_Pass() + => ValidationHelper.ValidateReservedChannelOpenPeers([Reserved(Loop, 60), Reserved(Boltz, 40)], OwnNode) + .Should().BeNull(); + + [Fact] + public void ValidateReservedChannelOpenPeers_NoNodeChosen_Fails() + => ValidationHelper.ValidateReservedChannelOpenPeers([Reserved(0)], OwnNode) + .Should().Contain("Choose a node"); + + [Fact] + public void ValidateReservedChannelOpenPeers_TheNodeItself_Fails() + => ValidationHelper.ValidateReservedChannelOpenPeers([Reserved(OwnNode)], OwnNode) + .Should().Contain("itself"); + + [Theory] + [InlineData(0)] + [InlineData(101)] + public void ValidateReservedChannelOpenPeers_ShareOutOfRange_Fails(int pct) + => ValidationHelper.ValidateReservedChannelOpenPeers([Reserved(Loop, pct)], OwnNode) + .Should().Contain("between 1 and 100%"); + + [Fact] + public void ValidateReservedChannelOpenPeers_SharesAboveAHundredPercent_Fail() + => ValidationHelper.ValidateReservedChannelOpenPeers([Reserved(Loop, 60), Reserved(Boltz, 41)], OwnNode) + .Should().Contain("101%"); + + [Fact] + public void ValidateReservedChannelOpenPeers_SamePeerTwice_Fails() + => ValidationHelper.ValidateReservedChannelOpenPeers([Reserved(Loop, 10), Reserved(Loop, 10)], OwnNode) + .Should().Contain("more than once"); +