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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,11 @@
"ROUTING_ENGINE_ENABLED": "true",
"AUTO_CHANNEL_OPEN_ENABLED": "true",
"AUTO_CHANNEL_OPEN_MIN_EARNED_FEE_SATS": "1",
"AUTO_CHANNEL_OPEN_MIN_REFUSALS": "3"
"AUTO_CHANNEL_OPEN_MIN_REFUSALS": "1",
"AUTO_CHANNEL_OPEN_LOOKBACK_DAYS": "30",
"AUTO_CHANNEL_OPEN_SHORTAGE_HOURS": "24",
"AUTO_CHANNEL_OPEN_LOW_OUTBOUND_PCT": "50",
"AUTO_CHANNEL_OPEN_PEER_COOLDOWN_HOURS": "1"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
Expand Down
2 changes: 1 addition & 1 deletion docker/loop/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ x-loop-service: &loop-service

x-loopd-service: &loopd-service
<<: *loop-service
image: lightninglabs/loop:v0.31.2-beta
image: lightninglabs/loop:v0.36.0-beta

services:
loopserver:
Expand Down
24 changes: 22 additions & 2 deletions docs/auto-channel-open.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Auto channel open

Auto channel open proposes a new channel to a peer when two things are true: the route to that peer has been earning us fees, and we have recently been turning payments to it away for lack of outbound liquidity. The channel always has the same size, set per node.
Auto channel open proposes a new channel to a peer when two things are true: the route to that peer has been earning us fees, and we have recently been turning payments to it away for lack of outbound liquidity. The channel always has the same size, set per node. Peers we want channels with regardless, such as a swap service, can be [reserved](#reserved-peers) a share of the budget.

[`AutoChannelOpenJob`](../src/Jobs/AutoChannelOpenJob.cs) runs every 30 minutes (every minute in a dev environment) as part of the routing engine (see [routing-engine.md](routing-engine.md)). It writes recommendations, which an operator promotes from the Routing Management page. In **Auto** mode the job promotes them itself. Either way a promotion only creates a channel open request: funding still goes through the usual approval and signing flow.

Expand Down Expand Up @@ -39,7 +39,18 @@ Promoting creates a `ChannelOperationRequest` to open a public channel to the pe
- With a **hot wallet** that needs no human signature, the template PSBT is built and `ChannelOpenJob` is scheduled straight away. If the template can't be built (no spendable coins), the request fails.
- Otherwise the request stays **Pending** for the wallet's signers, like any other channel open.

**The fee the channel opens at.** A new channel arrives with all its balance on our side, so at the node's default fee it would become the cheapest route to a peer we already know is in demand. It opens instead at the highest fee rate we currently charge on our channels to that peer, with the base fee of that same channel. The policy is captured with the evidence on every run, and the channel opens at the one captured last, without asking LND again at promotion.
**The fee the channel opens at.** A new channel arrives with all its balance on our side, so at the node's default fee it would become the cheapest route to a peer we already know is in demand. It opens instead at the highest fee rate we currently charge on our channels to that peer, with the base fee of that same channel. The policy is captured with the evidence on every run, and the channel opens at the one captured last, without asking LND again at promotion. The one exception is a reserved peer we have no fee to copy from, usually because we have no channel with it yet: its channel opens at the fee rate and base fee set on its reservation.

## Reserved peers

Some peers need channels whether or not they earn us anything. A swap service such as Loop is the usual case: our swap-outs are our own payments to it, not forwards, so the route to it never earns fees and never passes check 1. Each node can list such peers on the Nodes page (Automatic Channel Opening ▸ Reserved Peers). Each one is a node registered in NodeGuard, picked from a list, with a share of the budget in percent, a fee rate and a base fee. The shares of a node add up to at most 100%. Both fees are required.

A reserved peer skips the evidence (checks 1, 2 and 5). It qualifies when:
- the usable outbound to it is below `AUTO_CHANNEL_OPEN_LOW_OUTBOUND_PCT` of the capacity we have with it, or we have no channel with it at all;
- it is not on cooldown;
- the node's channel size fits the funding wallet and the budget left for it (see below).

Reserved peers are evaluated ahead of the others in each run, so the per-run cap can't crowd them out. Their recommendations show a **reserved** badge on the Routing Management page, and the panel shows what each share has committed this period.

## Lifecycle

Expand All @@ -63,6 +74,13 @@ Each node has a channel open budget: the most it may commit to new channels per

What counts as committed is the capacity of every channel open request from the node created in the current period, except those cancelled, rejected or failed. That includes opens created by hand, not only the automatic ones. Within a run, every promotion is deducted before the next plan is checked.

**Reserved shares.** Each reserved peer's share of the budget (its percentage) is set aside for it, and the rest is shared by every other peer:
- An ordinary peer can only use the unreserved part.
- A reserved peer uses its own share first, then the unreserved part.
- Committed sats count against the peer the request opens to, so an open made by hand to a reserved peer uses up its share too. Whatever a reserved peer commits beyond its share comes out of the unreserved part.

For example, with a 10 BTC budget and Loop reserved at 30%, other peers can commit at most 7 BTC, and Loop up to 3 BTC on its own share plus whatever the others leave of the 7.

## Settings

**Environment** ([`Constants.cs`](../src/Helpers/Constants.cs)):
Expand All @@ -85,6 +103,7 @@ What counts as committed is the capacity of every channel open request from the
- **Funding wallet**: the wallet the channels are paid from. Required.
- **Channel size**: the capacity of every recommended channel. Required, at least `MINIMUM_CHANNEL_CAPACITY_SATS`.
- **Budget** and **budget refresh interval**. A budget is required.
- **Reserved peers**: a registered node, a share of the budget and an opening fee (rate and base) for each. See [Reserved peers](#reserved-peers).
- **Dry run**, shared with the fee engine and the rebalancer.

A node without a funding wallet, channel size or budget is skipped, and the job logs why. The Routing Management page shows the size, the budget and what the current period has committed next to the recommendations, and warns when the feature is globally off or the node has no funding wallet.
Expand All @@ -97,3 +116,4 @@ A node without a funding wallet, channel size or budget is skipped, and the job
- **One size for every peer.** The channel doesn't grow with demand. A peer that needs more gets another recommendation once the cooldown has passed and it is short again.
- **The swap-out check doesn't see requests still waiting for signatures.** A promoted open counts towards the node's balance only once LND reports it as pending, so opens promoted in earlier runs and not yet funded are left out.
- **The budget is checked per recommendation.** In Recommendation mode several open recommendations may together exceed the remaining budget, and promoting from the panel doesn't check the budget again. The next run sees what was committed.
- **A reserved peer's channel is invisible until it opens.** The job reads channels from `ListChannels`, which leaves out pending ones. An automatic open holds its peer until it confirms, but an open made by hand to a reserved peer we had no channel with doesn't: the peer looks channel-less, and is recommended again once its cooldown, if any, has passed. Its share still caps what it can be given.
1 change: 1 addition & 0 deletions src/Automapper/MapperProfile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ public MapperProfile()
.ForMember(x => x.FundsDestinationWallet, opt => opt.Ignore())
.ForMember(x => x.AutoChannelOpenWallet, opt => opt.Ignore())
.ForMember(x => x.ChannelOpenRecommendations, opt => opt.Ignore())
.ForMember(x => x.ReservedChannelOpenPeers, opt => opt.Ignore())
.ForMember(x => x.Users, opt => opt.Ignore());

CreateMap<Channel, Channel>()
Expand Down
18 changes: 18 additions & 0 deletions src/Data/ApplicationDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,22 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
modelBuilder.Entity<ChannelOpenRecommendation>()
.HasIndex(x => new { x.NodeId, x.PeerPubKey }).IsUnique();

modelBuilder.Entity<ReservedChannelOpenPeer>()
.HasOne(x => x.Node)
.WithMany(x => x.ReservedChannelOpenPeers)
.HasForeignKey(x => x.NodeId)
.OnDelete(DeleteBehavior.Cascade);

// Deleting the peer's node drops its reservations too, so none is left pointing nowhere.
modelBuilder.Entity<ReservedChannelOpenPeer>()
.HasOne(x => x.PeerNode)
.WithMany()
.HasForeignKey(x => x.PeerNodeId)
.OnDelete(DeleteBehavior.Cascade);

modelBuilder.Entity<ReservedChannelOpenPeer>()
.HasIndex(x => new { x.NodeId, x.PeerNodeId }).IsUnique();

// These default ON: existing rows must be backfilled true (the C# initializer
// only affects new in-code instances, not the DB column default / migration backfill).
modelBuilder.Entity<Channel>().Property(x => x.IsDynamicFeeEnabled).HasDefaultValue(false);
Expand Down Expand Up @@ -239,5 +255,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
public DbSet<SparkSignerIdentity> SparkSignerIdentities { get; set; }

public DbSet<ChannelOpenRecommendation> ChannelOpenRecommendations { get; set; }

public DbSet<ReservedChannelOpenPeer> ReservedChannelOpenPeers { get; set; }
}
}
4 changes: 4 additions & 0 deletions src/Data/Models/ChannelOpenRecommendation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ public class ChannelOpenRecommendation : Entity
public long? InheritedFeeRatePpm { get; set; }

public long? InheritedBaseFeeMsat { get; set; }

/// Qualified as a <see cref="ReservedChannelOpenPeer"/>, on outbound alone. With no channel to the
/// peer there is no policy to inherit, and the channel opens at the node's default fee.
public bool IsReservedPeer { get; set; }
#endregion Evidence

#region Lifecycle
Expand Down
2 changes: 2 additions & 0 deletions src/Data/Models/Node.cs
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,8 @@ public class Node : Entity

public ICollection<ChannelOpenRecommendation> ChannelOpenRecommendations { get; set; }

public ICollection<ReservedChannelOpenPeer> ReservedChannelOpenPeers { get; set; }

public ICollection<ChannelOperationRequest> ChannelOperationRequestsAsSource { get; set; }
public ICollection<ChannelOperationRequest> ChannelOperationRequestsAsDestination { get; set; }

Expand Down
50 changes: 50 additions & 0 deletions src/Data/Models/ReservedChannelOpenPeer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* NodeGuard
* Copyright (C) 2023 Elenpay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/

using System.ComponentModel.DataAnnotations;

namespace NodeGuard.Data.Models;

/// <summary>
/// A peer that gets its own share of the node's channel open budget, such as a swap service. It skips
/// the earning evidence: it qualifies on low outbound alone, or on having no channel with us at all.
/// Its channel opens at the fee set here whenever we have no fee toward it to copy.
/// The peer is one of the registered nodes, so its name and pubkey are read from there.
/// <para>
/// One row per (<see cref="NodeId"/>, <see cref="PeerNodeId"/>). Shares of one node sum to at most 100.
/// </para>
/// </summary>
public class ReservedChannelOpenPeer : Entity
{
public int NodeId { get; set; }
public Node? Node { get; set; }

public int PeerNodeId { get; set; }
public Node? PeerNode { get; set; }

/// Share of the node's channel open budget reserved for this peer, 1 to 100.
public int BudgetPct { get; set; }

/// Nullable so a form can leave it unset, required so no row is saved without it.
[Required]
public long? FeeRatePpm { get; set; }

[Required]
public long? BaseFeeMsat { get; set; }
}
4 changes: 3 additions & 1 deletion src/Data/Repositories/ChannelOpenRecommendationRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ public async Task<List<ChannelOpenRecommendation>> GetOpenByNode(int nodeId)

return await context.ChannelOpenRecommendations
.Where(x => x.NodeId == nodeId && x.Status == ChannelOpenRecommendationStatus.Open)
.OrderByDescending(x => x.EarnedFeeSats)
.OrderByDescending(x => x.IsReservedPeer)
.ThenByDescending(x => x.EarnedFeeSats)
.ToListAsync();
}

Expand Down Expand Up @@ -121,6 +122,7 @@ private static void CopyEvidence(ChannelOpenRecommendation from, ChannelOpenReco
to.SuggestedCapacitySats = from.SuggestedCapacitySats;
to.InheritedFeeRatePpm = from.InheritedFeeRatePpm;
to.InheritedBaseFeeMsat = from.InheritedBaseFeeMsat;
to.IsReservedPeer = from.IsReservedPeer;
to.LastEvidenceAt = from.LastEvidenceAt;
}

Expand Down
16 changes: 16 additions & 0 deletions src/Data/Repositories/ChannelOperationRequestRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,22 @@ public async Task<long> GetOpenSatsCommittedSince(int sourceNodeId, DateTimeOffs
.SumAsync(x => (long?)x.SatsAmount) ?? 0;
}

public async Task<Dictionary<string, long>> GetOpenSatsCommittedByPeerSince(int sourceNodeId, DateTimeOffset since)
{
await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync();

return await applicationDbContext.ChannelOperationRequests
.Where(x => x.SourceNodeId == sourceNodeId
&& x.RequestType == OperationRequestType.Open
&& x.CreationDatetime >= since
&& x.Status != ChannelOperationRequestStatus.Cancelled
&& x.Status != ChannelOperationRequestStatus.Rejected
&& x.Status != ChannelOperationRequestStatus.Failed)
.GroupBy(x => x.DestNode != null ? x.DestNode.PubKey : "")
.Select(g => new { PubKey = g.Key, Sats = g.Sum(x => x.SatsAmount) })
.ToDictionaryAsync(x => x.PubKey, x => x.Sats);
}

public async Task<List<ChannelOperationRequest>> GetPendingRequests()
{
await using var applicationDbContext = await _dbContextFactory.CreateDbContextAsync();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ public interface IChannelOperationRequestRepository : IBitcoinRequestRepository
/// </summary>
Task<long> GetOpenSatsCommittedSince(int sourceNodeId, DateTimeOffset since);

/// <summary>
/// <see cref="GetOpenSatsCommittedSince"/> split by the peer's pubkey, for the reserved budget shares.
/// A request without a destination node is keyed by the empty string.
/// </summary>
Task<Dictionary<string, long>> GetOpenSatsCommittedByPeerSince(int sourceNodeId, DateTimeOffset since);

Task<(List<ChannelOperationRequest> requests, int totalCount)> GetPaginatedAsync(
int pageNumber,
int pageSize,
Expand Down
5 changes: 5 additions & 0 deletions src/Data/Repositories/Interfaces/INodeRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ public interface INodeRepository
/// </summary>
Task<Dictionary<string, string>> GetNamesByPubKeys(IReadOnlyCollection<string> pubKeys);

/// <summary>
/// Every registered node, managed or not, without its relationships. For node pickers.
/// </summary>
Task<List<Node>> GetAllForSelection();

Task<List<Node>> GetAllManagedByUser(string userId);

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* NodeGuard
* Copyright (C) 2023 Elenpay
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/

using NodeGuard.Data.Models;

namespace NodeGuard.Data.Repositories.Interfaces;

public interface IReservedChannelOpenPeerRepository
{
/// <summary>The node's reserved peers, each with its <see cref="ReservedChannelOpenPeer.PeerNode"/>.</summary>
Task<List<ReservedChannelOpenPeer>> GetByNode(int nodeId);

/// <summary>
/// Replaces the node's reserved peers with <paramref name="peers"/> atomically, so a half-saved list can
/// never push the shares past 100%.
/// </summary>
Task<(bool, string?)> ReplaceForNode(int nodeId, IReadOnlyList<ReservedChannelOpenPeer> peers);
}
Loading
Loading