diff --git a/src/Automapper/MapperProfile.cs b/src/Automapper/MapperProfile.cs index 77680116d..1fa42fa02 100644 --- a/src/Automapper/MapperProfile.cs +++ b/src/Automapper/MapperProfile.cs @@ -41,6 +41,8 @@ public MapperProfile() .ForMember(x => x.ChannelOperationRequestsAsDestination, opt => opt.Ignore()) .ForMember(x => x.ChannelOperationRequestsAsSource, opt => opt.Ignore()) .ForMember(x => x.FundsDestinationWallet, opt => opt.Ignore()) + .ForMember(x => x.AutoChannelOpenWallet, opt => opt.Ignore()) + .ForMember(x => x.ChannelOpenRecommendations, opt => opt.Ignore()) .ForMember(x => x.Users, opt => opt.Ignore()); CreateMap() diff --git a/src/Data/ApplicationDbContext.cs b/src/Data/ApplicationDbContext.cs index ef3189dd2..c70e62fb8 100644 --- a/src/Data/ApplicationDbContext.cs +++ b/src/Data/ApplicationDbContext.cs @@ -168,6 +168,23 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity() .HasIndex(x => new { x.SeedFingerprint, x.Account }).IsUnique(); + modelBuilder.Entity() + .HasOne(x => x.Node) + .WithMany(x => x.ChannelOpenRecommendations) + .HasForeignKey(x => x.NodeId) + .OnDelete(DeleteBehavior.Cascade); + + modelBuilder.Entity() + .HasOne(x => x.ChannelOperationRequest) + .WithMany() + .HasForeignKey(x => x.ChannelOperationRequestId) + .OnDelete(DeleteBehavior.SetNull); + + // One recommendation per peer per node — the job upserts on this. Keyed by peer rather + // than channel because non-strict forwarding splits one signal across a peer's channels. + modelBuilder.Entity() + .HasIndex(x => new { x.NodeId, x.PeerPubKey }).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); @@ -220,5 +237,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) public DbSet ChannelFeeStates { get; set; } public DbSet SparkSignerIdentities { get; set; } + + public DbSet ChannelOpenRecommendations { get; set; } } } diff --git a/src/Data/Models/AuditLog.cs b/src/Data/Models/AuditLog.cs index f5f01a864..f17e364dd 100644 --- a/src/Data/Models/AuditLog.cs +++ b/src/Data/Models/AuditLog.cs @@ -205,5 +205,6 @@ public enum AuditObjectType UTXO, InternalWallet, Session, - Rebalance + Rebalance, + ChannelOpenRecommendation } diff --git a/src/Data/Models/ChannelOpenRecommendation.cs b/src/Data/Models/ChannelOpenRecommendation.cs new file mode 100644 index 000000000..9d2e5864f --- /dev/null +++ b/src/Data/Models/ChannelOpenRecommendation.cs @@ -0,0 +1,101 @@ +/* + * 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; + +public enum AutoChannelOpenMode +{ + /// Write the recommendation and stop. A human promotes it. + Recommendation = 0, + + /// Write the recommendation and promote it at the node's fixed size, under budget. + Auto = 1 +} + +public enum ChannelOpenRecommendationStatus +{ + /// Awaiting a decision; refreshed in place while the peer still qualifies. + Open = 0, + + /// Turned into a . + Promoted = 1, + + /// Rejected by an operator; suppresses the peer for the cooldown. + Dismissed = 2, + + /// Not reproduced by the latest run. Re-opened in place if the peer qualifies again. + Expired = 3, + + /// Promoted, but the channel never opened — the request failed or was cancelled. Unlike a + /// dismissal this says nothing about the peer, so it leaves no cooldown behind. + Failed = 4 +} + +/// Kept distinct from : a request is a funding instruction +/// awaiting treasury, a recommendation is evidence an operator may promote or dismiss. +/// +/// One row per (, ) — keyed by peer, not channel. +/// +public class ChannelOpenRecommendation : Entity +{ + public int NodeId { get; set; } + public Node? Node { get; set; } + + [MaxLength(66)] + public string PeerPubKey { get; set; } = string.Empty; + + #region Evidence + /// Fees earned on settled forwards out to the peer over the lookback window. + public long EarnedFeeSats { get; set; } + + /// Settled volume out to the peer over the lookback window. Displayed, never gated on. + public long SettledOutSats { get; set; } + + /// Forwards refused for lack of outbound to the peer over the shortage window. + public int Refusals { get; set; } + + /// Usable outbound to the peer when the run saw it, reserve excluded. + public long UsableLocalSats { get; set; } + + /// Total capacity of our open channels to the peer. + public long PeerCapacitySats { get; set; } + + /// The node's fixed size at the time of the run. An operator may override it before promoting. + public long SuggestedCapacitySats { get; set; } + + /// The policy the channel opens at: the highest-rate one among our channels to the peer. + public long? InheritedFeeRatePpm { get; set; } + + public long? InheritedBaseFeeMsat { get; set; } + #endregion Evidence + + #region Lifecycle + public ChannelOpenRecommendationStatus Status { get; set; } + + public DateTimeOffset LastEvidenceAt { get; set; } + + public int? ChannelOperationRequestId { get; set; } + public ChannelOperationRequest? ChannelOperationRequest { get; set; } + + [MaxLength(512)] + public string? DismissReason { get; set; } + #endregion Lifecycle +} diff --git a/src/Data/Models/ChannelOperationRequest.cs b/src/Data/Models/ChannelOperationRequest.cs index 413e00bef..9e1114272 100644 --- a/src/Data/Models/ChannelOperationRequest.cs +++ b/src/Data/Models/ChannelOperationRequest.cs @@ -94,6 +94,12 @@ public decimal Amount public ChannelOperationRequestStatus Status { get; set; } + [NotMapped] + public bool IsFinalized => Status is ChannelOperationRequestStatus.OnChainConfirmed + or ChannelOperationRequestStatus.Cancelled + or ChannelOperationRequestStatus.Rejected + or ChannelOperationRequestStatus.Failed; + public OperationRequestType RequestType { get; set; } /// diff --git a/src/Data/Models/Node.cs b/src/Data/Models/Node.cs index 99f1abf5e..e3720d813 100644 --- a/src/Data/Models/Node.cs +++ b/src/Data/Models/Node.cs @@ -242,10 +242,37 @@ public class Node : Entity /// public double? MaxRebalanceCostToEarnRatio { get; set; } + /// + /// Gate for automatic channel opening. + /// + public bool AutoChannelOpenEnabled { get; set; } = false; + + public AutoChannelOpenMode AutoChannelOpenMode { get; set; } = AutoChannelOpenMode.Recommendation; + + /// + /// Wallet the opened channels are funded from. Without it no plan can be promoted. + /// + public int? AutoChannelOpenWalletId { get; set; } + + public Wallet? AutoChannelOpenWallet { get; set; } + + /// + /// Every automatic open uses this size; a wallet or budget that can't cover it skips the peer. + /// + public long? AutoChannelOpenSizeSats { get; set; } + + public long? AutoChannelOpenBudgetSats { get; set; } + + public TimeSpan? AutoChannelOpenBudgetRefreshInterval { get; set; } + + public DateTimeOffset? AutoChannelOpenBudgetStartDatetime { get; set; } + #endregion Routing Engine #region Relationships + public ICollection ChannelOpenRecommendations { get; set; } + public ICollection ChannelOperationRequestsAsSource { get; set; } public ICollection ChannelOperationRequestsAsDestination { get; set; } diff --git a/src/Data/Repositories/ChannelOpenRecommendationRepository.cs b/src/Data/Repositories/ChannelOpenRecommendationRepository.cs new file mode 100644 index 000000000..8b13b4edf --- /dev/null +++ b/src/Data/Repositories/ChannelOpenRecommendationRepository.cs @@ -0,0 +1,221 @@ +/* + * 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 ChannelOpenRecommendationRepository : IChannelOpenRecommendationRepository +{ + private readonly IDbContextFactory _dbContextFactory; + private readonly ILogger _logger; + + public ChannelOpenRecommendationRepository(IDbContextFactory dbContextFactory, + ILogger logger) + { + _dbContextFactory = dbContextFactory; + _logger = logger; + } + + public async Task GetById(int id) + { + await using var context = await _dbContextFactory.CreateDbContextAsync(); + + return await context.ChannelOpenRecommendations + .Include(x => x.Node) + .Include(x => x.ChannelOperationRequest) + .FirstOrDefaultAsync(x => x.Id == id); + } + + public async Task> GetOpenByNode(int nodeId) + { + await using var context = await _dbContextFactory.CreateDbContextAsync(); + + return await context.ChannelOpenRecommendations + .Where(x => x.NodeId == nodeId && x.Status == ChannelOpenRecommendationStatus.Open) + .OrderByDescending(x => x.EarnedFeeSats) + .ToListAsync(); + } + + public async Task<(ChannelOpenRecommendation? Persisted, string? Error)> Upsert(ChannelOpenRecommendation recommendation) + { + await using var context = await _dbContextFactory.CreateDbContextAsync(); + + try + { + var existing = await context.ChannelOpenRecommendations + .Include(x => x.ChannelOperationRequest) + .FirstOrDefaultAsync(x => x.NodeId == recommendation.NodeId + && x.PeerPubKey == recommendation.PeerPubKey); + + if (existing == null) + { + // Insert via FK only — never let the Node nav try to insert/attach a Node. + recommendation.Node = null; + recommendation.SetCreationDatetime(); + recommendation.SetUpdateDatetime(); + await context.ChannelOpenRecommendations.AddAsync(recommendation); + await context.SaveChangesAsync(); + + return (recommendation, null); + } + + // A plan only reaches this point for a peer already past its cooldown, so the one reason + // left to hold a row back is a promotion whose channel open has not resolved yet. + if (existing.Status == ChannelOpenRecommendationStatus.Promoted + && existing.ChannelOperationRequest is { IsFinalized: false }) + { + return (existing, null); + } + + CopyEvidence(from: recommendation, to: existing); + existing.Status = ChannelOpenRecommendationStatus.Open; + + // The row is being recycled, so the previous decision's trail would misrepresent it. The + // promotion itself survives on the request and in the audit log. + existing.ChannelOperationRequestId = null; + existing.ChannelOperationRequest = null; + existing.DismissReason = null; + existing.SetUpdateDatetime(); + await context.SaveChangesAsync(); + + return (existing, null); + } + catch (Exception e) + { + _logger.LogError(e, "Error upserting channel open recommendation for node {NodeId} peer {Peer}", + recommendation.NodeId, recommendation.PeerPubKey); + return (null, e.Message); + } + } + + /// + /// Identity, lifecycle and the promotion link belong to the stored row and are deliberately not + /// copied. + /// + private static void CopyEvidence(ChannelOpenRecommendation from, ChannelOpenRecommendation to) + { + to.EarnedFeeSats = from.EarnedFeeSats; + to.SettledOutSats = from.SettledOutSats; + to.Refusals = from.Refusals; + to.UsableLocalSats = from.UsableLocalSats; + to.PeerCapacitySats = from.PeerCapacitySats; + to.SuggestedCapacitySats = from.SuggestedCapacitySats; + to.InheritedFeeRatePpm = from.InheritedFeeRatePpm; + to.InheritedBaseFeeMsat = from.InheritedBaseFeeMsat; + to.LastEvidenceAt = from.LastEvidenceAt; + } + + public async Task<(bool, string?)> UpdateIfStatus(ChannelOpenRecommendation recommendation, + ChannelOpenRecommendationStatus expectedStatus) + { + await using var context = await _dbContextFactory.CreateDbContextAsync(); + + try + { + recommendation.SetUpdateDatetime(); + + // One statement: of two callers that both read the row in the expected status, only one matches. + var updated = await context.ChannelOpenRecommendations + .Where(x => x.Id == recommendation.Id && x.Status == expectedStatus) + .ExecuteUpdateAsync(setters => setters + .SetProperty(x => x.Status, recommendation.Status) + .SetProperty(x => x.ChannelOperationRequestId, recommendation.ChannelOperationRequestId) + .SetProperty(x => x.DismissReason, recommendation.DismissReason) + .SetProperty(x => x.UpdateDatetime, recommendation.UpdateDatetime)); + + return updated == 1 + ? (true, null) + : (false, $"Recommendation is no longer {expectedStatus}"); + } + catch (Exception e) + { + _logger.LogError(e, "Error updating channel open recommendation {Id}", recommendation.Id); + return (false, e.Message); + } + } + + public async Task ExpireOpen(int nodeId) + { + await using var context = await _dbContextFactory.CreateDbContextAsync(); + + return await context.ChannelOpenRecommendations + .Where(x => x.NodeId == nodeId + && x.Status == ChannelOpenRecommendationStatus.Open) + .ExecuteUpdateAsync(setters => setters + .SetProperty(x => x.Status, ChannelOpenRecommendationStatus.Expired) + .SetProperty(x => x.UpdateDatetime, DateTimeOffset.UtcNow)); + } + + public async Task FailUnrealizedPromotions(int nodeId) + { + await using var context = await _dbContextFactory.CreateDbContextAsync(); + + var unrealized = await context.ChannelOpenRecommendations + .Include(x => x.ChannelOperationRequest) + .Where(x => x.NodeId == nodeId + && x.Status == ChannelOpenRecommendationStatus.Promoted + && x.ChannelOperationRequest != null + && (x.ChannelOperationRequest.Status == ChannelOperationRequestStatus.Failed + || x.ChannelOperationRequest.Status == ChannelOperationRequestStatus.Cancelled + || x.ChannelOperationRequest.Status == ChannelOperationRequestStatus.Rejected)) + .ToListAsync(); + + if (unrealized.Count == 0) + { + return 0; + } + + var failed = 0; + foreach (var recommendation in unrealized) + { + // Rejected is an operator turning the peer down, so it becomes a dismissal dated now: the + // cooldown then runs from the rejection, however long after the promotion it came. + if (recommendation.ChannelOperationRequest!.Status == ChannelOperationRequestStatus.Rejected) + { + recommendation.Status = ChannelOpenRecommendationStatus.Dismissed; + recommendation.DismissReason = "Channel open request rejected"; + } + else + { + recommendation.Status = ChannelOpenRecommendationStatus.Failed; + failed++; + } + + recommendation.SetUpdateDatetime(); + } + + await context.SaveChangesAsync(); + + return failed; + } + + public async Task> GetLastDecisionByPeer(int nodeId) + { + await using var context = await _dbContextFactory.CreateDbContextAsync(); + + return await context.ChannelOpenRecommendations + .Where(x => x.NodeId == nodeId + && (x.Status == ChannelOpenRecommendationStatus.Promoted + || x.Status == ChannelOpenRecommendationStatus.Dismissed)) + .ToDictionaryAsync(x => x.PeerPubKey, x => x.UpdateDatetime); + } +} diff --git a/src/Data/Repositories/ChannelOperationRequestRepository.cs b/src/Data/Repositories/ChannelOperationRequestRepository.cs index 34744987b..ab81310d7 100644 --- a/src/Data/Repositories/ChannelOperationRequestRepository.cs +++ b/src/Data/Repositories/ChannelOperationRequestRepository.cs @@ -221,6 +221,20 @@ public async Task> GetUnsignedPendingRequestsByUse return result; } + public async Task GetOpenSatsCommittedSince(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) + .SumAsync(x => (long?)x.SatsAmount) ?? 0; + } + public async Task> GetPendingRequests() { await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); diff --git a/src/Data/Repositories/ForwardingHtlcEventRepository.cs b/src/Data/Repositories/ForwardingHtlcEventRepository.cs index 00a5d9230..e0997b842 100644 --- a/src/Data/Repositories/ForwardingHtlcEventRepository.cs +++ b/src/Data/Repositories/ForwardingHtlcEventRepository.cs @@ -106,6 +106,42 @@ public async Task GetOutgoingAmountMsat(string managedNodePubKey, ulong ch .SumAsync(x => (long?)x.OutgoingAmountMsat) ?? 0; } + public async Task> GetOutgoingAmountsMsatByChannel(string managedNodePubKey, DateTimeOffset since) + { + await using var context = await _dbContextFactory.CreateDbContextAsync(); + + return await Settled(context, managedNodePubKey, since) + .GroupBy(x => x.OutgoingChannelId) + .Select(g => new { ChanId = g.Key, Amount = g.Sum(x => (long?)x.OutgoingAmountMsat) ?? 0 }) + .ToDictionaryAsync(x => x.ChanId, x => x.Amount); + } + + public async Task> GetEarnedFeesMsatByChannel(string managedNodePubKey, DateTimeOffset since) + { + await using var context = await _dbContextFactory.CreateDbContextAsync(); + + return await Settled(context, managedNodePubKey, since) + .GroupBy(x => x.OutgoingChannelId) + .Select(g => new { ChanId = g.Key, Fee = g.Sum(x => x.FeeMsat) ?? 0 }) + .ToDictionaryAsync(x => x.ChanId, x => x.Fee); + } + + public async Task> GetInsufficientBalanceCountsByChannel(string managedNodePubKey, DateTimeOffset since) + { + await using var context = await _dbContextFactory.CreateDbContextAsync(); + + return await context.ForwardingHtlcEvents + .Where(x => x.ManagedNodePubKey == managedNodePubKey + && x.EventTimestamp >= since + && x.EventType == HtlcEventType.Forward + && x.EventCase == HtlcEventCase.LinkFailEvent + // The only failure a channel open can fix. HTLC_EXCEEDS_MAX is our own ceiling. + && x.FailureDetail == (int)Routerrpc.FailureDetail.InsufficientBalance) + .GroupBy(x => x.OutgoingChannelId) + .Select(g => new { ChanId = g.Key, Count = g.Count() }) + .ToDictionaryAsync(x => x.ChanId, x => x.Count); + } + public async Task GetIncomingAmountMsat(string managedNodePubKey, ulong chanIdLnd, DateTimeOffset since) { await using var context = await _dbContextFactory.CreateDbContextAsync(); diff --git a/src/Data/Repositories/Interfaces/IChannelOpenRecommendationRepository.cs b/src/Data/Repositories/Interfaces/IChannelOpenRecommendationRepository.cs new file mode 100644 index 000000000..ccc708849 --- /dev/null +++ b/src/Data/Repositories/Interfaces/IChannelOpenRecommendationRepository.cs @@ -0,0 +1,62 @@ +/* + * 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 IChannelOpenRecommendationRepository +{ + Task GetById(int id); + + Task> GetOpenByNode(int nodeId); + + /// + /// A promotion whose channel open is still unresolved is left untouched; every other row is + /// recycled into a fresh Open one. The returned row's status tells the caller which case it hit. + /// + Task<(ChannelOpenRecommendation? Persisted, string? Error)> Upsert(ChannelOpenRecommendation recommendation); + + /// + /// Writes the row's lifecycle fields only while it is still in , + /// so a caller acting on a stale read is refused instead of overwriting a newer decision. + /// + Task<(bool, string?)> UpdateIfStatus(ChannelOpenRecommendation recommendation, + ChannelOpenRecommendationStatus expectedStatus); + + /// + /// Runs first each cycle; the upsert re-opens what still qualifies, so the panel is always the + /// latest run's output. + /// + Task ExpireOpen(int nodeId); + + /// + /// Flips a Promoted row whose channel never opened to Failed. The promotion was a + /// decision to fund the peer, not a verdict on it, so once it comes to nothing it must stop + /// feeding — hence this runs ahead of it every cycle. + /// A rejected request is the exception: its row turns Dismissed, so the peer's cooldown + /// restarts at the rejection. Returns only the rows marked Failed. + /// + Task FailUnrealizedPromotions(int nodeId); + + /// + /// Feeds the per-peer cooldown, which is what stops a drained sink peer being re-proposed every run. + /// + Task> GetLastDecisionByPeer(int nodeId); +} diff --git a/src/Data/Repositories/Interfaces/IChannelOperationRequestRepository.cs b/src/Data/Repositories/Interfaces/IChannelOperationRequestRepository.cs index 56dbcb641..bffb03780 100644 --- a/src/Data/Repositories/Interfaces/IChannelOperationRequestRepository.cs +++ b/src/Data/Repositories/Interfaces/IChannelOperationRequestRepository.cs @@ -45,6 +45,12 @@ public interface IChannelOperationRequestRepository : IBitcoinRequestRepository /// Task> GetPendingRequests(); + /// + /// Sats committed to channel opens for this source node since the given time. Cancelled, rejected + /// and failed requests never spent anything, so they are excluded. + /// + Task GetOpenSatsCommittedSince(int sourceNodeId, DateTimeOffset since); + Task<(List requests, int totalCount)> GetPaginatedAsync( int pageNumber, int pageSize, diff --git a/src/Data/Repositories/Interfaces/IForwardingHtlcEventRepository.cs b/src/Data/Repositories/Interfaces/IForwardingHtlcEventRepository.cs index 5ae2dd8e4..f9e3a08d4 100644 --- a/src/Data/Repositories/Interfaces/IForwardingHtlcEventRepository.cs +++ b/src/Data/Repositories/Interfaces/IForwardingHtlcEventRepository.cs @@ -31,6 +31,22 @@ public interface IForwardingHtlcEventRepository /// Task GetOutgoingAmountMsat(string managedNodePubKey, ulong chanIdLnd, DateTimeOffset since); + /// + /// Same as but for every channel at once, keyed by scid. + /// + Task> GetOutgoingAmountsMsatByChannel(string managedNodePubKey, DateTimeOffset since); + + /// + /// Σ FeeMsat of succeeded forwards, keyed by outgoing scid: what each channel earned us. + /// + Task> GetEarnedFeesMsatByChannel(string managedNodePubKey, DateTimeOffset since); + + /// + /// Forwards refused for lack of local outbound (LinkFail / INSUFFICIENT_BALANCE), counted per + /// outgoing scid. Raw rows, so sender retries are counted too. + /// + Task> GetInsufficientBalanceCountsByChannel(string managedNodePubKey, DateTimeOffset since); + /// /// Σ IncomingAmountMsat of succeeded forwards where IncomingChannelId == chanIdLnd, for the /// given managed node, since the window start (fills our local balance — "pull"). diff --git a/src/Data/Repositories/Interfaces/INodeRepository.cs b/src/Data/Repositories/Interfaces/INodeRepository.cs index 60cb63517..c61e1d40b 100644 --- a/src/Data/Repositories/Interfaces/INodeRepository.cs +++ b/src/Data/Repositories/Interfaces/INodeRepository.cs @@ -52,6 +52,12 @@ public interface INodeRepository /// A list of nodes with auto liquidity management enabled Task> GetAllWithAutoLiquidityEnabled(); + /// + /// Nodes eligible for automatic channel opening: enabled, not disabled, and with a funding + /// wallet set. Without a wallet nothing could be promoted anyway. + /// + Task> GetAllWithAutoChannelOpenEnabled(); + Task<(bool, string?)> AddAsync(Node type); Task<(bool, string?)> AddRangeAsync(List type); diff --git a/src/Data/Repositories/NodeRepository.cs b/src/Data/Repositories/NodeRepository.cs index 6fdc36a13..1b8488acd 100644 --- a/src/Data/Repositories/NodeRepository.cs +++ b/src/Data/Repositories/NodeRepository.cs @@ -194,6 +194,19 @@ public async Task> GetAllWithAutoLiquidityEnabled() .ToListAsync(); } + public async Task> GetAllWithAutoChannelOpenEnabled() + { + await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); + + return await applicationDbContext.Nodes + .Include(x => x.AutoChannelOpenWallet) + .ThenInclude(x => x!.Keys) + .Where(node => !node.IsNodeDisabled && + node.AutoChannelOpenEnabled && + node.AutoChannelOpenWalletId.HasValue) + .ToListAsync(); + } + public async Task<(bool, string?)> AddAsync(Node type) { await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync(); diff --git a/src/Helpers/Constants.cs b/src/Helpers/Constants.cs index 68fa2753c..83879495e 100644 --- a/src/Helpers/Constants.cs +++ b/src/Helpers/Constants.cs @@ -404,6 +404,37 @@ public class Constants public static readonly string CAROL_LOOPD_MACAROON = string.Empty; public static readonly string CAROL_LOOPD_TLS_CERT = string.Empty; + #region Auto Channel Open + + // Master switch for automatic channel opening. Per-node gates still apply. + public static bool AUTO_CHANNEL_OPEN_ENABLED = false; + + // "The route worked": fees earned to the peer over this many days must reach the minimum below. + public static int AUTO_CHANNEL_OPEN_LOOKBACK_DAYS = 7; + + public static long AUTO_CHANNEL_OPEN_MIN_EARNED_FEE_SATS = 50_000; + + // "We're short": forwards refused for lack of outbound to the peer over this many hours. + public static int AUTO_CHANNEL_OPEN_SHORTAGE_HOURS = 6; + + public static int AUTO_CHANNEL_OPEN_MIN_REFUSALS = 5; + + // "Still short now": usable outbound to the peer below this % of our capacity to it. + public static int AUTO_CHANNEL_OPEN_LOW_OUTBOUND_PCT = 20; + + // Per-peer suppression after an open attempt or a dismissal. + public static int AUTO_CHANNEL_OPEN_PEER_COOLDOWN_HOURS = 6; + + // Plans per node per run. In Auto mode this is also the concurrency bound: nothing else caps opens in flight. + public static int AUTO_CHANNEL_OPEN_MAX_PLANS_PER_RUN = 5; + + public static int AUTO_CHANNEL_OPEN_DEFAULT_BUDGET_REFRESH_HOURS = 720; + + // In dev this is 1 minute. + public static int AUTO_CHANNEL_OPEN_JOB_INTERVAL_MINUTES = 30; + + #endregion Auto Channel Open + private static string? GetEnvironmentalVariableOrThrowIfNotTesting(string envVariableName, string? errorMessage = null) { @@ -752,6 +783,37 @@ static Constants() CAROL_LOOPD_HOST = Environment.GetEnvironmentVariable("CAROL_LOOPD_HOST") ?? CAROL_LOOPD_HOST; CAROL_LOOPD_MACAROON = Environment.GetEnvironmentVariable("CAROL_LOOPD_MACAROON") ?? CAROL_LOOPD_MACAROON; CAROL_LOOPD_TLS_CERT = Environment.GetEnvironmentVariable("CAROL_LOOPD_TLS_CERT") ?? CAROL_LOOPD_TLS_CERT; + + // Auto Channel Open + AUTO_CHANNEL_OPEN_ENABLED = StringHelper.IsTrue(Environment.GetEnvironmentVariable("AUTO_CHANNEL_OPEN_ENABLED")); + + var acoLookbackDays = Environment.GetEnvironmentVariable("AUTO_CHANNEL_OPEN_LOOKBACK_DAYS"); + if (acoLookbackDays != null) AUTO_CHANNEL_OPEN_LOOKBACK_DAYS = int.Parse(acoLookbackDays); + + var acoMinEarnedFee = Environment.GetEnvironmentVariable("AUTO_CHANNEL_OPEN_MIN_EARNED_FEE_SATS"); + if (acoMinEarnedFee != null) AUTO_CHANNEL_OPEN_MIN_EARNED_FEE_SATS = long.Parse(acoMinEarnedFee); + + var acoShortageHours = Environment.GetEnvironmentVariable("AUTO_CHANNEL_OPEN_SHORTAGE_HOURS"); + if (acoShortageHours != null) AUTO_CHANNEL_OPEN_SHORTAGE_HOURS = int.Parse(acoShortageHours); + + var acoMinRefusals = Environment.GetEnvironmentVariable("AUTO_CHANNEL_OPEN_MIN_REFUSALS"); + if (acoMinRefusals != null) AUTO_CHANNEL_OPEN_MIN_REFUSALS = int.Parse(acoMinRefusals); + + var acoLowOutboundPct = Environment.GetEnvironmentVariable("AUTO_CHANNEL_OPEN_LOW_OUTBOUND_PCT"); + if (acoLowOutboundPct != null) AUTO_CHANNEL_OPEN_LOW_OUTBOUND_PCT = int.Parse(acoLowOutboundPct); + + var acoCooldown = Environment.GetEnvironmentVariable("AUTO_CHANNEL_OPEN_PEER_COOLDOWN_HOURS"); + if (acoCooldown != null) AUTO_CHANNEL_OPEN_PEER_COOLDOWN_HOURS = int.Parse(acoCooldown); + + var acoMaxPlans = Environment.GetEnvironmentVariable("AUTO_CHANNEL_OPEN_MAX_PLANS_PER_RUN"); + if (acoMaxPlans != null) AUTO_CHANNEL_OPEN_MAX_PLANS_PER_RUN = int.Parse(acoMaxPlans); + + var acoDefaultRefreshHours = Environment.GetEnvironmentVariable("AUTO_CHANNEL_OPEN_DEFAULT_BUDGET_REFRESH_HOURS"); + if (acoDefaultRefreshHours != null) AUTO_CHANNEL_OPEN_DEFAULT_BUDGET_REFRESH_HOURS = int.Parse(acoDefaultRefreshHours); + + var acoInterval = Environment.GetEnvironmentVariable("AUTO_CHANNEL_OPEN_JOB_INTERVAL_MINUTES"); + if (acoInterval != null) AUTO_CHANNEL_OPEN_JOB_INTERVAL_MINUTES = int.Parse(acoInterval); + if (IS_DEV_ENVIRONMENT) AUTO_CHANNEL_OPEN_JOB_INTERVAL_MINUTES = 1; } } diff --git a/src/Migrations/20261029165151_AddAutoChannelOpen.Designer.cs b/src/Migrations/20261029165151_AddAutoChannelOpen.Designer.cs new file mode 100644 index 000000000..703165913 --- /dev/null +++ b/src/Migrations/20261029165151_AddAutoChannelOpen.Designer.cs @@ -0,0 +1,2148 @@ +// +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("20261029165151_AddAutoChannelOpen")] + partial class AddAutoChannelOpen + { + /// + 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("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.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.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("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/20261029165151_AddAutoChannelOpen.cs b/src/Migrations/20261029165151_AddAutoChannelOpen.cs new file mode 100644 index 000000000..f7906715b --- /dev/null +++ b/src/Migrations/20261029165151_AddAutoChannelOpen.cs @@ -0,0 +1,166 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace NodeGuard.Migrations +{ + /// + public partial class AddAutoChannelOpen : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "AutoChannelOpenBudgetRefreshInterval", + table: "Nodes", + type: "interval", + nullable: true); + + migrationBuilder.AddColumn( + name: "AutoChannelOpenBudgetSats", + table: "Nodes", + type: "bigint", + nullable: true); + + migrationBuilder.AddColumn( + name: "AutoChannelOpenBudgetStartDatetime", + table: "Nodes", + type: "timestamp with time zone", + nullable: true); + + migrationBuilder.AddColumn( + name: "AutoChannelOpenEnabled", + table: "Nodes", + type: "boolean", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "AutoChannelOpenMode", + table: "Nodes", + type: "integer", + nullable: false, + defaultValue: 0); + + migrationBuilder.AddColumn( + name: "AutoChannelOpenSizeSats", + table: "Nodes", + type: "bigint", + nullable: true); + + migrationBuilder.AddColumn( + name: "AutoChannelOpenWalletId", + table: "Nodes", + type: "integer", + nullable: true); + + migrationBuilder.CreateTable( + name: "ChannelOpenRecommendations", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + NodeId = table.Column(type: "integer", nullable: false), + PeerPubKey = table.Column(type: "character varying(66)", maxLength: 66, nullable: false), + EarnedFeeSats = table.Column(type: "bigint", nullable: false), + SettledOutSats = table.Column(type: "bigint", nullable: false), + Refusals = table.Column(type: "integer", nullable: false), + UsableLocalSats = table.Column(type: "bigint", nullable: false), + PeerCapacitySats = table.Column(type: "bigint", nullable: false), + SuggestedCapacitySats = table.Column(type: "bigint", nullable: false), + InheritedFeeRatePpm = table.Column(type: "bigint", nullable: true), + InheritedBaseFeeMsat = table.Column(type: "bigint", nullable: true), + Status = table.Column(type: "integer", nullable: false), + LastEvidenceAt = table.Column(type: "timestamp with time zone", nullable: false), + ChannelOperationRequestId = table.Column(type: "integer", nullable: true), + DismissReason = table.Column(type: "character varying(512)", maxLength: 512, nullable: true), + 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_ChannelOpenRecommendations", x => x.Id); + table.ForeignKey( + name: "FK_ChannelOpenRecommendations_ChannelOperationRequests_Channel~", + column: x => x.ChannelOperationRequestId, + principalTable: "ChannelOperationRequests", + principalColumn: "Id", + onDelete: ReferentialAction.SetNull); + table.ForeignKey( + name: "FK_ChannelOpenRecommendations_Nodes_NodeId", + column: x => x.NodeId, + principalTable: "Nodes", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Nodes_AutoChannelOpenWalletId", + table: "Nodes", + column: "AutoChannelOpenWalletId"); + + migrationBuilder.CreateIndex( + name: "IX_ChannelOpenRecommendations_ChannelOperationRequestId", + table: "ChannelOpenRecommendations", + column: "ChannelOperationRequestId"); + + migrationBuilder.CreateIndex( + name: "IX_ChannelOpenRecommendations_NodeId_PeerPubKey", + table: "ChannelOpenRecommendations", + columns: new[] { "NodeId", "PeerPubKey" }, + unique: true); + + migrationBuilder.AddForeignKey( + name: "FK_Nodes_Wallets_AutoChannelOpenWalletId", + table: "Nodes", + column: "AutoChannelOpenWalletId", + principalTable: "Wallets", + principalColumn: "Id"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_Nodes_Wallets_AutoChannelOpenWalletId", + table: "Nodes"); + + migrationBuilder.DropTable( + name: "ChannelOpenRecommendations"); + + migrationBuilder.DropIndex( + name: "IX_Nodes_AutoChannelOpenWalletId", + table: "Nodes"); + + migrationBuilder.DropColumn( + name: "AutoChannelOpenBudgetRefreshInterval", + table: "Nodes"); + + migrationBuilder.DropColumn( + name: "AutoChannelOpenBudgetSats", + table: "Nodes"); + + migrationBuilder.DropColumn( + name: "AutoChannelOpenBudgetStartDatetime", + table: "Nodes"); + + migrationBuilder.DropColumn( + name: "AutoChannelOpenEnabled", + table: "Nodes"); + + migrationBuilder.DropColumn( + name: "AutoChannelOpenMode", + table: "Nodes"); + + migrationBuilder.DropColumn( + name: "AutoChannelOpenSizeSats", + table: "Nodes"); + + migrationBuilder.DropColumn( + name: "AutoChannelOpenWalletId", + table: "Nodes"); + } + } +} diff --git a/src/Migrations/ApplicationDbContextModelSnapshot.cs b/src/Migrations/ApplicationDbContextModelSnapshot.cs index 5ea136e16..705db302b 100644 --- a/src/Migrations/ApplicationDbContextModelSnapshot.cs +++ b/src/Migrations/ApplicationDbContextModelSnapshot.cs @@ -496,6 +496,75 @@ protected override void BuildModel(ModelBuilder modelBuilder) 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("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") @@ -984,6 +1053,27 @@ protected override void BuildModel(ModelBuilder modelBuilder) 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"); @@ -1122,6 +1212,8 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasKey("Id"); + b.HasIndex("AutoChannelOpenWalletId"); + b.HasIndex("FundsDestinationWalletId"); b.HasIndex("PubKey") @@ -1777,6 +1869,24 @@ protected override void BuildModel(ModelBuilder modelBuilder) 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") @@ -1890,6 +2000,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) 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"); @@ -1899,6 +2013,8 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasForeignKey("SparkWalletId") .OnDelete(DeleteBehavior.Restrict); + b.Navigation("AutoChannelOpenWallet"); + b.Navigation("FundsDestinationWallet"); }); @@ -2021,6 +2137,8 @@ protected override void BuildModel(ModelBuilder modelBuilder) modelBuilder.Entity("NodeGuard.Data.Models.Node", b => { + b.Navigation("ChannelOpenRecommendations"); + b.Navigation("ChannelOperationRequestsAsDestination"); b.Navigation("ChannelOperationRequestsAsSource"); diff --git a/test/NodeGuard.Tests/Data/Models/ChannelOperationRequestTests.cs b/test/NodeGuard.Tests/Data/Models/ChannelOperationRequestTests.cs index ac2bf2349..edae1a717 100644 --- a/test/NodeGuard.Tests/Data/Models/ChannelOperationRequestTests.cs +++ b/test/NodeGuard.Tests/Data/Models/ChannelOperationRequestTests.cs @@ -66,4 +66,31 @@ public void GetSingleTemplatePsbt_TwoTemplates_Throws() .Should().Throw() .WithMessage("*704*more than one template*"); } + + /// + /// Exhaustive on purpose. The channel-open upsert refuses to re-propose a peer while its request + /// is unfinalized, so a status added without a verdict here would silently pick one. + /// + [Theory] + [InlineData(ChannelOperationRequestStatus.OnChainConfirmed, true)] + [InlineData(ChannelOperationRequestStatus.Cancelled, true)] + [InlineData(ChannelOperationRequestStatus.Rejected, true)] + [InlineData(ChannelOperationRequestStatus.Failed, true)] + [InlineData(ChannelOperationRequestStatus.Approved, false)] + [InlineData(ChannelOperationRequestStatus.Pending, false)] + [InlineData(ChannelOperationRequestStatus.PSBTSignaturesPending, false)] + [InlineData(ChannelOperationRequestStatus.OnChainConfirmationPending, false)] + [InlineData(ChannelOperationRequestStatus.FinalizingPSBT, false)] + public void IsFinalized_IsTrueOnlyWhenTheRequestCanNoLongerBecomeAChannel( + ChannelOperationRequestStatus status, bool expected) + { + new ChannelOperationRequest { Status = status }.IsFinalized.Should().Be(expected); + } + + [Fact] + public void IsFinalized_CoversEveryDeclaredStatus() + { + // Guards the theory above: a new status must be given a verdict rather than inherit one. + Enum.GetValues().Should().HaveCount(9); + } } diff --git a/test/NodeGuard.Tests/Data/Repositories/ChannelOpenRecommendationRepositoryTests.cs b/test/NodeGuard.Tests/Data/Repositories/ChannelOpenRecommendationRepositoryTests.cs new file mode 100644 index 000000000..f82cad1bf --- /dev/null +++ b/test/NodeGuard.Tests/Data/Repositories/ChannelOpenRecommendationRepositoryTests.cs @@ -0,0 +1,392 @@ +/* + * 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; + +/// +/// The upsert owns when a peer may be proposed again, so these cover the recycling rules rather +/// than the persistence mechanics. +/// +public class ChannelOpenRecommendationRepositoryTests +{ + private readonly Random _random = new(); + private const int NodeId = 1; + private const string Peer = "03aaa"; + + private (ChannelOpenRecommendationRepository sut, ApplicationDbContext seed) SetupDb() + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: "ChannelOpenRec" + _random.Next()) + .Options; + + var factory = new Mock>(); + factory.Setup(x => x.CreateDbContext()).Returns(() => new ApplicationDbContext(options)); + factory.Setup(x => x.CreateDbContextAsync(default)).ReturnsAsync(() => new ApplicationDbContext(options)); + + var logger = new Mock>(); + + return (new ChannelOpenRecommendationRepository(factory.Object, logger.Object), new ApplicationDbContext(options)); + } + + private static ChannelOpenRecommendation Stored( + ChannelOpenRecommendationStatus status, + int? requestId = null, + string? dismissReason = null) + => new() + { + NodeId = NodeId, + PeerPubKey = Peer, + SuggestedCapacitySats = 1_000_000, + Status = status, + ChannelOperationRequestId = requestId, + DismissReason = dismissReason, + LastEvidenceAt = DateTimeOffset.UtcNow.AddHours(-2) + }; + + /// A freshly planned row for the same peer, distinguishable by its capacity. + private static ChannelOpenRecommendation Plan() + => new() + { + NodeId = NodeId, + PeerPubKey = Peer, + SuggestedCapacitySats = 4_000_000, + Refusals = 7, + Status = ChannelOpenRecommendationStatus.Open, + LastEvidenceAt = DateTimeOffset.UtcNow + }; + + [Fact] + public async Task Upsert_ExpiredRow_IsReopenedWithTheNewEvidence() + { + var (sut, seed) = SetupDb(); + seed.ChannelOpenRecommendations.Add(Stored(ChannelOpenRecommendationStatus.Expired)); + await seed.SaveChangesAsync(); + + var (persisted, error) = await sut.Upsert(Plan()); + + error.Should().BeNull(); + persisted!.Status.Should().Be(ChannelOpenRecommendationStatus.Open); + persisted.SuggestedCapacitySats.Should().Be(4_000_000); + persisted.Refusals.Should().Be(7); + } + + [Fact] + public async Task Upsert_DismissedRow_IsRecycledAndTheReasonCleared() + { + var (sut, seed) = SetupDb(); + seed.ChannelOpenRecommendations.Add( + Stored(ChannelOpenRecommendationStatus.Dismissed, dismissReason: "not now")); + await seed.SaveChangesAsync(); + + // Only a peer already past its cooldown reaches the upsert, so a dismissal is a suppression + // and not a permanent exclusion. + var (persisted, error) = await sut.Upsert(Plan()); + + error.Should().BeNull(); + persisted!.Status.Should().Be(ChannelOpenRecommendationStatus.Open); + persisted.DismissReason.Should().BeNull(); + persisted.SuggestedCapacitySats.Should().Be(4_000_000); + } + + [Fact] + public async Task Upsert_FailedRow_IsRecycledAndTheLinkCleared() + { + var (sut, seed) = SetupDb(); + seed.ChannelOpenRecommendations.Add( + Stored(ChannelOpenRecommendationStatus.Failed, requestId: 55)); + await seed.SaveChangesAsync(); + + var (persisted, error) = await sut.Upsert(Plan()); + + // The peer never got the channel and carries no cooldown, so the next run that still sees the + // demand must be able to propose it again. + error.Should().BeNull(); + persisted!.Status.Should().Be(ChannelOpenRecommendationStatus.Open); + persisted.SuggestedCapacitySats.Should().Be(4_000_000); + persisted.ChannelOperationRequestId.Should().BeNull(); + } + + [Fact] + public async Task Upsert_PromotedRowWhoseOpenIsStillUnresolved_IsLeftUntouched() + { + var (sut, seed) = SetupDb(); + seed.ChannelOperationRequests.Add(new ChannelOperationRequest + { + Id = 55, + RequestType = OperationRequestType.Open, + Status = ChannelOperationRequestStatus.Pending + }); + seed.ChannelOpenRecommendations.Add(Stored(ChannelOpenRecommendationStatus.Promoted, requestId: 55)); + await seed.SaveChangesAsync(); + + var (persisted, error) = await sut.Upsert(Plan()); + + error.Should().BeNull(); + persisted!.Status.Should().Be(ChannelOpenRecommendationStatus.Promoted); + persisted.SuggestedCapacitySats.Should().Be(1_000_000); + persisted.ChannelOperationRequestId.Should().Be(55); + } + + [Theory] + [InlineData(ChannelOperationRequestStatus.OnChainConfirmed)] + [InlineData(ChannelOperationRequestStatus.Failed)] + [InlineData(ChannelOperationRequestStatus.Cancelled)] + [InlineData(ChannelOperationRequestStatus.Rejected)] + public async Task Upsert_PromotedRowWhoseOpenResolved_IsRecycledAndTheLinkCleared( + ChannelOperationRequestStatus resolved) + { + var (sut, seed) = SetupDb(); + seed.ChannelOperationRequests.Add(new ChannelOperationRequest + { + Id = 55, + RequestType = OperationRequestType.Open, + Status = resolved + }); + seed.ChannelOpenRecommendations.Add(Stored(ChannelOpenRecommendationStatus.Promoted, requestId: 55)); + await seed.SaveChangesAsync(); + + var (persisted, error) = await sut.Upsert(Plan()); + + error.Should().BeNull(); + persisted!.Status.Should().Be(ChannelOpenRecommendationStatus.Open); + persisted.SuggestedCapacitySats.Should().Be(4_000_000); + persisted.ChannelOperationRequestId.Should().BeNull(); + } + + [Fact] + public async Task Upsert_NoRowForThePeer_Inserts() + { + var (sut, _) = SetupDb(); + + var (persisted, error) = await sut.Upsert(Plan()); + + error.Should().BeNull(); + persisted!.Status.Should().Be(ChannelOpenRecommendationStatus.Open); + persisted.PeerPubKey.Should().Be(Peer); + } + + /// A stored row for an arbitrary node and peer, for the queries that span several of both. + private static ChannelOpenRecommendation Row( + int nodeId, string peer, ChannelOpenRecommendationStatus status, + long earnedFeeSats = 0, DateTimeOffset? updatedAt = null) + => new() + { + NodeId = nodeId, + PeerPubKey = peer, + Status = status, + EarnedFeeSats = earnedFeeSats, + SuggestedCapacitySats = 1_000_000, + UpdateDatetime = updatedAt ?? DateTimeOffset.UtcNow, + LastEvidenceAt = DateTimeOffset.UtcNow + }; + + [Fact] + public async Task GetOpenByNode_ReturnsOnlyThatNodesOpenRows_RichestFirst() + { + var (sut, seed) = SetupDb(); + seed.ChannelOpenRecommendations.AddRange( + Row(NodeId, "03low", ChannelOpenRecommendationStatus.Open, earnedFeeSats: 10), + Row(NodeId, "03high", ChannelOpenRecommendationStatus.Open, earnedFeeSats: 900), + Row(NodeId, "03mid", ChannelOpenRecommendationStatus.Open, earnedFeeSats: 300), + Row(NodeId, "03promoted", ChannelOpenRecommendationStatus.Promoted, earnedFeeSats: 5000), + Row(NodeId, "03dismissed", ChannelOpenRecommendationStatus.Dismissed, earnedFeeSats: 5000), + Row(NodeId, "03expired", ChannelOpenRecommendationStatus.Expired, earnedFeeSats: 5000), + Row(2, "03otherNode", ChannelOpenRecommendationStatus.Open, earnedFeeSats: 5000)); + await seed.SaveChangesAsync(); + + var result = await sut.GetOpenByNode(NodeId); + + // A limited budget is spent down this list, so the ordering decides which peer gets funded. + result.Select(x => x.PeerPubKey).Should().Equal("03high", "03mid", "03low"); + } + + [Fact] + public async Task GetOpenByNode_NoOpenRows_ReturnsEmpty() + { + var (sut, seed) = SetupDb(); + seed.ChannelOpenRecommendations.Add(Stored(ChannelOpenRecommendationStatus.Promoted)); + await seed.SaveChangesAsync(); + + var result = await sut.GetOpenByNode(NodeId); + + result.Should().BeEmpty(); + } + + [Fact] + public async Task GetLastDecisionByPeer_ReturnsEachPeersDecisionTimeForThatNodeOnly() + { + var (sut, seed) = SetupDb(); + var now = DateTimeOffset.UtcNow; + + seed.ChannelOpenRecommendations.AddRange( + Row(NodeId, "03a", ChannelOpenRecommendationStatus.Dismissed, updatedAt: now.AddDays(-1)), + Row(NodeId, "03b", ChannelOpenRecommendationStatus.Promoted, updatedAt: now.AddDays(-4)), + Row(2, "03c", ChannelOpenRecommendationStatus.Promoted, updatedAt: now)); + await seed.SaveChangesAsync(); + + var result = await sut.GetLastDecisionByPeer(NodeId); + + result.Should().BeEquivalentTo(new Dictionary + { + ["03a"] = now.AddDays(-1), + ["03b"] = now.AddDays(-4), + }); + } + + [Fact] + public async Task GetLastDecisionByPeer_IgnoresOpenAndExpiredRows() + { + var (sut, seed) = SetupDb(); + seed.ChannelOpenRecommendations.AddRange( + Row(NodeId, "03open", ChannelOpenRecommendationStatus.Open), + Row(NodeId, "03expired", ChannelOpenRecommendationStatus.Expired)); + await seed.SaveChangesAsync(); + + var result = await sut.GetLastDecisionByPeer(NodeId); + + // Neither is an operator decision. An expired row counting here would put its peer in a + // cooldown nobody asked for, and the demand would stay unproposed for the whole window. + result.Should().BeEmpty(); + } + + [Fact] + public async Task GetLastDecisionByPeer_IgnoresFailedRows() + { + var (sut, seed) = SetupDb(); + seed.ChannelOpenRecommendations.Add(Row(NodeId, Peer, ChannelOpenRecommendationStatus.Failed)); + await seed.SaveChangesAsync(); + + var result = await sut.GetLastDecisionByPeer(NodeId); + + // The whole point of the status: a promotion that produced no channel must not suppress the + // peer, or the demand behind it goes unserved for the length of the cooldown. + result.Should().BeEmpty(); + } + + [Theory] + [InlineData(ChannelOperationRequestStatus.Failed)] + [InlineData(ChannelOperationRequestStatus.Cancelled)] + public async Task FailUnrealizedPromotions_PromotedRowWhoseChannelNeverOpened_IsMarkedFailed( + ChannelOperationRequestStatus unrealized) + { + var (sut, seed) = SetupDb(); + seed.ChannelOperationRequests.Add(new ChannelOperationRequest + { + Id = 55, + RequestType = OperationRequestType.Open, + Status = unrealized + }); + seed.ChannelOpenRecommendations.Add(Stored(ChannelOpenRecommendationStatus.Promoted, requestId: 55)); + await seed.SaveChangesAsync(); + + var count = await sut.FailUnrealizedPromotions(NodeId); + + count.Should().Be(1); + var stored = await seed.ChannelOpenRecommendations.AsNoTracking().SingleAsync(); + stored.Status.Should().Be(ChannelOpenRecommendationStatus.Failed); + } + + [Theory] + [InlineData(ChannelOperationRequestStatus.Pending)] + [InlineData(ChannelOperationRequestStatus.OnChainConfirmationPending)] + [InlineData(ChannelOperationRequestStatus.OnChainConfirmed)] + public async Task FailUnrealizedPromotions_PromotedRowWhoseOpenIsLiveOrDone_StaysPromoted( + ChannelOperationRequestStatus kept) + { + var (sut, seed) = SetupDb(); + seed.ChannelOperationRequests.Add(new ChannelOperationRequest + { + Id = 55, + RequestType = OperationRequestType.Open, + Status = kept + }); + seed.ChannelOpenRecommendations.Add(Stored(ChannelOpenRecommendationStatus.Promoted, requestId: 55)); + await seed.SaveChangesAsync(); + + var count = await sut.FailUnrealizedPromotions(NodeId); + + // An open still on its way keeps its peer suppressed so the run cannot double the intent. + count.Should().Be(0); + var stored = await seed.ChannelOpenRecommendations.AsNoTracking().SingleAsync(); + stored.Status.Should().Be(ChannelOpenRecommendationStatus.Promoted); + } + + [Fact] + public async Task FailUnrealizedPromotions_RequestRejectedLongAfterThePromotion_DismissesTheRowFromNow() + { + var (sut, seed) = SetupDb(); + var now = DateTimeOffset.UtcNow; + seed.ChannelOperationRequests.Add(new ChannelOperationRequest + { + Id = 55, + RequestType = OperationRequestType.Open, + Status = ChannelOperationRequestStatus.Rejected + }); + // Promoted two days ago, well past any cooldown counted from the promotion. + var promoted = Row(NodeId, Peer, ChannelOpenRecommendationStatus.Promoted, updatedAt: now.AddDays(-2)); + promoted.ChannelOperationRequestId = 55; + seed.ChannelOpenRecommendations.Add(promoted); + await seed.SaveChangesAsync(); + + var count = await sut.FailUnrealizedPromotions(NodeId); + + // Not a failure: a rejection is an operator turning the peer down, like a dismissal. + count.Should().Be(0); + var stored = await seed.ChannelOpenRecommendations.AsNoTracking().SingleAsync(); + stored.Status.Should().Be(ChannelOpenRecommendationStatus.Dismissed); + stored.DismissReason.Should().Be("Channel open request rejected"); + + // The cooldown must run from the rejection, or the peer is proposed again on the next run. + var lastDecision = await sut.GetLastDecisionByPeer(NodeId); + lastDecision[Peer].Should().BeOnOrAfter(now); + } + + [Fact] + public async Task FailUnrealizedPromotions_LeavesOtherNodesAndUnpromotedRowsAlone() + { + var (sut, seed) = SetupDb(); + seed.ChannelOperationRequests.Add(new ChannelOperationRequest + { + Id = 55, + RequestType = OperationRequestType.Open, + Status = ChannelOperationRequestStatus.Failed + }); + var otherNodesRow = Row(2, "03otherNode", ChannelOpenRecommendationStatus.Promoted); + otherNodesRow.ChannelOperationRequestId = 55; + seed.ChannelOpenRecommendations.AddRange( + otherNodesRow, + Row(NodeId, "03dismissed", ChannelOpenRecommendationStatus.Dismissed), + Row(NodeId, "03open", ChannelOpenRecommendationStatus.Open)); + await seed.SaveChangesAsync(); + + var count = await sut.FailUnrealizedPromotions(NodeId); + + count.Should().Be(0); + var statuses = await seed.ChannelOpenRecommendations.AsNoTracking() + .ToDictionaryAsync(x => x.PeerPubKey, x => x.Status); + statuses["03otherNode"].Should().Be(ChannelOpenRecommendationStatus.Promoted); + statuses["03dismissed"].Should().Be(ChannelOpenRecommendationStatus.Dismissed); + statuses["03open"].Should().Be(ChannelOpenRecommendationStatus.Open); + } +} diff --git a/test/NodeGuard.Tests/Data/Repositories/ChannelOperationRequestRepositoryTests.cs b/test/NodeGuard.Tests/Data/Repositories/ChannelOperationRequestRepositoryTests.cs index fef7352c5..35801e0e6 100644 --- a/test/NodeGuard.Tests/Data/Repositories/ChannelOperationRequestRepositoryTests.cs +++ b/test/NodeGuard.Tests/Data/Repositories/ChannelOperationRequestRepositoryTests.cs @@ -125,4 +125,67 @@ public async Task AddAsync_ChannelOpenOperations_SimultaneousOpsAllowed() result.Item1.Should().BeTrue(); result.Item2.Should().BeNull(); } -} \ No newline at end of file + + private static ChannelOperationRequest Committed( + int sourceNodeId, long satsAmount, ChannelOperationRequestStatus status, + DateTimeOffset createdAt, OperationRequestType type = OperationRequestType.Open) + => new() + { + SourceNodeId = sourceNodeId, + DestNodeId = 99, + SatsAmount = satsAmount, + Status = status, + RequestType = type, + CreationDatetime = createdAt, + }; + + private static ChannelOperationRequestRepository BudgetSut( + Mock> dbContextFactory) + => new(Mock.Of>(), null, dbContextFactory.Object, null, null); + + [Fact] + public async Task GetOpenSatsCommittedSince_SumsOnlyLiveOpensOfThatSourceNodeInThePeriod() + { + // Arrange + var dbContextFactory = SetupDbContextFactory(); + await using var context = await dbContextFactory.Object.CreateDbContextAsync(); + var now = DateTimeOffset.UtcNow; + var since = now.AddDays(-1); + + await context.ChannelOperationRequests.AddRangeAsync( + Committed(1, 100, ChannelOperationRequestStatus.Pending, now.AddHours(-2)), + // The period start is inclusive, otherwise the first open of a budget period escapes it. + Committed(1, 200, ChannelOperationRequestStatus.OnChainConfirmed, since), + Committed(1, 400, ChannelOperationRequestStatus.Approved, now), + // Sats that will never leave the wallet must not keep eating the budget. + Committed(1, 800, ChannelOperationRequestStatus.Cancelled, now), + Committed(1, 1600, ChannelOperationRequestStatus.Rejected, now), + Committed(1, 3200, ChannelOperationRequestStatus.Failed, now), + Committed(1, 6400, ChannelOperationRequestStatus.Pending, since.AddSeconds(-1)), + Committed(2, 12800, ChannelOperationRequestStatus.Pending, now), + // A close returns funds rather than committing them. + Committed(1, 25600, ChannelOperationRequestStatus.Pending, now, OperationRequestType.Close)); + await context.SaveChangesAsync(); + + // Act + var result = await BudgetSut(dbContextFactory).GetOpenSatsCommittedSince(1, since); + + // Assert + result.Should().Be(700); + } + + [Fact] + public async Task GetOpenSatsCommittedSince_ReturnsZero_WhenNothingMatches() + { + // Arrange + var dbContextFactory = SetupDbContextFactory(); + + // Act + // A node in its first budget period has no rows at all, and the job would divide by a null + // budget rather than skip the node if this threw. + var result = await BudgetSut(dbContextFactory).GetOpenSatsCommittedSince(1, DateTimeOffset.UtcNow.AddDays(-1)); + + // Assert + result.Should().Be(0); + } +} diff --git a/test/NodeGuard.Tests/Data/Repositories/ForwardingHtlcEventRepositoryTests.cs b/test/NodeGuard.Tests/Data/Repositories/ForwardingHtlcEventRepositoryTests.cs index 8226a4a54..3e3e74dfe 100644 --- a/test/NodeGuard.Tests/Data/Repositories/ForwardingHtlcEventRepositoryTests.cs +++ b/test/NodeGuard.Tests/Data/Repositories/ForwardingHtlcEventRepositoryTests.cs @@ -105,4 +105,95 @@ public async Task Getters_ReturnZero_WhenNoMatchingRows() (await sut.GetOutgoingAmountMsat(Node, Chan, DateTimeOffset.UtcNow.AddDays(-1))).Should().Be(0); (await sut.GetIncomingAmountMsat(Node, Chan, DateTimeOffset.UtcNow.AddDays(-1))).Should().Be(0); } + + [Fact] + public async Task ByChannelGetters_GroupSettledOutgoingVolumeAndFeesPerChannel() + { + var (factory, seed) = SetupDb(); + var now = DateTimeOffset.UtcNow; + var since = now.AddDays(-7); + + seed.ForwardingHtlcEvents.AddRange( + Event(Node, 900, Chan, ForwardingOutcome.Settled, now, outgoingAmt: 1000, fee: 10, inHtlc: 1, outHtlc: 1), + Event(Node, 901, Chan, ForwardingOutcome.Settled, since, outgoingAmt: 500, fee: 5, inHtlc: 2, outHtlc: 2), + Event(Node, 902, OtherChan, ForwardingOutcome.Settled, now, outgoingAmt: 3000, fee: 30, inHtlc: 3, outHtlc: 3), + // Refused or still unresolved forwards earned nothing. + Event(Node, 903, Chan, ForwardingOutcome.Failed, now, outgoingAmt: 7777, fee: 77, inHtlc: 4, outHtlc: 4), + Event(Node, 904, Chan, ForwardingOutcome.Settled, since.AddSeconds(-1), outgoingAmt: 9999, fee: 99, inHtlc: 5, outHtlc: 5), + Event(OtherNode, 905, Chan, ForwardingOutcome.Settled, now, outgoingAmt: 6666, fee: 66, inHtlc: 6, outHtlc: 6) + ); + await seed.SaveChangesAsync(); + + var sut = Sut(factory); + + (await sut.GetOutgoingAmountsMsatByChannel(Node, since)).Should().BeEquivalentTo( + new Dictionary { [Chan] = 1500, [OtherChan] = 3000 }); + (await sut.GetEarnedFeesMsatByChannel(Node, since)).Should().BeEquivalentTo( + new Dictionary { [Chan] = 15, [OtherChan] = 30 }); + } + + [Fact] + public async Task GetEarnedFeesMsatByChannel_SettledRowWithoutFee_CountsAsZero() + { + var (factory, seed) = SetupDb(); + var now = DateTimeOffset.UtcNow; + var row = Event(Node, 900, Chan, ForwardingOutcome.Settled, now, outgoingAmt: 1000, inHtlc: 1, outHtlc: 1); + row.FeeMsat = null; + seed.ForwardingHtlcEvents.Add(row); + await seed.SaveChangesAsync(); + + var result = await Sut(factory).GetEarnedFeesMsatByChannel(Node, now.AddDays(-1)); + + result.Should().BeEquivalentTo(new Dictionary { [Chan] = 0 }); + } + + /// A refused forward, with every field the insufficient-balance filter looks at explicit. + private static ForwardingHtlcEvent Failure( + string node, ulong incomingChan, ulong outgoingChan, DateTimeOffset ts, + int failureDetail = (int)Routerrpc.FailureDetail.InsufficientBalance, + HtlcEventType eventType = HtlcEventType.Forward, + HtlcEventCase eventCase = HtlcEventCase.LinkFailEvent, + ulong inHtlc = 0, ulong outHtlc = 0) + => new() + { + ManagedNodePubKey = node, + IncomingChannelId = incomingChan, + OutgoingChannelId = outgoingChan, + IncomingHtlcId = inHtlc, + OutgoingHtlcId = outHtlc, + EventTimestamp = ts, + EventType = eventType, + EventCase = eventCase, + Outcome = ForwardingOutcome.Failed, + FailureDetail = failureDetail, + }; + + [Fact] + public async Task GetInsufficientBalanceCountsByChannel_CountsOnlyOutboundShortagesOfThisNodeInWindow() + { + var (factory, seed) = SetupDb(); + var now = DateTimeOffset.UtcNow; + var since = now.AddHours(-6); + + seed.ForwardingHtlcEvents.AddRange( + Failure(Node, 900, Chan, now.AddHours(-2), inHtlc: 1, outHtlc: 1), + // The window is inclusive: a refusal landing exactly on the boundary still counts. + Failure(Node, 901, Chan, since, inHtlc: 2, outHtlc: 2), + Failure(Node, 902, OtherChan, now, inHtlc: 3, outHtlc: 3), + Failure(Node, 903, Chan, since.AddSeconds(-1), inHtlc: 4, outHtlc: 4), + Failure(OtherNode, 904, Chan, now, inHtlc: 5, outHtlc: 5), + // A local send is not routing demand. + Failure(Node, 905, Chan, now, eventType: HtlcEventType.Send, inHtlc: 6, outHtlc: 6), + // A downstream failure says nothing about our own outgoing balance. + Failure(Node, 906, Chan, now, eventCase: HtlcEventCase.ForwardFailEvent, inHtlc: 7, outHtlc: 7), + // Our own max-HTLC ceiling, not a shortage. + Failure(Node, 907, Chan, now, failureDetail: (int)Routerrpc.FailureDetail.HtlcExceedsMax, + inHtlc: 8, outHtlc: 8) + ); + await seed.SaveChangesAsync(); + + var result = await Sut(factory).GetInsufficientBalanceCountsByChannel(Node, since); + + result.Should().BeEquivalentTo(new Dictionary { [Chan] = 2, [OtherChan] = 1 }); + } } diff --git a/test/NodeGuard.Tests/Data/Repositories/NodeRepositoryTests.cs b/test/NodeGuard.Tests/Data/Repositories/NodeRepositoryTests.cs index 7c0aa30db..b90413578 100644 --- a/test/NodeGuard.Tests/Data/Repositories/NodeRepositoryTests.cs +++ b/test/NodeGuard.Tests/Data/Repositories/NodeRepositoryTests.cs @@ -1,3 +1,6 @@ +using AutoMapper; +using Microsoft.Extensions.Logging.Abstractions; +using NodeGuard.Automapper; using FluentAssertions; using NodeGuard.Data.Models; using NodeGuard.Data.Repositories.Interfaces; @@ -72,4 +75,103 @@ public async Task GetAllConfiguredByProvider_ForSpark_ReturnsEveryManagedLndNode sparkNodes.Select(n => n.Name).Should().BeEquivalentTo("lnd-only", "with-loop"); loopNodes.Select(n => n.Name).Should().BeEquivalentTo("with-loop"); } + + private static Node AutoOpenNode(string pubKey, bool enabled = true, int? walletId = 10, + bool nodeDisabled = false) + => new() + { + PubKey = pubKey, + Name = pubKey, + Endpoint = "localhost:10009", + IsNodeDisabled = nodeDisabled, + AutoChannelOpenEnabled = enabled, + AutoChannelOpenWalletId = walletId, + }; + + private static NodeRepository AutoOpenSut(Mock> dbContextFactory) + => new(Mock.Of>(), null, dbContextFactory.Object, null); + + [Fact] + public async Task GetAllWithAutoChannelOpenEnabled_SkipsDisabledOptedOutAndUnfundedNodes() + { + // Arrange + var dbContextFactory = SetupDbContextFactory(); + await using var context = await dbContextFactory.Object.CreateDbContextAsync(); + context.Wallets.Add(new Wallet { Id = 10, Name = "funding", MofN = 1, Keys = new List() }); + context.Nodes.AddRange( + AutoOpenNode("eligible"), + AutoOpenNode("disabled", nodeDisabled: true), + AutoOpenNode("optedOut", enabled: false), + // Without a funding wallet there is nothing to pay for the channel, so the job cannot act. + AutoOpenNode("unfunded", walletId: null)); + await context.SaveChangesAsync(); + + // Act + var result = await AutoOpenSut(dbContextFactory).GetAllWithAutoChannelOpenEnabled(); + + // Assert + result.Should().ContainSingle().Which.PubKey.Should().Be("eligible"); + } + + [Fact] + public async Task GetAllWithAutoChannelOpenEnabled_EagerLoadsTheFundingWalletAndItsKeys() + { + // Arrange + var dbContextFactory = SetupDbContextFactory(); + await using var context = await dbContextFactory.Object.CreateDbContextAsync(); + context.Wallets.Add(new Wallet + { + Id = 10, + Name = "funding", + MofN = 1, + Keys = new List { new() { Name = "key", XPUB = "xpub" } } + }); + context.Nodes.Add(AutoOpenNode("eligible")); + await context.SaveChangesAsync(); + + // Act + var result = await AutoOpenSut(dbContextFactory).GetAllWithAutoChannelOpenEnabled(); + + // Assert + // The job reads the wallet off the node to get a balance, so losing this eager load would + // silently stop every node from ever opening a channel instead of failing loudly. + var node = result.Should().ContainSingle().Subject; + node.AutoChannelOpenWallet.Should().NotBeNull(); + node.AutoChannelOpenWallet!.Keys.Should().ContainSingle(); + } + + [Fact] + public async Task Update_NodeLoadedWithItsAutoChannelOpenWallet_PersistsWithoutTouchingTheWallet() + { + // Arrange + var dbContextFactory = SetupDbContextFactory(); + await using (var context = await dbContextFactory.Object.CreateDbContextAsync()) + { + context.Wallets.Add(new Wallet + { + Id = 10, + Name = "funding", + MofN = 1, + Keys = new List { new() { Name = "key", XPUB = "xpub" } } + }); + context.Nodes.Add(AutoOpenNode("eligible")); + await context.SaveChangesAsync(); + } + + var mapper = new MapperConfiguration(config => config.AddProfile()).CreateMapper(); + var sut = new NodeRepository(new Repository(NullLogger.Instance), null, dbContextFactory.Object, mapper); + var node = (await sut.GetAllWithAutoChannelOpenEnabled()).Single(); + var budgetStart = DateTimeOffset.UtcNow; + node.AutoChannelOpenBudgetStartDatetime = budgetStart; + + // Act + var (updated, _) = sut.Update(node); + + // Assert + // Attaching the eagerly loaded wallet re-inserts its KeyWallet join rows, so the save fails + updated.Should().BeTrue(); + await using var verify = await dbContextFactory.Object.CreateDbContextAsync(); + var persisted = await verify.Nodes.AsNoTracking().SingleAsync(x => x.PubKey == "eligible"); + persisted.AutoChannelOpenBudgetStartDatetime.Should().Be(budgetStart); + } }