Skip to content

Commit

Permalink
Merge branch 'main' into fix_naming_node
Browse files Browse the repository at this point in the history
  • Loading branch information
RodriFS authored Aug 1, 2023
2 parents 269ecf1 + c0bcfe2 commit e0fb894
Show file tree
Hide file tree
Showing 7 changed files with 139 additions and 21 deletions.
12 changes: 12 additions & 0 deletions .run/Compose Deployment.run.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Compose Deployment" type="docker-deploy" factoryName="docker-compose.yml" server-name="Docker">
<deployment type="docker-compose.yml">
<settings>
<option name="envFilePath" value="" />
<option name="sourceFilePath" value="docker/docker-compose.yml" />
</settings>
</deployment>
<EXTENSION ID="com.jetbrains.rider.docker.debug" isFastModeEnabled="true" isSslEnabled="true" />
<method v="2" />
</configuration>
</component>
17 changes: 17 additions & 0 deletions .run/NodeGuard_ NodeGuard local debug.run.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="NodeGuard: NodeGuard local debug" type="LaunchSettings" factoryName=".NET Launch Settings Profile">
<option name="LAUNCH_PROFILE_PROJECT_FILE_PATH" value="$PROJECT_DIR$/src/NodeGuard.csproj" />
<option name="LAUNCH_PROFILE_TFM" value="net7.0" />
<option name="LAUNCH_PROFILE_NAME" value="NodeGuard local debug" />
<option name="USE_EXTERNAL_CONSOLE" value="0" />
<option name="USE_MONO" value="0" />
<option name="RUNTIME_ARGUMENTS" value="" />
<option name="GENERATE_APPLICATIONHOST_CONFIG" value="1" />
<option name="SHOW_IIS_EXPRESS_OUTPUT" value="0" />
<option name="SEND_DEBUG_REQUEST" value="1" />
<option name="ADDITIONAL_IIS_EXPRESS_ARGUMENTS" value="" />
<method v="2">
<option name="Build" />
</method>
</configuration>
</component>
6 changes: 3 additions & 3 deletions src/Data/Repositories/NodeRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,13 @@ public async Task<Node> GetOrCreateByPubKey(string pubKey, ILightningService lig
var foundNode = await lightningService.GetNodeInfo(pubKey);
if (foundNode == null)
{
throw new Exception("Node info not found");
_logger.LogWarning("Peer with PubKey {pubKey} not found", pubKey);
}

node = new Node()
{
Name = foundNode.Alias,
PubKey = foundNode.PubKey,
Name = foundNode?.Alias ?? "",
PubKey = pubKey
};
var addNode = await AddAsync(node);
if (!addNode.Item1)
Expand Down
11 changes: 5 additions & 6 deletions src/Jobs/ChannelMonitorJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,16 +86,16 @@ public async Task Execute(IJobExecutionContext context)
}
catch (Exception e)
{
_logger.LogError(e, "Error while subscribing for the channel updates of node {NodeId}", nodeId);
throw new JobExecutionException(e, true);
_logger.LogError(e, "Error while trying to monitor channels of node {NodeId}", nodeId);
throw new JobExecutionException(e, false);
}

_logger.LogInformation("{JobName} ended", nameof(ChannelMonitorJob));
}

public async Task RecoverGhostChannels(Node source, Node destination, Channel? channel)
public async Task RecoverGhostChannels(Node source, Node destination, Channel channel)
{
if (!channel.Initiator) return;
if (!channel.Initiator && destination.IsManaged) return;
try
{
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
Expand All @@ -114,14 +114,14 @@ public async Task RecoverGhostChannels(Node source, Node destination, Channel? c
};

var createdChannel = await LightningService.CreateChannel(source, destination.Id, parsedChannelPoint, channel.Capacity, channel.CloseAddress);
createdChannel.CreatedByNodeGuard = false;

await dbContext.Channels.AddAsync(createdChannel);
await dbContext.SaveChangesAsync();
}
catch (Exception e)
{
_logger.LogError(e, "Error while recovering ghost channel, {SourceNodeId}, {ChannelId}: {Error}", source.Id, channel?.ChanId, e);
throw new JobExecutionException(e, true);
}
}

Expand Down Expand Up @@ -149,7 +149,6 @@ public async Task RecoverChannelInConfirmationPendingStatus(Node source)
catch (Exception e)
{
_logger.LogError(e, "Error while recovering channel in OnChainConfirmationPending status, {SourceNodeId}: {Error}", source.Id, e);
throw new JobExecutionException(e, true);
}
}
}
14 changes: 11 additions & 3 deletions src/Services/LightningService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ public async Task OpenChannel(ChannelOperationRequest channelOperationRequest)
throw new InvalidOperationException();
}

var feeRate = await _nbXplorerService.GetFeesByType(channelOperationRequest.MempoolRecommendedFeesTypes) ?? channelOperationRequest.FeeRate;;
var feeRate = await _nbXplorerService.GetFeesByType(channelOperationRequest.MempoolRecommendedFeesTypes) ?? channelOperationRequest.FeeRate;
var initialFeeRate = feeRate ??
(await LightningHelper.GetFeeRateResult(network, _nbXplorerService)).FeeRate
.SatoshiPerByte;
Expand Down Expand Up @@ -692,6 +692,14 @@ public static async Task<Channel> CreateChannel(Node source, int destId, Channel
throw new InvalidOperationException($"Error, channel not found for channel point: {channelPoint}");
}

var sourceNodeId = source.Id;
var destinationNodeId = destId;
if (!currentChannel.Initiator)
{
sourceNodeId = destId;
destinationNodeId = source.Id;
}

var channel = new Channel
{
ChanId = currentChannel.ChanId,
Expand All @@ -702,8 +710,8 @@ public static async Task<Channel> CreateChannel(Node source, int destId, Channel
SatsAmount = satsAmount,
UpdateDatetime = DateTimeOffset.Now,
Status = Channel.ChannelStatus.Open,
SourceNodeId = source.Id,
DestinationNodeId = destId,
SourceNodeId = sourceNodeId,
DestinationNodeId = destinationNodeId,
CreatedByNodeGuard = true,
IsPrivate = currentChannel.Private
};
Expand Down
5 changes: 3 additions & 2 deletions test/NodeGuard.Tests/Data/Repositories/NodeRepositoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,17 @@ public async Task AddsNewNode_WhenRemoteNodeNotFound()
var lightningServiceMock = new Mock<ILightningService>();
var repositoryMock = new Mock<IRepository<Node>>();

var node = new LightningNode() { Alias = "TestAlias", PubKey = "TestPubKey" };
lightningServiceMock.Setup(service => service.GetNodeInfo(It.IsAny<string>()))
.ReturnsAsync(new LightningNode() { Alias = "TestAlias", PubKey = "TestPubKey" });
.ReturnsAsync(node);

repositoryMock.Setup(repository => repository.AddAsync(It.IsAny<Node>(), It.IsAny<ApplicationDbContext>()))
.ReturnsAsync((true, null));

var nodeRepository = new NodeRepository(repositoryMock.Object, null, dbContextFactory.Object, null);

// Act
var result = await nodeRepository.GetOrCreateByPubKey("abc", lightningServiceMock.Object);
var result = await nodeRepository.GetOrCreateByPubKey(node.PubKey, lightningServiceMock.Object);

// Assert
result.Name.Should().Be("TestAlias");
Expand Down
95 changes: 88 additions & 7 deletions test/NodeGuard.Tests/Jobs/ChannelMonitorJobTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ private Mock<IDbContextFactory<ApplicationDbContext>> SetupDbContextFactory()
}

[Fact]
public async Task RecoverGhostChannels_ChannelIsNotInitiator()
public async Task RecoverGhostChannels_ChannelIsNotInitiatorButManaged()
{
// Arrange
var dbContextFactory = SetupDbContextFactory();
Expand All @@ -41,13 +41,13 @@ public async Task RecoverGhostChannels_ChannelIsNotInitiator()
{
Initiator = false
};
var destination = new Node() { Endpoint = "abc" };
// Act
var act = () => channelMonitorJob.RecoverGhostChannels(null, null, channel);
var act = () => channelMonitorJob.RecoverGhostChannels(null, destination, channel);

// Assert
await act.Should().NotThrowAsync();
dbContextFactory.Invocations.Count.Should().Be(0);

}

[Fact]
Expand Down Expand Up @@ -80,8 +80,10 @@ public async Task RecoverGhostChannels_ChannelAlreadyExists()
dbContextFactory.Invocations.Count.Should().Be(2);
}

[Fact]
public async Task RecoverGhostChannels_CreatesChannel()
[Theory]
[InlineData("locahost")]
[InlineData(null)]
public async Task RecoverGhostChannels_CreatesChannel(string? endpoint)
{
// Arrange
var logger = new Mock<ILogger<ChannelMonitorJob>>();
Expand All @@ -100,7 +102,8 @@ public async Task RecoverGhostChannels_CreatesChannel()
ChanId = 123,
Capacity = 1000,
LocalBalance = 100,
RemoteBalance = 900
RemoteBalance = 900,
Initiator = true
}
}
};
Expand All @@ -120,10 +123,15 @@ public async Task RecoverGhostChannels_CreatesChannel()

var source = new Node()
{
Id = 1,
Endpoint = "localhost",
ChannelAdminMacaroon = "abc"
};
var destination = new Node();
var destination = new Node()
{
Id = 2,
Endpoint = endpoint
};
var channel = new Lnrpc.Channel()
{
ChanId = 1,
Expand All @@ -135,6 +143,79 @@ public async Task RecoverGhostChannels_CreatesChannel()
await channelMonitorJob.RecoverGhostChannels(source, destination, channel);

// Assert
var createdChannel = await context.Channels.FirstAsync();
createdChannel.SourceNodeId.Should().Be(source.Id);
createdChannel.DestinationNodeId.Should().Be(destination.Id);
context.Channels.Count().Should().Be(1);
LightningService.CreateLightningClient = originalLightningClient;
}

[Fact]
public async Task RecoverGhostChannels_CreatesChannelNotInitiator()
{
// Arrange
var logger = new Mock<ILogger<ChannelMonitorJob>>();
var dbContextFactory = SetupDbContextFactory();
var context = await dbContextFactory.Object.CreateDbContextAsync();
//Mock lightning client with iunmockable methods
var channelPoint = new ChannelPoint { FundingTxidBytes = ByteString.CopyFrom(Convert.FromHexString("a2dffe0545ae0ce9091949477a9a7d91bb9478eb054fd9fa142e73562287ca4e").Reverse().ToArray()), OutputIndex = 1 };

var listChannelsResponse = new ListChannelsResponse
{
Channels =
{
new Lnrpc.Channel
{
Active = true,
RemotePubkey = "03b48034270e522e4033afdbe43383d66d426638927b940d09a8a7a0de4d96e807",
ChannelPoint = $"{LightningHelper.DecodeTxId(channelPoint.FundingTxidBytes)}:{channelPoint.OutputIndex}",
ChanId = 123,
Capacity = 1000,
LocalBalance = 100,
RemoteBalance = 900,
Initiator = false
}
}
};

var lightningClient = Interceptor.For<Lightning.LightningClient>()
.Setup(x => x.ListChannelsAsync(
Arg.Ignore<ListChannelsRequest>(),
Arg.Ignore<Metadata>(),
null,
Arg.Ignore<CancellationToken>()
))
.Returns(MockHelpers.CreateAsyncUnaryCall(listChannelsResponse));
var originalLightningClient = LightningService.CreateLightningClient;
LightningService.CreateLightningClient = (_) => lightningClient;

var channelMonitorJob = new ChannelMonitorJob(logger.Object, dbContextFactory.Object, null, null, null);

var source = new Node()
{
Id = 1,
Endpoint = "localhost",
ChannelAdminMacaroon = "abc"
};
var destination = new Node()
{
Id = 2,
Endpoint = null,
};
var channel = new Lnrpc.Channel()
{
ChanId = 1,
Initiator = false,
ChannelPoint = "a2dffe0545ae0ce9091949477a9a7d91bb9478eb054fd9fa142e73562287ca4e:1"
};

// Act
await channelMonitorJob.RecoverGhostChannels(source, destination, channel);

// Assert
var createdChannel = await context.Channels.FirstAsync();
createdChannel.SourceNodeId.Should().Be(destination.Id);
createdChannel.DestinationNodeId.Should().Be(source.Id);
context.Channels.Count().Should().Be(1);
LightningService.CreateLightningClient = originalLightningClient;
}
Expand Down

0 comments on commit e0fb894

Please sign in to comment.