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
14 changes: 3 additions & 11 deletions src/Jobs/AutoLiquidityManagementJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,22 +121,14 @@ public async Task Execute(IJobExecutionContext context)
}

/// <summary>The providers with a weight; all weights at 0 means Loop, as before.</summary>
private List<(SwapProvider Provider, int Weight)> WeightedProviders(Node node)
private IReadOnlyList<(SwapProvider Provider, int Weight)> WeightedProviders(Node node)
{
var weights = new List<(SwapProvider Provider, int Weight)>
{
(SwapProvider.Loop, node.LoopSwapWeight),
(SwapProvider.FortySwap, node.FortySwapWeight),
(SwapProvider.Spark, node.SparkSwapWeight)
};

if (weights.All(w => w.Weight <= 0))
if (node is { LoopSwapWeight: <= 0, FortySwapWeight: <= 0, SparkSwapWeight: <= 0 })
{
_logger.LogWarning("Node {NodeName} has total weight of 0, defaulting to Loop", node.Name);
return [(SwapProvider.Loop, 1)];
}

return weights.Where(w => w.Weight > 0).ToList();
return SwapProviderLimits.Weighted(node);
}

/// <summary>
Expand Down
152 changes: 120 additions & 32 deletions src/Pages/ChannelRequests.razor
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
@using Google.Protobuf
@using NBXplorer.Models
@using NodeGuard.Helpers;
@using NodeGuard.Services.Spark
@using System.Net
@attribute [Authorize(Roles = "FinanceManager, Superadmin, NodeManager")]

<PageTitle>Channel Requests</PageTitle>
Expand Down Expand Up @@ -565,11 +567,20 @@
<ConfirmationModal
@ref="_approveOperationConfirmationModal"
Title="Are you sure?"
Body="You selected a hot wallet. This means that the system will automatically use the funds in it without the need of manual approval. Are you sure you want to perform this operation?"
Body="@($"You selected a hot wallet. This means that the system will automatically use the funds in it without the need of manual approval. Are you sure you want to perform this operation?{(_swapOutWarning == null ? "" : $"<br/><br/>{_swapOutWarning}")}")"
OkLabel="Yes, I am sure"
OnCancel="@ApproveOperationCloseConfirmationModal"
OnSubmit="@ApproveOperationSubmitConfirmationModal"/>

<ConfirmationModal
@ref="_swapOutConfirmationModal"
Title="Swap-out warning"
Body="@(_swapOutWarning ?? "")"
OkLabel="Open anyway"
OkDisabled="@_createInFlight"
OnCancel="@SwapOutCloseConfirmationModal"
OnSubmit="@SwapOutSubmitConfirmationModal"/>

<ConfirmationModal
@ref="_markRequestAsFailedConfirmationModal"
Title="Are you sure?"
Expand Down Expand Up @@ -597,6 +608,7 @@
@inject IAuditService AuditService
@inject IHttpContextAccessor HttpContextAccessor
@inject IApplicationUserRepository ApplicationUserRepository
@inject SparkSettings SparkSettings

@code {
private List<ChannelOperationRequest>? _channelRequests;
Expand Down Expand Up @@ -637,6 +649,10 @@
private bool _createInFlight;
private ConfirmationModal _approveOperationConfirmationModal;
private ConfirmationModal _markRequestAsFailedConfirmationModal;
private ConfirmationModal _swapOutConfirmationModal;
// Why the open request being created would be swapped right back out, or null when it would not.
private string? _swapOutWarning;
private static readonly TimeSpan SwapOutBalanceTimeout = TimeSpan.FromSeconds(5);
private UTXOSelectorModal _utxoSelectorModalRef;
private List<UTXO> _selectedUTXOs = new();
private MempoolRecommendedFeesType _selectedMempoolRecommendedFeesType;
Expand Down Expand Up @@ -901,45 +917,25 @@
};

var selectedWallet = await WalletRepository.GetById(_selectedWalletId.Value);
_swapOutWarning = await SwapOutWarningAsync(request);


if (selectedWallet.IsHotWallet)
if (selectedWallet.IsHotWallet || _swapOutWarning != null)
{
_selectedRequest = request;
await datagridRef.Edit(null);
await _approveOperationConfirmationModal.ShowModal();
if (selectedWallet.IsHotWallet)
{
await _approveOperationConfirmationModal.ShowModal();
}
else
{
await _swapOutConfirmationModal.ShowModal();
}
await ResetChannelRequestRejectModal();
return;
}

var createChannelResult = await ChannelOperationRequestRepository.AddAsync(request);

if (createChannelResult.Item1)
{
ToastService.ShowSuccess("Open channel request created!");
await AuditService.LogAsync(
AuditActionType.Create,
AuditEventType.Success,
AuditObjectType.ChannelOperationRequest,
request.Id.ToString(),
new { Amount = amount, SourceNodeId = _selectedSourceNodeId, DestNodeId = _selectedDestNode?.Id, Description = $"Channel open request created. Amount: {amount} BTC, SourceNodeId: {_selectedSourceNodeId}, DestNodeId: {_selectedDestNode?.Id}" });

if (_selectedUTXOs.Count > 0)
{
await CoinSelectionService.LockUTXOs(_selectedUTXOs, request, BitcoinRequestType.ChannelOperation);
}
}
else
{
ToastService.ShowError(createChannelResult.Item2);
await AuditService.LogAsync(
AuditActionType.Create,
AuditEventType.Failure,
AuditObjectType.ChannelOperationRequest,
null,
new { Error = createChannelResult.Item2, Description = $"Failed to create channel open request. Error: {createChannelResult.Item2}" });
}
_utxoSelectorModalRef.ClearModal();
await CreateOpenRequestAsync(request);
}
else
{
Expand All @@ -952,6 +948,98 @@
await ReloadAllRequestsGrid();
}

/// <summary>
/// Creates a cold-wallet open request and locks its selected UTXOs.
/// </summary>
private async Task CreateOpenRequestAsync(ChannelOperationRequest request)
{
var amount = new Money(request.SatsAmount).ToUnit(MoneyUnit.BTC);
var createChannelResult = await ChannelOperationRequestRepository.AddAsync(request);

if (createChannelResult.Item1)
{
ToastService.ShowSuccess("Open channel request created!");
await AuditService.LogAsync(
AuditActionType.Create,
AuditEventType.Success,
AuditObjectType.ChannelOperationRequest,
request.Id.ToString(),
new { Amount = amount, SourceNodeId = request.SourceNodeId, DestNodeId = request.DestNodeId, Description = $"Channel open request created. Amount: {amount} BTC, SourceNodeId: {request.SourceNodeId}, DestNodeId: {request.DestNodeId}" });

if (_selectedUTXOs.Count > 0)
{
await CoinSelectionService.LockUTXOs(_selectedUTXOs, request, BitcoinRequestType.ChannelOperation);
}
}
else
{
ToastService.ShowError(createChannelResult.Item2);
await AuditService.LogAsync(
AuditActionType.Create,
AuditEventType.Failure,
AuditObjectType.ChannelOperationRequest,
null,
new { Error = createChannelResult.Item2, Description = $"Failed to create channel open request. Error: {createChannelResult.Item2}" });
}
_utxoSelectorModalRef.ClearModal();
}

/// <summary>
/// The warning to show when the automatic swap-out would take the outbound of the channel <paramref name="request"/>
/// opens from its source node, or null when it would not or the node's balance can't be read within
/// <see cref="SwapOutBalanceTimeout"/>.
/// </summary>
private async Task<string?> SwapOutWarningAsync(ChannelOperationRequest request)
{
var node = await NodeRepository.GetById(request.SourceNodeId, false);
if (node == null || !SwapOutForecast.SwapsOutAutomatically(node)) return null;

// The node's LND gets no deadline of its own: an unreachable one must not hold the Save button
Lnrpc.ChannelBalanceResponse? balance;
try
{
balance = await LightningService.ChannelBalanceAsync(node).WaitAsync(SwapOutBalanceTimeout);
}
catch (TimeoutException)
{
return null;
}
if (balance == null) return null;

var localBalanceSats = (long)(balance.LocalBalance?.Sat ?? 0) + (long)(balance.PendingOpenLocalBalance?.Sat ?? 0);
if (SwapOutForecast.SatsSwappedAfterOpen(node, localBalanceSats, request.SatsAmount, SparkSettings) is not { } swappedSats) return null;

var balanceAfterBtc = new Money(localBalanceSats + request.SatsAmount).ToUnit(MoneyUnit.BTC);
var thresholdBtc = new Money(node.MinimumBalanceThresholdSats).ToUnit(MoneyUnit.BTC);
var swappedBtc = new Money(swappedSats).ToUnit(MoneyUnit.BTC);
return $"Opening this channel takes {WebUtility.HtmlEncode(node.Name)}'s local balance to {balanceAfterBtc:f8} BTC, above its {thresholdBtc:f8} BTC swap-out threshold. " +
$"Automatic liquidity management would swap out up to {swappedBtc:f8} BTC of this channel's outbound liquidity: you would pay swap fees and lose that outbound. Open it anyway?";
}

private async Task SwapOutCloseConfirmationModal()
{
await _swapOutConfirmationModal.CloseModal();
}

private async Task SwapOutSubmitConfirmationModal()
{
if (_selectedRequest == null || _createInFlight) return;
_createInFlight = true;

try
{
await CreateOpenRequestAsync(_selectedRequest);
await _swapOutConfirmationModal.CloseModal();
await LoadData();
await FetchRequests();
await ReloadAllRequestsGrid();
}
finally
{
_createInFlight = false;
}
}

#endregion

private static bool RequestPendingFilter(ChannelOperationRequest req)
Expand Down
75 changes: 75 additions & 0 deletions src/Services/SwapOutForecast.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* 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;
using NodeGuard.Services.Spark;

namespace NodeGuard.Services;

/// <summary>
/// What the automatic swap-out (<c>AutoLiquidityManagementJob</c>) would take from a node's new outbound after a channel
/// open, by the same rule it swaps by.
/// </summary>
public static class SwapOutForecast
{
/// <summary>
/// The sats of a <paramref name="channelSats"/> channel opened from <paramref name="node"/> that the automatic
/// swap-out would take, or null when it would not swap. It swaps when <see cref="SwapsOutAutomatically"/> and the
/// excess, the node's local balance after the open (<paramref name="localBalanceSats"/>, before the open, plus the
/// channel) over its threshold, fits a weighted provider the job can pick (see <see cref="CanSwap"/>).
/// What only delays a swap is left out: swaps in flight, the budget spent this period, a busy or full Spark wallet.
/// </summary>
public static long? SatsSwappedAfterOpen(Node node, long localBalanceSats, long channelSats, SparkSettings spark)
{
if (!SwapsOutAutomatically(node))
{
return null;
}

var excess = localBalanceSats + channelSats - node.MinimumBalanceThresholdSats;
if (excess <= 0 || !SwapProviderLimits.Weighted(node).Any(w => CanSwap(node, w.Provider, excess, spark)))
{
return null;
}

return Math.Min(channelSats, excess);
}

/// <summary>
/// Whether the automatic swap-out can swap anything for <paramref name="node"/>: enabled, with automatic liquidity
/// management on, a funds destination wallet (as <c>INodeRepository.GetAllWithAutoLiquidityEnabled</c> picks them)
/// and a swap budget above 0 (with none, every run stops at an exhausted budget).
/// </summary>
public static bool SwapsOutAutomatically(Node node) =>
!node.IsNodeDisabled && node.AutoLiquidityManagementEnabled && node.FundsDestinationWalletId.HasValue
&& node.SwapBudgetSats > 0;

/// <summary>
/// Whether <c>AutoLiquidityManagementJob</c> can swap <paramref name="excess"/> sats through
/// <paramref name="provider"/>: it runs swaps (max swaps in flight above 0), the most it may take of the excess
/// (its max swap) reaches its min swap and, for Spark, the node has a Spark wallet.
/// </summary>
private static bool CanSwap(Node node, SwapProvider provider, long excess, SparkSettings spark)
{
var limits = SwapProviderLimits.For(node, provider, spark);
return limits.MaxInFlight > 0
&& Math.Min(excess, limits.MaxSats) >= limits.MinSats
&& (provider != SwapProvider.Spark || spark.WalletFor(node) is not null);
}
}
16 changes: 16 additions & 0 deletions src/Services/SwapProviderLimits.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,22 @@ public readonly record struct SwapProviderLimits(long MinSats, long MaxSats, int
_ => throw new ArgumentOutOfRangeException(nameof(provider), provider, "Unknown swap provider")
};

/// <summary>
/// The providers <paramref name="node"/> swaps out through, with their weights: those with a weight above 0, or Loop
/// alone when none has one.
/// </summary>
public static IReadOnlyList<(SwapProvider Provider, int Weight)> Weighted(Node node)
{
var weighted = new List<(SwapProvider Provider, int Weight)>
{
(SwapProvider.Loop, node.LoopSwapWeight),
(SwapProvider.FortySwap, node.FortySwapWeight),
(SwapProvider.Spark, node.SparkSwapWeight)
}.Where(w => w.Weight > 0).ToList();

return weighted.Count > 0 ? weighted : [(SwapProvider.Loop, 1)];
}

/// <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