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
3 changes: 3 additions & 0 deletions docker/e2e/nodeguard-entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ until [ -s "$ENV_FILE" ] || [ $i -ge 60 ]; do i=$((i+1)); sleep 2; done
if [ -s "$ENV_FILE" ]; then
set -a; . "$ENV_FILE"; set +a
echo "Loaded LND connection env for ALICE/BOB/CAROL."
# AutoChannelOpenE2ETests: carol stands in for a 40swap node. It only counts for a node that gives
# 40swap a weight, which the seeded nodes don't.
export FORTYSWAP_NODE_PUBKEYS="${FORTYSWAP_NODE_PUBKEYS:-$CAROL_PUBKEY}"
else
echo "WARNING: $ENV_FILE missing/empty; NodeGuard may fail to reach LND." >&2
fi
Expand Down
26 changes: 23 additions & 3 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. Peers we want channels with regardless, such as a swap service, can be [reserved](#reserved-peers) a share of the budget.
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 can be [reserved](#reserved-peers) a share of the budget. A swap provider the node swaps out through [never gets one](#swap-providers).

[`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 All @@ -27,6 +27,24 @@ The size is never adjusted: a peer whose channel doesn't fit the wallet or the b
- Outbound and capacity come from LND's `ListChannels` at the time of the run. Check 3 matters because the refusals are history: a rebalance or a payment the other way may have refilled the peer since.
- What the wallet can fund is computed from the wallet's spendable coins (locked and frozen ones excluded) at mempool's hour fee rate, leaving room for the funding fee and a change output.

## Swap providers

A node gets no recommendation to a swap provider it swaps out through. The swap-outs are our own payments to the provider, so they would drain the new channel as soon as it opened.

A node swaps out through every provider it gives a weight above 0 (Loop alone when none has one), however small the weight. The provider's Lightning nodes are listed by pubkey (see below). A peer on the list of such a provider is rejected before any other check, [reserved](#reserved-peers) or not, and logged with the reason. An open recommendation to it expires on the next run. A provider the node gives no weight is treated like any other peer.

The check is only on recommendations: a channel open request created by hand is not stopped.

Each provider's list has a default, the provider's mainnet nodes:

| Variable | Default |
|---|---|
| `LOOP_NODE_PUBKEYS` | `021c97a90a411ff2b10dc2a8e32de2f29d2fa49d41bfbb52bd416e460db0747d0d` |
| `FORTYSWAP_NODE_PUBKEYS` | empty: 40swap is not blocked until its nodes are listed |
| `SPARK_NODE_PUBKEYS` | `039174f846626c6053ba80f5443d0db33da384f1dde135bf7080ba1eec465019c3`, `02a98e8c590a1b5602049d6b21d8f4c8861970aa310762f42eae1b2be88372e924` |

Setting a variable replaces its default, it does not add to it: list every pubkey, comma-separated. An empty value clears the list, so that provider is no longer blocked.

## Modes and promotion

Each node runs in one of two modes:
Expand All @@ -43,11 +61,12 @@ Promoting creates a `ChannelOperationRequest` to open a public channel to the pe

## 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.
Some peers need channels whether or not they earn us anything: a peer we mostly pay ourselves rather than forward to never earns fees on the route, so it 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;
- it is not a [swap provider](#swap-providers) the node swaps out through;
- 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.
Expand Down Expand Up @@ -81,7 +100,7 @@ What counts as committed is the capacity of every channel open request from the
- 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.
For example, with a 10 BTC budget and a peer reserved at 30%, other peers can commit at most 7 BTC, and the reserved peer up to 3 BTC on its own share plus whatever the others leave of the 7.

## Settings

Expand All @@ -99,6 +118,7 @@ For example, with a 10 BTC budget and Loop reserved at 30%, other peers can comm
| `AUTO_CHANNEL_OPEN_MAX_PLANS_PER_RUN` | 5 | Most recommendations per node per run. |
| `AUTO_CHANNEL_OPEN_DEFAULT_BUDGET_REFRESH_HOURS` | 720 | Budget period when the node sets none. |
| `AUTO_CHANNEL_OPEN_JOB_INTERVAL_MINUTES` | 30 | Job interval; 1 in a dev environment. |
| `LOOP_NODE_PUBKEYS`, `FORTYSWAP_NODE_PUBKEYS`, `SPARK_NODE_PUBKEYS` | see [Swap providers](#swap-providers) | Pubkeys of each swap provider's Lightning nodes, comma-separated. |

**Per node**, on the Nodes page (liquidity management ▸ Automatic Channel Opening):
- **Enable automatic channel opening** and the **mode**.
Expand Down
24 changes: 24 additions & 0 deletions src/Helpers/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,21 @@ public class Constants
// In dev this is 1 minute.
public static int AUTO_CHANNEL_OPEN_JOB_INTERVAL_MINUTES = 30;

// Lightning pubkeys of each swap provider's nodes, comma-separated in the environment. A node gets no
// channel open recommendation to a provider it swaps out through.
public static IReadOnlySet<string> LOOP_NODE_PUBKEYS = new HashSet<string>()
{
"021c97a90a411ff2b10dc2a8e32de2f29d2fa49d41bfbb52bd416e460db0747d0d",
};

public static IReadOnlySet<string> FORTYSWAP_NODE_PUBKEYS = new HashSet<string>();

public static IReadOnlySet<string> SPARK_NODE_PUBKEYS = new HashSet<string>()
{
"039174f846626c6053ba80f5443d0db33da384f1dde135bf7080ba1eec465019c3",
"02a98e8c590a1b5602049d6b21d8f4c8861970aa310762f42eae1b2be88372e924",
};

#endregion Auto Channel Open


Expand All @@ -450,6 +465,11 @@ public class Constants
return envVariable;
}

// Null when the variable is unset, so the default stays.
private static IReadOnlySet<string>? ParsePubKeys(string? commaSeparated) =>
commaSeparated?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.ToHashSet(StringComparer.OrdinalIgnoreCase);

static Constants()
{
IS_DEV_ENVIRONMENT = StringHelper.IsTrue(Environment.GetEnvironmentVariable("IS_DEV_ENVIRONMENT"));
Expand Down Expand Up @@ -814,6 +834,10 @@ static Constants()
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;

LOOP_NODE_PUBKEYS = ParsePubKeys(Environment.GetEnvironmentVariable("LOOP_NODE_PUBKEYS")) ?? LOOP_NODE_PUBKEYS;
FORTYSWAP_NODE_PUBKEYS = ParsePubKeys(Environment.GetEnvironmentVariable("FORTYSWAP_NODE_PUBKEYS")) ?? FORTYSWAP_NODE_PUBKEYS;
SPARK_NODE_PUBKEYS = ParsePubKeys(Environment.GetEnvironmentVariable("SPARK_NODE_PUBKEYS")) ?? SPARK_NODE_PUBKEYS;
}

}
Expand Down
4 changes: 3 additions & 1 deletion src/Jobs/AutoChannelOpenJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ private async Task<List<PeerSnapshot>> BuildPeerSnapshots(Node node, DateTimeOff
var policyByChanId = policyTask.Result;
var lastDecisionByPeer = lastDecisionTask.Result;
var cooldownCutoff = now.AddHours(-Constants.AUTO_CHANNEL_OPEN_PEER_COOLDOWN_HOURS);
var swapProviderByPeer = SwapProviderLimits.NodesSwappedThrough(node);

// Fees and refusals on channels that have since closed are dropped with them: only the peer's
// current channels map back to a pubkey.
Expand Down Expand Up @@ -287,7 +288,8 @@ private async Task<List<PeerSnapshot>> BuildPeerSnapshots(Node node, DateTimeOff
.Where(p => p != null)
.MaxBy(p => p!.FeeRatePpm) ?? reserved.GetValueOrDefault(x.Peer),
OnCooldown: lastDecisionByPeer.TryGetValue(x.Peer, out var last) && last > cooldownCutoff,
IsReserved: reserved.ContainsKey(x.Peer)))
IsReserved: reserved.ContainsKey(x.Peer),
SwapProvider: swapProviderByPeer.TryGetValue(x.Peer, out var provider) ? provider : null))
.ToList();
}

Expand Down
3 changes: 2 additions & 1 deletion src/Pages/Nodes.razor
Original file line number Diff line number Diff line change
Expand Up @@ -902,10 +902,11 @@
<Field>
<FieldLabel>Reserved Peers</FieldLabel>
<FieldHelp>
Registered nodes with their own share of the budget, such as a swap service. They skip the earning evidence: a reserved peer gets a channel
Registered nodes with their own share of the budget. They skip the earning evidence: a reserved peer gets a channel
whenever its usable outbound is below @Constants.AUTO_CHANNEL_OPEN_LOW_OUTBOUND_PCT%, or we have no channel with it yet.
Other peers can't spend a reserved share. A reserved peer spends its own share first, then the rest of the budget.
The fee rate and base fee are what its channel opens at when we have no channel with it to copy a fee from.
A swap provider this node swaps out through gets no channel, reserved or not.
</FieldHelp>
@foreach (var peer in _reservedPeers)
{
Expand Down
11 changes: 10 additions & 1 deletion src/Services/ChannelOpenInitiatorService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ namespace NodeGuard.Services;
/// Everything the planner knows about one peer, aggregated over all our open channels to it. LND
/// forwards non-strictly and reports whichever channel it tried last, so the peer is the identity.
/// A reserved peer we have no channel with has a zero capacity and the policy set on its reservation.
/// <paramref name="SwapProvider"/> is set when the peer is a node of a provider we swap out through.
/// </summary>
public record PeerSnapshot(
string PeerPubKey,
Expand All @@ -36,7 +37,8 @@ public record PeerSnapshot(
long CapacitySats,
LocalOutboundPolicy? OutboundPolicy,
bool OnCooldown,
bool IsReserved = false);
bool IsReserved = false,
SwapProvider? SwapProvider = null);

public record ChannelOpenInitiatorTunables(
long MinEarnedFeeSats,
Expand Down Expand Up @@ -70,6 +72,7 @@ public record ChannelOpenClassification(
/// Channel-open planner. Pure, no I/O. A peer gets a fixed-size channel when the route to it has
/// earned us fees, it refused forwards recently for lack of outbound, and it is still short now.
/// A reserved peer skips the evidence: being short now, or having no channel at all, is enough.
/// A swap provider the node swaps out through never gets one.
/// </summary>
public static class ChannelOpenInitiatorService
{
Expand Down Expand Up @@ -120,6 +123,12 @@ public static ChannelOpenClassification Evaluate(

private static string? Reject(PeerSnapshot peer, ChannelOpenInitiatorTunables t)
{
// Reserved or not: the swap-outs we pay through it would drain the new channel.
if (peer.SwapProvider != null)
{
return $"it is a {peer.SwapProvider} node, a swap provider the node swaps out through";
}

if (peer.OnCooldown)
{
return "on cooldown after a recent promotion or dismissal";
Expand Down
26 changes: 26 additions & 0 deletions src/Services/SwapProviderLimits.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,32 @@ public readonly record struct SwapProviderLimits(long MinSats, long MaxSats, int
return weighted.Count > 0 ? weighted : [(SwapProvider.Loop, 1)];
}

/// <summary>
/// The Lightning nodes of the providers <paramref name="node"/> swaps out through (see <see cref="Weighted"/>),
/// by pubkey, from LOOP_NODE_PUBKEYS, FORTYSWAP_NODE_PUBKEYS and SPARK_NODE_PUBKEYS.
/// </summary>
public static IReadOnlyDictionary<string, SwapProvider> NodesSwappedThrough(Node node)
{
var providerByPubKey = new Dictionary<string, SwapProvider>(StringComparer.OrdinalIgnoreCase);
foreach (var (provider, _) in Weighted(node))
{
foreach (var pubKey in NodePubKeysOf(provider))
{
providerByPubKey.TryAdd(pubKey, provider);
}
}

return providerByPubKey;
}

private static IReadOnlySet<string> NodePubKeysOf(SwapProvider provider) => provider switch
{
SwapProvider.Loop => Constants.LOOP_NODE_PUBKEYS,
SwapProvider.FortySwap => Constants.FORTYSWAP_NODE_PUBKEYS,
SwapProvider.Spark => Constants.SPARK_NODE_PUBKEYS,
_ => throw new ArgumentOutOfRangeException(nameof(provider), provider, "Unknown swap provider")
};

/// <summary><paramref name="node"/>'s max routing fee ratio for <paramref name="provider"/>'s swaps.</summary>
public static decimal MaxRoutingFeeRatioFor(Node node, SwapProvider provider) => provider switch
{
Expand Down
Loading
Loading