From 87e7f272daa960ff41c001d81c92e47be815ab3b Mon Sep 17 00:00:00 2001 From: Marcos Date: Mon, 23 Nov 2026 19:05:18 +0100 Subject: [PATCH] refactor: write the swap confirmation as component markup and confirm the source node before opening a channel The swap confirmation is laid out in NewSwapModal's markup from a small record of the values it shows, instead of being assembled as a string. ConfirmationModal takes its body as text, or as child content for a formatted message. Before a channel is opened, the LND at the source node's endpoint is asked for its identity and the open only goes ahead when it is the node's pubkey. AddNode over gRPC makes the same check before adding a managed node. --- src/Rpc/NodeGuardService.cs | 10 + src/Services/LightningService.cs | 36 +++ src/Shared/ConfirmationModal.razor | 21 +- src/Shared/NewSwapModal.razor | 172 +++++++---- .../Rpc/NodeGuardServiceTests.cs | 34 +++ .../Services/LightningServiceTests.cs | 281 ++++++++++++++++++ 6 files changed, 493 insertions(+), 61 deletions(-) diff --git a/src/Rpc/NodeGuardService.cs b/src/Rpc/NodeGuardService.cs index e141b7fa..2644b5d7 100644 --- a/src/Rpc/NodeGuardService.cs +++ b/src/Rpc/NodeGuardService.cs @@ -776,6 +776,16 @@ public override async Task AddNode(AddNodeRequest request, Serv RefuseSparkWallet(await _walletRepository.GetById(request.ReturningFundsWalletId)); } + // A managed node is only added when the LND at its endpoint holds its key + if (!string.IsNullOrWhiteSpace(node.Endpoint) && !string.IsNullOrWhiteSpace(node.ChannelAdminMacaroon)) + { + var identityError = await _lightningService.GetNodeIdentityError(node); + if (identityError != null) + { + throw new RpcException(new Status(StatusCode.FailedPrecondition, identityError)); + } + } + try { var result = await _nodeRepository.AddAsync(node); diff --git a/src/Services/LightningService.cs b/src/Services/LightningService.cs index 112c037b..b4cd41f3 100644 --- a/src/Services/LightningService.cs +++ b/src/Services/LightningService.cs @@ -144,6 +144,13 @@ public interface ILightningService /// public Task GetBlockHeight(Node node); + /// + /// Checks that the LND behind the node's endpoint and macaroon is the node itself: its identity pubkey is the + /// node's. Returns null when it is, and otherwise why it could not be confirmed (a different pubkey, or the + /// LND could not be asked). + /// + public Task GetNodeIdentityError(Node node); + /// /// Lists all channels for a given node /// @@ -361,6 +368,17 @@ public async Task OpenChannel(ChannelOperationRequest channelOperationRequest) source.Name, destination.Name); + // A node's endpoint and macaroon can be edited, so the LND they lead to is asked who it is before the + // wallet funds a channel on it: otherwise the funds would open a channel on whatever node answers + var identityError = await GetNodeIdentityError(source); + if (identityError != null) + { + _logger.LogError( + "Channel open request {RequestId} refused, the source node could not be confirmed: {Reason}", + channelOperationRequest.Id, identityError); + throw new InvalidOperationException(identityError); + } + var combinedPSBT = GetCombinedPsbt(channelOperationRequest, _logger); @@ -1618,6 +1636,24 @@ public async Task> GetChannelsState() return info?.BlockHeight; } + public async Task GetNodeIdentityError(Node node) + { + if (node == null) throw new ArgumentNullException(nameof(node)); + + var info = await _lightningClientService.GetInfo(node); + if (info == null) + { + return $"The LND at {node.Endpoint} could not be asked for its identity, so it cannot be confirmed to be node {node.Name}"; + } + + if (!string.Equals(info.IdentityPubkey, node.PubKey, StringComparison.OrdinalIgnoreCase)) + { + return $"The LND at {node.Endpoint} is {info.IdentityPubkey}, not node {node.Name} ({node.PubKey})"; + } + + return null; + } + public async Task ListChannels(Node node) { if (node == null) throw new ArgumentNullException(nameof(node)); diff --git a/src/Shared/ConfirmationModal.razor b/src/Shared/ConfirmationModal.razor index 671a66ff..e3e09731 100644 --- a/src/Shared/ConfirmationModal.razor +++ b/src/Shared/ConfirmationModal.razor @@ -5,7 +5,15 @@ - @((MarkupString)Body) + @* Both are HTML-encoded by Blazor: a body never renders as raw markup *@ + @if (ChildContent is not null) + { + @ChildContent + } + else + { + @Body + } @@ -22,9 +30,18 @@ [Parameter, EditorRequired] public string Title { get; set; } = ""; - [Parameter, EditorRequired] + /// + /// The message as plain text. Use for one that needs formatting + /// + [Parameter] public string Body { get; set; } = ""; + /// + /// A formatted message, shown instead of + /// + [Parameter] + public RenderFragment? ChildContent { get; set; } + [Parameter] public string CancelLabel { get; set; } = "Cancel"; diff --git a/src/Shared/NewSwapModal.razor b/src/Shared/NewSwapModal.razor index b85489be..ced4c55e 100644 --- a/src/Shared/NewSwapModal.razor +++ b/src/Shared/NewSwapModal.razor @@ -193,10 +193,79 @@ + OnSubmit="@OnCreateSwap"> + @* Written as markup, never as an HTML string: the names and the provider's error are HTML-encoded *@ + @if (_confirmation is { } confirmation) + { + @if (confirmation.QuoteError is not null) + { + @:Quote was not successful because of the following error:

+ @confirmation.QuoteError

+ @:The swap will be created with the following details:

+ } + else + { + @:You are about to create a new swap with the following details:

+ } + + - Provider: @confirmation.Provider
+ - Direction: @confirmation.Direction
+ - Amount: @confirmation.Amount
+ - Origin Node: @confirmation.NodeName
+ - Destination Wallet: @confirmation.WalletName

+ + @if (confirmation.QuoteError is not null) + { + The fees could not be estimated. Default values will be used.

+
+ } + else if (confirmation.Quote is { } quote) + { + - Estimated Fees:
+
    +
  • Service Fee: @quote.ServiceFee
  • + @if (quote.SelectedServiceFee is not null) + { +
  • (You selected: @quote.SelectedServiceFee, it might not go through)
  • + } +
  • Off-Chain Fee: @quote.OffChainFee
  • + @if (quote.SelectedRoutingFee is not null) + { +
  • (You selected: @quote.SelectedRoutingFee, it might not go through)
  • + } +
  • On-Chain Fee: @quote.OnChainFee
  • +
  • Total: @quote.TotalFees
  • +
+
+ - Estimated total cost: @quote.TotalCost
+ @if (!quote.CouldEstimateRoutingFees) + { +
Warning: Routing fees could not be estimated. The actual fees will be higher than 0.

+ } +
+ } + else if (confirmation.Spark is { } spark) + { + - Maximum fees:
+
    +
  • Off-Chain Fee: up to @spark.MaxRoutingFee
  • +
  • Service Fee: Spark's fixed @SparkSwapService.ServiceFeeBps bps (@FeeFormat.Percent(SparkSwapService.ServiceFeeBps * 100L)), charged on the Lightning route: part of the off-chain fee
  • +
  • On-Chain Fee (from Spark to L1: the SSP's exit fee and the L1 broadcast): up to @spark.MaxExitFee
  • +

+ @:The node starts paying its Spark wallet (@spark.Identity) as you confirm, and LND keeps + @:trying routes for up to @spark.PaymentTimeoutMinutes minutes (the node's Spark payment timeout); + @:the swap shows as pending on the Swaps page meanwhile. + @:Once paid, the swap waits in the Spark wallet until the wallet is full (no room left for another swap under its max balance), + @:then exits with the wallet's other paid swaps in one on-chain transaction to the destination wallet, sharing its fee, + @:at exit speed @SparkSettings.ExitSpeedSummary. + @:Up to @spark.MaxSwapsInFlight Spark swaps of @confirmation.NodeName (its Spark max swaps in flight) are paid at once.

+ } + + @:Please confirm that you want to proceed. + } +
@inject ISwapsService SwapsService @inject IToastService ToastService @@ -230,7 +299,18 @@ private string? _noSparkNodesReason; private Node? _selectedNode; private string? _amountInNodeBtc; - private string _confirmationModalBody = string.Empty; + private SwapConfirmation? _confirmation; + + /// What the confirmation shows: the swap, plus its quote, the error of a failed quote or Spark's caps + private sealed record SwapConfirmation(string Provider, string Direction, string Amount, string? NodeName, string? WalletName, + string? QuoteError = null, QuotedFees? Quote = null, SparkCaps? Spark = null); + + /// The selected fees are only set when the quoted fee is above what the user selected + private sealed record QuotedFees(string ServiceFee, string? SelectedServiceFee, string OffChainFee, string? SelectedRoutingFee, + string OnChainFee, string TotalFees, string TotalCost, bool CouldEstimateRoutingFees); + + private sealed record SparkCaps(string MaxRoutingFee, string MaxExitFee, string? Identity, int PaymentTimeoutMinutes, + int MaxSwapsInFlight); private decimal _btcPrice; private bool _showAdvancedOptions = false; private int _swapPublicationDeadlineOffsetMinutes = Constants.IS_DEV_ENVIRONMENT ? 1 : 30; @@ -421,28 +501,20 @@ var HTLC_SWEEP_FEE_SAT_ON_QUOTE_ERROR = _amountBtc * EnvironmentHelpers.GetOrDefault("HTLC_SWEEP_FEE_SAT_ON_QUOTE_ERROR", 0.015m); var PREPAY_AMT_SAT_ON_QUOTE_ERROR = _amountBtc * EnvironmentHelpers.GetOrDefault("PREPAY_AMT_SAT_ON_QUOTE_ERROR", 0.005m); - var middleChunkMessage = $"- Provider: {_selectedProvider.GetDisplayName()}
" + - $"- Direction: {_selectedDirection}
" + - $"- Amount: {FormatBtcWithUsd(_amountBtc)}
" + - $"- Origin Node: {_selectedNode?.Name}
" + - $"- Destination Wallet: {_selectedWallet?.Name}

"; - ArgumentNullException.ThrowIfNull(_selectedWallet, nameof(_selectedWallet)); ArgumentNullException.ThrowIfNull(_selectedNode, nameof(_selectedNode)); + var swap = new SwapConfirmation(_selectedProvider.GetDisplayName(), _selectedDirection.ToString(), + FormatBtcWithUsd(_amountBtc), _selectedNode.Name, _selectedWallet.Name); + if (_selectedProvider == SwapProvider.Spark) { - await ShowSparkConfirmationModal(middleChunkMessage); + await ShowSparkConfirmationModal(swap); return; } var showErrorModal = async (string errorMessage) => { - _confirmationModalBody = "Quote was not successful because of the following error:

" + - $"{errorMessage}" + "

" + - "The swap will be created with the following details:

" + - middleChunkMessage + - "The fees could not be estimated. Default values will be used.

" + - "
Please confirm that you want to proceed."; + _confirmation = swap with { QuoteError = errorMessage }; var data = new Dictionary { @@ -466,36 +538,25 @@ var onChainFee = new Money(quote.OnChainFees); var totalFees = new Money(quote.ServiceFees + quote.OffChainFees + quote.OnChainFees); - var selectedServiceFee = _maxServiceFeesPercent * _amountBtc / 100; - var serviceFeeChunkMessage = $"
  • Service Fee: {FormatBtcWithUsd(serviceFee.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(serviceFee)})
  • "; - if (serviceFee.ToUnit(MoneyUnit.BTC) > selectedServiceFee) { - serviceFeeChunkMessage += $"
  • (You selected: {FormatBtcWithUsd(selectedServiceFee)}, it might not go through)
  • "; - } + string WithPercent(Money fee) => $"{FormatBtcWithUsd(fee.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(fee)})"; + var selectedServiceFee = _maxServiceFeesPercent * _amountBtc / 100; var selectedRoutingFee = _maxRoutingFeesPercent * _amountBtc / 100; - var routingFeeChunkMessage = $"
  • Off-Chain Fee: {FormatBtcWithUsd(offChainFee.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(offChainFee)})
  • "; - if (offChainFee.ToUnit(MoneyUnit.BTC) > selectedRoutingFee) { - routingFeeChunkMessage += $"
  • (You selected: {FormatBtcWithUsd(selectedRoutingFee)}, it might not go through)
  • "; - } + var totalFeesBtc = FormatBtcWithUsd(totalFees.ToUnit(MoneyUnit.BTC)); - _confirmationModalBody = $"You are about to create a new swap with the following details:

    " + - middleChunkMessage + - $"- Estimated Fees:
    " + - "
      "+ - serviceFeeChunkMessage + - routingFeeChunkMessage + - $"
    • On-Chain Fee: {FormatBtcWithUsd(onChainFee.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(onChainFee)})
    • " + - $"
    • Total: {FormatBtcWithUsd(totalFees.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(totalFees)})
    • " + - "
    "+ - "
    " + - $"- Estimated total cost: {FormatBtcWithUsd(totalFees.ToUnit(MoneyUnit.BTC))} (Percentage of total swap: {Math.Round(totalFees.ToUnit(MoneyUnit.BTC) / _amountBtc * 100, 2)}%)
    "; - - if (!quote.CouldEstimateRoutingFees) + _confirmation = swap with { - _confirmationModalBody += "
    " + $"Warning: Routing fees could not be estimated. The actual fees will be higher than 0.

    "; - } - - _confirmationModalBody += $"
    Please confirm that you want to proceed."; + Quote = new QuotedFees( + ServiceFee: WithPercent(serviceFee), + SelectedServiceFee: serviceFee.ToUnit(MoneyUnit.BTC) > selectedServiceFee ? FormatBtcWithUsd(selectedServiceFee) : null, + OffChainFee: WithPercent(offChainFee), + SelectedRoutingFee: offChainFee.ToUnit(MoneyUnit.BTC) > selectedRoutingFee ? FormatBtcWithUsd(selectedRoutingFee) : null, + OnChainFee: WithPercent(onChainFee), + TotalFees: WithPercent(totalFees), + TotalCost: $"{totalFeesBtc} (Percentage of total swap: {Math.Round(totalFees.ToUnit(MoneyUnit.BTC) / _amountBtc * 100, 2)}%)", + CouldEstimateRoutingFees: quote.CouldEstimateRoutingFees) + }; + var data = new Dictionary { { "HtlcSweepFeeSat", quote.HtlcSweepFeeSat }, @@ -519,28 +580,21 @@ /// Spark has no up-front quote: the SSP quotes its exit fee for the leaves the payment brings in, so the /// confirmation shows the caps the swap runs under instead /// - private async Task ShowSparkConfirmationModal(string middleChunkMessage) + private async Task ShowSparkConfirmationModal(SwapConfirmation swap) { var maxRoutingFee = new Money(_maxRoutingFeesPercent * _amountBtc / 100, MoneyUnit.BTC); var maxExitFee = new Money(SparkSettings.MaxExitFeeSats); var maxSwapsInFlight = Math.Max(_selectedNode?.SparkMaxSwapsInFlight ?? 0, 1); - _confirmationModalBody = "You are about to create a new swap with the following details:

    " + - middleChunkMessage + - "- Maximum fees:
    " + - "
      " + - $"
    • Off-Chain Fee: up to {FormatBtcWithUsd(maxRoutingFee.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(maxRoutingFee)})
    • " + - $"
    • Service Fee: Spark's fixed {SparkSwapService.ServiceFeeBps} bps ({FeeFormat.Percent(SparkSwapService.ServiceFeeBps * 100L)}), charged on the Lightning route: part of the off-chain fee
    • " + - $"
    • On-Chain Fee (from Spark to L1: the SSP's exit fee and the L1 broadcast): up to {FormatBtcWithUsd(maxExitFee.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(maxExitFee)})
    • " + - "

    " + - $"The node starts paying its Spark wallet ({SparkIdentityOf(_selectedNode!)}) as you confirm, and LND keeps " + - $"trying routes for up to {SparkSettings.PaymentTimeoutFor(_selectedNode!)} minutes (the node's Spark payment timeout); " + - "the swap shows as pending on the Swaps page meanwhile. " + - "Once paid, the swap waits in the Spark wallet until the wallet is full (no room left for another swap under its max balance), " + - "then exits with the wallet's other paid swaps in one on-chain transaction to the destination wallet, sharing its fee, " + - $"at exit speed {SparkSettings.ExitSpeedSummary}. " + - $"Up to {maxSwapsInFlight} Spark swaps of {_selectedNode?.Name} (its Spark max swaps in flight) are paid at once.

    " + - "Please confirm that you want to proceed."; + _confirmation = swap with + { + Spark = new SparkCaps( + MaxRoutingFee: $"{FormatBtcWithUsd(maxRoutingFee.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(maxRoutingFee)})", + MaxExitFee: $"{FormatBtcWithUsd(maxExitFee.ToUnit(MoneyUnit.BTC))} ({PercentOfAmount(maxExitFee)})", + Identity: SparkIdentityOf(_selectedNode!), + PaymentTimeoutMinutes: SparkSettings.PaymentTimeoutFor(_selectedNode!), + MaxSwapsInFlight: maxSwapsInFlight) + }; await _confirmationModal.ShowModal(new Dictionary { diff --git a/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs b/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs index b1a6e2f8..c516491d 100644 --- a/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs +++ b/test/NodeGuard.Tests/Rpc/NodeGuardServiceTests.cs @@ -1860,6 +1860,40 @@ public async Task AddNode_ValidRequest_AddsNodeAndReturnsResponse() htlcMonitoringSchedulerMock.Verify(x => x.EnsureNodeWorkerScheduled(It.IsAny()), Times.Once); } + [Fact] + public async Task AddNode_EndpointAnsweredByAnotherLnd_IsRefusedAndNotAdded() + { + // Arrange + var nodeRepositoryMock = new Mock(); + var htlcMonitoringSchedulerMock = CreateHtlcMonitoringSchedulerMock(); + var lightningServiceMock = new Mock(); + lightningServiceMock.Setup(x => x.GetNodeIdentityError(It.IsAny())) + .ReturnsAsync("The LND at endpoint is otherPubKey, not node nodeName (pubKey)"); + + var service = CreateNodeGuardService( + nodeRepository: nodeRepositoryMock.Object, + schedulerFactory: GetSchedulerFactoryMock(), + lightningService: lightningServiceMock.Object, + htlcMonitoringScheduler: htlcMonitoringSchedulerMock.Object); + + var request = new AddNodeRequest + { + PubKey = "pubKey", + Name = "nodeName", + ChannelAdminMacaroon = "channelAdminMacaroon", + Endpoint = "endpoint", + ReturningFundsWalletId = 1, + }; + + // Act + var act = () => service.AddNode(request, new Mock().Object); + + // Assert + (await act.Should().ThrowAsync()).Which.StatusCode.Should().Be(StatusCode.FailedPrecondition); + nodeRepositoryMock.Verify(repo => repo.AddAsync(It.IsAny()), Times.Never); + htlcMonitoringSchedulerMock.Verify(x => x.EnsureNodeWorkerScheduled(It.IsAny()), Times.Never); + } + [Fact] public async Task AddNode_FailedToAddNode_ReturnsInternalError() { diff --git a/test/NodeGuard.Tests/Services/LightningServiceTests.cs b/test/NodeGuard.Tests/Services/LightningServiceTests.cs index ec074652..4f21184c 100644 --- a/test/NodeGuard.Tests/Services/LightningServiceTests.cs +++ b/test/NodeGuard.Tests/Services/LightningServiceTests.cs @@ -411,6 +411,8 @@ public async Task OpenChannel_SuccessLegacyMultiSig() .Returns(Task.FromResult(nodes)); var lightningClientService = new Mock(); + lightningClientService.Setup(x => x.GetInfo(It.IsAny(), It.IsAny())) + .ReturnsAsync((Node node, Lightning.LightningClient _) => new GetInfoResponse { IdentityPubkey = node.PubKey }); lightningClientService.Setup(x => x.GetNodeInfo(It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync( new LightningNode() { @@ -604,6 +606,8 @@ public async Task OpenChannel_SuccessMultiSig() .Returns(Task.FromResult(nodes)); var lightningClient = new Mock(); + lightningClient.Setup(x => x.GetInfo(It.IsAny(), It.IsAny())) + .ReturnsAsync((Node node, Lightning.LightningClient _) => new GetInfoResponse { IdentityPubkey = node.PubKey }); lightningClient .Setup(x => x.GetNodeInfo( It.IsAny(), @@ -818,6 +822,8 @@ public async Task OpenChannel_FailsWhenFundedInputsSpent() .Returns(Task.FromResult(nodes)); var lightningClient = new Mock(); + lightningClient.Setup(x => x.GetInfo(It.IsAny(), It.IsAny())) + .ReturnsAsync((Node node, Lightning.LightningClient _) => new GetInfoResponse { IdentityPubkey = node.PubKey }); lightningClient .Setup(x => x.GetNodeInfo( It.IsAny(), @@ -1090,6 +1096,8 @@ public async Task OpenChannel_SuccessSingleSigBip39() .Returns(Task.FromResult(nodes)); var lightningClient = new Mock(); + lightningClient.Setup(x => x.GetInfo(It.IsAny(), It.IsAny())) + .ReturnsAsync((Node node, Lightning.LightningClient _) => new GetInfoResponse { IdentityPubkey = node.PubKey }); lightningClient .Setup(x => x.GetNodeInfo( It.IsAny(), @@ -1310,6 +1318,8 @@ public async Task OpenChannel_FailedIncorrectNumberOfHumanSigs() .Returns(Task.FromResult(nodes)); var lightningClient = new Mock(); + lightningClient.Setup(x => x.GetInfo(It.IsAny(), It.IsAny())) + .ReturnsAsync((Node node, Lightning.LightningClient _) => new GetInfoResponse { IdentityPubkey = node.PubKey }); lightningClient .Setup(x => x.GetNodeInfo( It.IsAny(), @@ -1465,6 +1475,275 @@ public async Task OpenChannel_FailedIncorrectNumberOfHumanSigs() await act.Should().ThrowAsync(); } + [Fact] + public async Task OpenChannel_SourceNodeAnsweredByAnotherLnd_IsRefusedBeforeFunding() + { + // Arrange + Environment.SetEnvironmentVariable("NBXPLORER_URI", "http://10.0.0.2:38762"); + var dbContextFactory = new Mock>(); + + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: "ChannelOpenDb") + .Options; + var context = new ApplicationDbContext(options); + dbContextFactory.Setup(x => x.CreateDbContextAsync(default)).ReturnsAsync(context); + var channelOperationRequestRepository = new Mock(); + var nodeRepository = new Mock(); + + var channelOpReqPsbts = new List(); + var userSignedPSBT = + "cHNidP8BAF4BAAAAAfxbrSOgX+b0TEE/+djT9eYQrMqkbB0oS5eACIYo69ilAQAAAAD/////AYSRNXcAAAAAIgAgknIr2R4V8Bi4hnqXM/qI2ZXEy9MNhs8bc7M8k6KHNCAAAAAATwEENYfPAy8RJCyAAAAB/DvuQjoBjOttImoGYyiO0Pte4PqdeQqzcNAw4Ecw5sgDgI4uHNSCvdBxlpQ8WoEz0WmvhgIra7A4F3FkTsB0RNcQH8zk3jAAAIABAACAAQAAgE8BBDWHzwNWrAP0gAAAAfkIrkpmsP+hqxS1WvDOSPKnAiXLkBCQLWkBr5C5Po+BAlGvFeBbuLfqwYlbP19H/+/s2DIaAu8iKY+J0KIDffBgEGDzoLMwAACAAQAAgAEAAIBPAQQ1h88DfblGjQAAAACA3rcaovFO7X83IvRJXhrQefWfwPOD5bJ72dtvXpkhIAOv6z6lwqcNxKoocpZKXi/xFyrzRmob/tA5tiZlSX/FRhDtAhDIMAAAgAEAAIAAAAAAAAEBKwCUNXcAAAAAIgAg0KnQhQLDgpnwn8miRsBXVMFC0ribpYvNSiY/lUGGzM4iAgLYVMVgz+bATgvrRDQbanlASVXtiUwPt9yCgkQfv2kssUcwRAIgQMEU4f0gB9/Sgiw79s3Ug0BO201upuwiKqoUv6/svesCIGmKmt82DHfnLJsbKD7e2y4xEbc/Z1L/kMMkf4zQXuZLAgEDBAIAAAABBWlSIQLYVMVgz+bATgvrRDQbanlASVXtiUwPt9yCgkQfv2kssSEDAmf/CxGXSG9xiPljcG/e5CXFnnukFn0pJ64Q9U2aNL8hA2/OK1mLPmSxkVJC5GJuM8/inCj45Y6pksEvbHlmsVWpU64iBgLYVMVgz+bATgvrRDQbanlASVXtiUwPt9yCgkQfv2kssRgfzOTeMAAAgAEAAIABAACAAAAAAAAAAAAiBgMCZ/8LEZdIb3GI+WNwb97kJcWee6QWfSknrhD1TZo0vxhg86CzMAAAgAEAAIABAACAAAAAAAAAAAAiBgNvzitZiz5ksZFSQuRibjPP4pwo+OWOqZLBL2x5ZrFVqRjtAhDIMAAAgAEAAIAAAAAAAAAAAAAAAAAAAA=="; + channelOpReqPsbts.Add(new ChannelOperationRequestPSBT() + { + PSBT = userSignedPSBT, + }); + + //Lets add a second signed "human" PSBT + + channelOpReqPsbts.Add(new ChannelOperationRequestPSBT() + { + PSBT = userSignedPSBT, + }); + + var destinationNode = new Node() + { + PubKey = "03485d8dcdd149c87553eeb80586eb2bece874d412e9f117304446ce189955d375", + ChannelAdminMacaroon = "def", + Endpoint = "10.0.0.2" + }; + + var wallet = CreateWallet.MultiSig(_internalWallet); + var operationRequest = new ChannelOperationRequest + { + RequestType = OperationRequestType.Open, + SourceNode = new Node() + { + PubKey = "03b48034270e522e4033afdbe43383d66d426638927b940d09a8a7a0de4d96e807", + ChannelAdminMacaroon = "abc", + Endpoint = "10.0.0.1" + }, + DestNode = destinationNode, + Wallet = wallet, + ChannelOperationRequestPsbts = channelOpReqPsbts, + }; + + channelOperationRequestRepository + .Setup(x => x.GetById(It.IsAny())) + .ReturnsAsync(operationRequest); + + var nodes = new List { destinationNode }; + + nodeRepository + .Setup(x => x.GetAllManagedByNodeGuard(It.IsAny())) + .Returns(Task.FromResult(nodes)); + + var lightningClient = new Mock(); + lightningClient.Setup(x => x.GetInfo(It.IsAny(), It.IsAny())) + .ReturnsAsync((Node node, Lightning.LightningClient _) => new GetInfoResponse { IdentityPubkey = node.PubKey }); + lightningClient + .Setup(x => x.GetNodeInfo( + It.IsAny(), + It.IsAny(), + It.IsAny() + )) + .ReturnsAsync( + new LightningNode() + { + Addresses = + { + new NodeAddress() + { + Network = "tcp", + Addr = "10.0.0.2" + } + } + }); + + lightningClient + .Setup(x => x.ConnectToPeer( + It.IsAny(), + It.IsAny(), + It.IsAny() + )); + + var noneUpdate = new OpenStatusUpdate(); + var chanPendingUpdate = new OpenStatusUpdate + { + ChanPending = new PendingUpdate() + }; + var channelPoint = new ChannelPoint + { + FundingTxidBytes = + ByteString.CopyFromUtf8("e59fa8edcd772213239daef2834d9021d1aecc591d605b426ae32c4bec5fdd7d"), + OutputIndex = 1 + }; + var chanOpenUpdate = new OpenStatusUpdate + { + ChanOpen = new ChannelOpenUpdate() + { + ChannelPoint = channelPoint + } + }; + + var psbtFundUpdate = new OpenStatusUpdate + { + PsbtFund = new ReadyForPsbtFunding() + { + Psbt = ByteString.FromBase64(userSignedPSBT) + } + }; + lightningClient + .Setup(x => x.OpenChannel( + It.IsAny(), + It.IsAny(), + It.IsAny() + )) + .Returns(MockHelpers.CreateAsyncServerStreamingCall( + new List() + { + noneUpdate, + chanPendingUpdate, + psbtFundUpdate, + chanOpenUpdate + })); + + channelOperationRequestRepository + .Setup(x => x.Update(It.IsAny())) + .Returns((true, "")); + + var userSignedPsbtParsed = PSBT.Parse(userSignedPSBT, Network.RegTest); + var utxoChanges = new UTXOChanges(); + var input = userSignedPsbtParsed.Inputs[0]; + var utxoList = new List() + { + new UTXO() + { + Outpoint = input.PrevOut, + Index = 0, + ScriptPubKey = input.WitnessUtxo.ScriptPubKey, + KeyPath = new KeyPath("0/0"), + }, + }; + + utxoChanges.Confirmed = new UTXOChange() { UTXOs = utxoList }; + + var channelOperationRequestPsbtRepository = new Mock(); + channelOperationRequestPsbtRepository + .Setup(x => x.AddAsync(It.IsAny())) + .ReturnsAsync((true, "")); + + lightningClient + .Setup(x => x.FundingStateStepVerify( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny() + )); + lightningClient + .Setup(x => x.FundingStateStepFinalize( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny() + )); + + // Mock channel repository + var channelRepository = new Mock(); + + channelRepository + .Setup(x => x.GetByChanId(It.IsAny())) + .ReturnsAsync(() => null); + + //Mock List channels async + var listChannelsResponse = new ListChannelsResponse + { + Channels = + { + new Lnrpc.Channel + { + Active = true, + RemotePubkey = "03b48034270e522e4033afdbe43383d66d426638927b940d09a8a7a0de4d96e807", + ChannelPoint = + $"{LightningHelper.DecodeTxId(channelPoint.FundingTxidBytes)}:{channelPoint.OutputIndex}", + ChanId = 124, + Capacity = 1000, + LocalBalance = 100, + RemoteBalance = 900 + } + } + }; + + var lightningClientService = new Mock(); + lightningClientService.Setup(x => x.GetInfo(It.IsAny(), It.IsAny())) + .ReturnsAsync((Node node, Lightning.LightningClient _) => new GetInfoResponse { IdentityPubkey = "02c3c4d69130848ef0e2bdbc97e105597897dd8df60037cf832f050c6355e12ebe" }); + lightningClientService.Setup(x => x.ListChannels(It.IsAny(), It.IsAny())).ReturnsAsync(listChannelsResponse); + + var lightningService = new LightningService(_logger, + channelOperationRequestRepository.Object, + nodeRepository.Object, + dbContextFactory.Object, + channelOperationRequestPsbtRepository.Object, + channelRepository.Object, + null, + GetNBXplorerServiceFullyMocked(utxoChanges).Object, + null, + lightningClientService.Object, + null, null); + + // Act + var act = async () => await lightningService.OpenChannel(operationRequest); + + // Assert + await act.Should().ThrowAsync() + .WithMessage("*is 02c3c4d69130848ef0e2bdbc97e105597897dd8df60037cf832f050c6355e12ebe, not node*"); + lightningClientService.Verify(x => x.OpenChannel(It.IsAny(), It.IsAny(), + It.IsAny()), Times.Never); + lightningClientService.Verify(x => x.ConnectToPeer(It.IsAny(), It.IsAny(), + It.IsAny()), Times.Never); + } + + [Theory] + [InlineData("03b48034270e522e4033afdbe43383d66d426638927b940d09a8a7a0de4d96e807", true)] + [InlineData("03B48034270E522E4033AFDBE43383D66D426638927B940D09A8A7A0DE4D96E807", true)] + [InlineData("02c3c4d69130848ef0e2bdbc97e105597897dd8df60037cf832f050c6355e12ebe", false)] + public async Task GetNodeIdentityError_ComparesTheLndIdentityWithTheNodePubkey(string lndPubkey, bool isTheNode) + { + // Arrange + var node = new Node + { + Name = "carol", + PubKey = "03b48034270e522e4033afdbe43383d66d426638927b940d09a8a7a0de4d96e807", + ChannelAdminMacaroon = "abc", + Endpoint = "10.0.0.1" + }; + var client = new Mock(); + client.Setup(x => x.GetInfo(node, It.IsAny())) + .ReturnsAsync(new GetInfoResponse { IdentityPubkey = lndPubkey }); + var lightningService = new LightningService(_logger, null, null, null, null, null, null, null, null, client.Object, null, null); + + // Act + var error = await lightningService.GetNodeIdentityError(node); + + // Assert + (error == null).Should().Be(isTheNode); + } + + [Fact] + public async Task GetNodeIdentityError_LndCannotBeAsked_IsAnError() + { + // Arrange + var node = new Node { Name = "carol", PubKey = "03b4", ChannelAdminMacaroon = "abc", Endpoint = "10.0.0.1" }; + var client = new Mock(); + client.Setup(x => x.GetInfo(node, It.IsAny())).ReturnsAsync((GetInfoResponse?)null); + var lightningService = new LightningService(_logger, null, null, null, null, null, null, null, null, client.Object, null, null); + + // Act + var error = await lightningService.GetNodeIdentityError(node); + + // Assert + error.Should().Contain("could not be asked"); + } + [Fact] public async Task OpenChannel_SuccessSingleSig() { @@ -1524,6 +1803,8 @@ public async Task OpenChannel_SuccessSingleSig() .Returns(Task.FromResult(nodes)); var lightningClient = new Mock(); + lightningClient.Setup(x => x.GetInfo(It.IsAny(), It.IsAny())) + .ReturnsAsync((Node node, Lightning.LightningClient _) => new GetInfoResponse { IdentityPubkey = node.PubKey }); lightningClient .Setup(x => x.GetNodeInfo( It.IsAny(),