Skip to content
Draft
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
15 changes: 9 additions & 6 deletions docs/auto-channel-open.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,9 +216,16 @@ Applied in this order. `BindingClamp` records the last one that reduced the size
| Reserve | `target / 0.99`. LND keeps ~1% as channel reserve, which can't be used for routing. Without this the usable outbound falls short of the target. Not reported as a clamp. |
| Wumbo ceiling | 16,777,215 sats. **Regtest only.** On other networks wumbo is assumed. |
| Node max | `AutoChannelOpenMaxSizeSats` |
| Wallet | confirmed balance of the funding wallet |
| Wallet | the biggest channel the funding wallet can fund, after the funding fee and a dust change output (below) |
| Budget | remaining budget for the period (§7) |

The wallet limit (`LightningHelper.MaxFundableChannelSats`) matches the open that actually runs. That
open isn't changeless: it pays the fee on top of the channel amount and keeps a change output. So the
limit is the coins coin selection would use (no locked, frozen or dust UTXOs), minus the fee for
spending all of them into the funding output plus a change output, minus `MINIMUM_UTXO_VALUE_SATS`
(546) so the change stays above dust. NBitcoin sizes the transaction from the wallet's real scripts,
at `HourFee`, which is at or above the `EconomyFee` the funding transaction uses.

Then two checks on the final size. Failing either one means no recommendation, and the reason is
logged:

Expand Down Expand Up @@ -467,9 +474,6 @@ finished yet blocks a second one. A pending open to the same peer created by han
**Peer reachability isn't checked.** If the peer is offline, `ChannelOpenJob` fails, the
recommendation becomes `Failed`, and the next run can propose it again.

**The wallet clamp leaves no room for fees.** A plan can be sized to the wallet's full confirmed
balance, which doesn't leave enough to pay for the funding transaction.

**No coordination with the other tools.** The rebalancer may be refilling the same peer while this
proposes buying capacity for it. The only thing shared is the price: the new channel opens at what
we already charge that peer.
Expand All @@ -488,8 +492,7 @@ cost. Cost of capital and how long the channel stays open aren't considered.
2. **Payback model.** Replace the flat fee threshold with amortized cost (open + close + cost of
capital over the expected lifetime), and use the same model for sizing.
3. **Escalation ladder.** Only propose an open after rebalancing has clearly failed.
4. **Fee headroom in the wallet clamp**, and a reachability check (`ListPeers` / `ConnectPeer`)
before promoting.
4. **Reachability check** (`ListPeers` / `ConnectPeer`) before promoting.
5. **Group bursts by timelock.** Treat (burst, `OutgoingTimelock`) as one payment and take its
largest amount. First check prod data: count distinct timelocks per burst, and whether amounts
under one timelock look like halving chains or unrelated payments.
Expand Down
25 changes: 25 additions & 0 deletions src/Helpers/LightningHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
using Google.Protobuf;
using NBitcoin;
using NBXplorer;
using NBXplorer.DerivationStrategy;
using NBXplorer.Models;

namespace NodeGuard.Helpers
Expand Down Expand Up @@ -220,6 +221,30 @@ public static async Task<List<ICoin>> SelectCoins(Wallet wallet, List<UTXO> sele
.ToList();
}

/// <summary>
/// Biggest channel the coins can fund through a normal open: every coin in, the funding output
/// and a change output out, with the change kept at dust so the tx still relays.
/// </summary>
public static long MaxFundableChannelSats(DerivationStrategyBase derivationStrategy, List<UTXO> utxos, decimal feeRateSatPerVb)
{
if (utxos.Count == 0)
{
return 0;
}

// Output values don't change the size, so the amounts here are placeholders
var builder = CurrentNetworkHelper.GetCurrentNetwork().CreateTransactionBuilder();
var tx = builder.AddCoins(utxos.Select(u => u.AsCoin(derivationStrategy)))
.SendAll(new WitScriptId(uint256.Zero).ScriptPubKey)
.BuildTransaction(false);
tx.Outputs.Add(Money.Zero, utxos[0].ScriptPubKey);

var totalSats = utxos.Sum(u => ((Money)u.Value).Satoshi);
var feeSats = builder.EstimateFees(tx, new FeeRate(feeRateSatPerVb)).Satoshi;

return Math.Max(0, totalSats - feeSats - Constants.MINIMUM_UTXO_VALUE_SATS);
}

/// <summary>
/// Returns the fee rate (sat/vb) for a tx, 4 is the value in regtest
/// </summary>
Expand Down
27 changes: 18 additions & 9 deletions src/Jobs/AutoChannelOpenJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public class AutoChannelOpenJob : IJob
private readonly INBXplorerService _nbXplorerService;
private readonly IChannelOperationRequestRepository _channelOperationRequestRepository;
private readonly IAuditService _auditService;
private readonly ICoinSelectionService _coinSelectionService;

public AutoChannelOpenJob(
ILogger<AutoChannelOpenJob> logger,
Expand All @@ -62,7 +63,8 @@ public AutoChannelOpenJob(
ILightningService lightningService,
INBXplorerService nbXplorerService,
IChannelOperationRequestRepository channelOperationRequestRepository,
IAuditService auditService)
IAuditService auditService,
ICoinSelectionService coinSelectionService)
{
_logger = logger;
_nodeRepository = nodeRepository;
Expand All @@ -73,6 +75,7 @@ public AutoChannelOpenJob(
_nbXplorerService = nbXplorerService;
_channelOperationRequestRepository = channelOperationRequestRepository;
_auditService = auditService;
_coinSelectionService = coinSelectionService;
}

public async Task Execute(IJobExecutionContext context)
Expand Down Expand Up @@ -170,16 +173,16 @@ private async Task ProcessNode(Node node, decimal feeRate)
return;
}

var walletBalanceSats = await GetWalletBalanceSats(node);
if (walletBalanceSats <= 0)
var walletSpendableSats = await GetWalletSpendableSats(node, feeRate);
if (walletSpendableSats <= 0)
{
_logger.LogInformation("Node {NodeName}: funding wallet has no confirmed balance", node.Name);
_logger.LogInformation("Node {NodeName}: funding wallet has nothing spendable once the funding fee is paid", node.Name);
return;
}

var tunables = ChannelOpenInitiatorTunables.FromConstants(
node,
walletBalanceSats,
walletSpendableSats,
remainingBudget,
(long)(feeRate * EstimatedOpenCloseVBytes));

Expand Down Expand Up @@ -303,16 +306,22 @@ private async Task ProcessNode(Node node, decimal feeRate)
return failures.FirstOrDefault(x => ids.Contains(x.OutgoingChannelId))?.OutgoingPeerAlias;
}

private async Task<long> GetWalletBalanceSats(Node node)
/// <summary>
/// The biggest channel the wallet can fund from the coins coin selection would hand it, with the
/// funding fee already taken out.
/// </summary>
/// <param name="feeRate">HourFee, at or above the EconomyFee the funding tx is built at.</param>
private async Task<long> GetWalletSpendableSats(Node node, decimal feeRate)
{
if (node.AutoChannelOpenWallet == null)
var derivationStrategy = node.AutoChannelOpenWallet?.GetDerivationStrategy();
if (derivationStrategy == null)
{
return 0;
}

var balance = await _lightningService.GetWalletBalance(node.AutoChannelOpenWallet);
var utxos = await _coinSelectionService.GetAvailableUTXOsAsync(derivationStrategy);

return balance?.Confirmed is Money confirmed ? confirmed.Satoshi : 0;
return LightningHelper.MaxFundableChannelSats(derivationStrategy, utxos, feeRate);
}

/// <summary>
Expand Down
10 changes: 5 additions & 5 deletions src/Services/ChannelOpenInitiatorService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,14 @@ public record ChannelOpenInitiatorTunables(
bool AllowWumbo,
long NodeMinSizeSats,
long NodeMaxSizeSats,
long WalletBalanceSats,
long WalletSpendableSats,
long RemainingBudgetSats,
long EstimatedChainCostSats,
int MaxPlansPerRun)
{
public static ChannelOpenInitiatorTunables FromConstants(
Node node,
long walletBalanceSats,
long walletSpendableSats,
long remainingBudgetSats,
long estimatedChainCostSats) => new(
WindowHours: Constants.AUTO_CHANNEL_OPEN_WINDOW_HOURS,
Expand All @@ -78,7 +78,7 @@ public static ChannelOpenInitiatorTunables FromConstants(
AllowWumbo: CurrentNetworkHelper.GetCurrentNetwork() != Network.RegTest,
NodeMinSizeSats: node.AutoChannelOpenMinSizeSats ?? 0,
NodeMaxSizeSats: node.AutoChannelOpenMaxSizeSats ?? long.MaxValue,
WalletBalanceSats: walletBalanceSats,
WalletSpendableSats: walletSpendableSats,
RemainingBudgetSats: remainingBudgetSats,
EstimatedChainCostSats: estimatedChainCostSats,
MaxPlansPerRun: Constants.AUTO_CHANNEL_OPEN_MAX_PLANS_PER_RUN);
Expand Down Expand Up @@ -300,9 +300,9 @@ internal static (long Capacity, ChannelOpenSizingRegime Regime, ChannelOpenBindi
clamp = ChannelOpenBindingClamp.NodeMax;
}

if (target > t.WalletBalanceSats)
if (target > t.WalletSpendableSats)
{
target = t.WalletBalanceSats;
target = t.WalletSpendableSats;
clamp = ChannelOpenBindingClamp.WalletBalance;
}

Expand Down
Loading
Loading