add more logging to blink

This commit is contained in:
Kukks
2024-01-04 09:31:35 +01:00
parent 7039e19865
commit 01b9a52636
3 changed files with 22 additions and 11 deletions

View File

@@ -9,7 +9,7 @@
<PropertyGroup> <PropertyGroup>
<Product>Blink</Product> <Product>Blink</Product>
<Description>Blink Lightning support</Description> <Description>Blink Lightning support</Description>
<Version>1.0.4</Version> <Version>1.0.5</Version>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<RootNamespace>BTCPayServer.Plugins.Blink</RootNamespace> <RootNamespace>BTCPayServer.Plugins.Blink</RootNamespace>
</PropertyGroup> </PropertyGroup>

View File

@@ -13,6 +13,7 @@ using GraphQL.Client.Http;
using GraphQL.Client.Http.Websocket; using GraphQL.Client.Http.Websocket;
using GraphQL.Client.Serializer.Newtonsoft; using GraphQL.Client.Serializer.Newtonsoft;
using Microsoft.AspNetCore.OutputCaching; using Microsoft.AspNetCore.OutputCaching;
using Microsoft.Extensions.Logging;
using NBitcoin; using NBitcoin;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
@@ -30,18 +31,20 @@ public class BlinkLightningClient : ILightningClient
public string? WalletCurrency { get; set; } public string? WalletCurrency { get; set; }
private readonly Network _network; private readonly Network _network;
public ILogger Logger;
private readonly GraphQLHttpClient _client; private readonly GraphQLHttpClient _client;
public class BlinkConnectionInit public class BlinkConnectionInit
{ {
[JsonProperty("X-API-KEY")] public string ApiKey { get; set; } [JsonProperty("X-API-KEY")] public string ApiKey { get; set; }
} }
public BlinkLightningClient(string apiKey, Uri apiEndpoint, string walletId, Network network, HttpClient httpClient) public BlinkLightningClient(string apiKey, Uri apiEndpoint, string walletId, Network network, HttpClient httpClient, ILogger logger)
{ {
_apiKey = apiKey; _apiKey = apiKey;
_apiEndpoint = apiEndpoint; _apiEndpoint = apiEndpoint;
WalletId = walletId; WalletId = walletId;
_network = network; _network = network;
Logger = logger;
_client = new GraphQLHttpClient(new GraphQLHttpClientOptions() {EndPoint = _apiEndpoint, _client = new GraphQLHttpClient(new GraphQLHttpClientOptions() {EndPoint = _apiEndpoint,
WebSocketEndPoint = WebSocketEndPoint =
new Uri("wss://" + _apiEndpoint.Host.Replace("api.", "ws.") + _apiEndpoint.PathAndQuery), new Uri("wss://" + _apiEndpoint.Host.Replace("api.", "ws.") + _apiEndpoint.PathAndQuery),
@@ -226,11 +229,11 @@ query TransactionsByPaymentHash($paymentHash: PaymentHash!, $walletId: WalletId!
return null; return null;
var initiationVia = transaction["initiationVia"]; var initiationVia = transaction["initiationVia"];
if (initiationVia["paymentHash"] == null) if (initiationVia?["paymentHash"] == null)
return null; return null;
var bolt11 = BOLT11PaymentRequest.Parse((string)initiationVia["paymentRequest"], _network); var bolt11 = BOLT11PaymentRequest.Parse((string)initiationVia["paymentRequest"], _network);
var preimage = transaction["settlementVia"]?["preImage"]?.Value<string>();
return new LightningPayment() return new LightningPayment()
{ {
Amount = bolt11.MinimumAmount, Amount = bolt11.MinimumAmount,
@@ -246,6 +249,8 @@ query TransactionsByPaymentHash($paymentHash: PaymentHash!, $walletId: WalletId!
PaymentHash = (string)initiationVia["paymentHash"], PaymentHash = (string)initiationVia["paymentHash"],
CreatedAt = DateTimeOffset.FromUnixTimeSeconds(transaction["createdAt"].Value<long>()), CreatedAt = DateTimeOffset.FromUnixTimeSeconds(transaction["createdAt"].Value<long>()),
AmountSent = bolt11.MinimumAmount, AmountSent = bolt11.MinimumAmount,
Preimage = preimage
}; };
} }
@@ -388,7 +393,7 @@ expiresIn = (int)createInvoiceRequest.Expiry.TotalMinutes
public async Task<ILightningInvoiceListener> Listen(CancellationToken cancellation = new CancellationToken()) public async Task<ILightningInvoiceListener> Listen(CancellationToken cancellation = new CancellationToken())
{ {
return new BlinkListener(_client, this); return new BlinkListener(_client, this, Logger);
} }
public class BlinkListener : ILightningInvoiceListener public class BlinkListener : ILightningInvoiceListener
@@ -397,7 +402,7 @@ expiresIn = (int)createInvoiceRequest.Expiry.TotalMinutes
private readonly Channel<LightningInvoice> _invoices = Channel.CreateUnbounded<LightningInvoice>(); private readonly Channel<LightningInvoice> _invoices = Channel.CreateUnbounded<LightningInvoice>();
private readonly IDisposable _subscription; private readonly IDisposable _subscription;
public BlinkListener(GraphQLHttpClient httpClient, BlinkLightningClient lightningClient) public BlinkListener(GraphQLHttpClient httpClient, BlinkLightningClient lightningClient, ILogger logger)
{ {
try try
{ {
@@ -443,14 +448,14 @@ expiresIn = (int)createInvoiceRequest.Expiry.TotalMinutes
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine(e); logger.LogError(e, "Error while processing detecting lightning invoice payment");
} }
}); });
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine(e); logger.LogError(e, "Error while creating lightning invoice listener");
} }
} }
public void Dispose() public void Dispose()
@@ -594,6 +599,8 @@ mutation LnInvoicePaymentSend($input: LnInvoicePaymentInput!) {
} }
} }
}; };
var bolt11Parsed = BOLT11PaymentRequest.Parse(bolt11, _network);
CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellation, CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellation,
new CancellationTokenSource(payParams?.SendTimeout ?? PayInvoiceParams.DefaultSendTimeout).Token); new CancellationTokenSource(payParams?.SendTimeout ?? PayInvoiceParams.DefaultSendTimeout).Token);
var response =(JObject) (await _client.SendQueryAsync<dynamic>(request, cts.Token)).Data.lnInvoicePaymentSend; var response =(JObject) (await _client.SendQueryAsync<dynamic>(request, cts.Token)).Data.lnInvoicePaymentSend;
@@ -612,7 +619,7 @@ mutation LnInvoicePaymentSend($input: LnInvoicePaymentInput!) {
{ {
result.Details = new PayDetails() result.Details = new PayDetails()
{ {
PaymentHash = new uint256(response["transaction"]["initiationVia"]["paymentHash"].Value<string>()), PaymentHash = bolt11Parsed.PaymentHash ?? new uint256(response["transaction"]["initiationVia"]["paymentHash"].Value<string>()),
Status = response["status"].Value<string>() switch Status = response["status"].Value<string>() switch
{ {
"ALREADY_PAID" => LightningPaymentStatus.Complete, "ALREADY_PAID" => LightningPaymentStatus.Complete,

View File

@@ -3,6 +3,7 @@ using System;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
using BTCPayServer.Lightning; using BTCPayServer.Lightning;
using Microsoft.Extensions.Logging;
using Network = NBitcoin.Network; using Network = NBitcoin.Network;
namespace BTCPayServer.Plugins.Blink; namespace BTCPayServer.Plugins.Blink;
@@ -10,10 +11,12 @@ namespace BTCPayServer.Plugins.Blink;
public class BlinkLightningConnectionStringHandler : ILightningConnectionStringHandler public class BlinkLightningConnectionStringHandler : ILightningConnectionStringHandler
{ {
private readonly IHttpClientFactory _httpClientFactory; private readonly IHttpClientFactory _httpClientFactory;
private readonly ILoggerFactory _loggerFactory;
public BlinkLightningConnectionStringHandler(IHttpClientFactory httpClientFactory) public BlinkLightningConnectionStringHandler(IHttpClientFactory httpClientFactory, ILoggerFactory loggerFactory)
{ {
_httpClientFactory = httpClientFactory; _httpClientFactory = httpClientFactory;
_loggerFactory = loggerFactory;
} }
@@ -74,7 +77,7 @@ public class BlinkLightningConnectionStringHandler : ILightningConnectionStringH
client.BaseAddress = uri; client.BaseAddress = uri;
kv.TryGetValue("wallet-id", out var walletId); kv.TryGetValue("wallet-id", out var walletId);
var bclient = new BlinkLightningClient(apiKey, uri, walletId, network, client); var bclient = new BlinkLightningClient(apiKey, uri, walletId, network, client, _loggerFactory.CreateLogger($"{nameof(BlinkLightningClient)}:{walletId}"));
(Network Network, string DefaultWalletId, string DefaultWalletCurrency) res; (Network Network, string DefaultWalletId, string DefaultWalletCurrency) res;
try try
{ {
@@ -101,6 +104,7 @@ public class BlinkLightningConnectionStringHandler : ILightningConnectionStringH
{ {
bclient.WalletId = res.DefaultWalletId; bclient.WalletId = res.DefaultWalletId;
bclient.WalletCurrency = res.DefaultWalletCurrency; bclient.WalletCurrency = res.DefaultWalletCurrency;
bclient.Logger = _loggerFactory.CreateLogger($"{nameof(BlinkLightningClient)}:{walletId}");
} }
else else
{ {