Skip to content

Commit

Permalink
Fix build warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
dennisreimann committed Jan 20, 2025
1 parent 495fa91 commit 87f9de6
Show file tree
Hide file tree
Showing 23 changed files with 220 additions and 184 deletions.
6 changes: 3 additions & 3 deletions BTCPayApp.Core/Auth/AuthStateProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ public async Task<FormResult<AcceptInviteResult>> AcceptInvite(string inviteUrl,
try
{
var response = await GetClient(serverUrl).AcceptInvite(payload, cancellation.GetValueOrDefault());
var account = await GetAccount(serverUrl, response.Email);
var account = await GetAccount(serverUrl, response.Email!);
await SetCurrentAccount(account);
var message = "Invitation accepted.";
if (response.EmailHasBeenConfirmed is true)
Expand Down Expand Up @@ -313,9 +313,9 @@ public async Task<FormResult> Register(string serverUrl, string email, string pa
else
{
var signup = response.ToObject<ApplicationUserData>();
if (signup.RequiresEmailConfirmation)
if (signup?.RequiresEmailConfirmation is true)
message += " Please confirm your email.";
if (signup.RequiresApproval)
if (signup?.RequiresApproval is true)
message += " The new account requires approval by an admin before you can log in.";
}
await SetCurrentAccount(account);
Expand Down
35 changes: 21 additions & 14 deletions BTCPayApp.Core/BTCPayServer/AppToServerHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,47 +6,54 @@ namespace BTCPayApp.Core.BTCPayServer;

public static class AppToServerHelper
{

public static LightningInvoice ToInvoice(this AppLightningPayment lightningPayment)
{
return new LightningInvoice()
return new LightningInvoice
{
Id = lightningPayment.PaymentHash.ToString(),
Id = lightningPayment.PaymentHash?.ToString(),
Amount = lightningPayment.Value,
PaymentHash = lightningPayment.PaymentHash.ToString(),
PaymentHash = lightningPayment.PaymentHash?.ToString(),
Preimage = lightningPayment.Preimage,
ExpiresAt = lightningPayment.AdditionalData[PaymentsManager.LightningPaymentExpiryKey].GetDateTimeOffset(),
PaidAt = lightningPayment.Status == LightningPaymentStatus.Complete? DateTimeOffset.UtcNow: null, //TODO: store these in ln payment
BOLT11 = lightningPayment.PaymentRequest.ToString(),
Status = lightningPayment.Status == LightningPaymentStatus.Complete? LightningInvoiceStatus.Paid: lightningPayment.PaymentRequest.ExpiryDate < DateTimeOffset.UtcNow? LightningInvoiceStatus.Expired: LightningInvoiceStatus.Unpaid,
PaidAt = lightningPayment.Status == LightningPaymentStatus.Complete
? DateTimeOffset.UtcNow
: null, //TODO: store these in ln payment
BOLT11 = lightningPayment.PaymentRequest?.ToString(),
Status = lightningPayment.Status == LightningPaymentStatus.Complete
? LightningInvoiceStatus.Paid
: lightningPayment.PaymentRequest?.ExpiryDate < DateTimeOffset.UtcNow
? LightningInvoiceStatus.Expired
: LightningInvoiceStatus.Unpaid,
AmountReceived = lightningPayment.Status == LightningPaymentStatus.Complete? lightningPayment.Value: null
};
}

public static LightningPayment ToPayment(this AppLightningPayment lightningPayment)
{
return new LightningPayment()
return new LightningPayment
{
Id = lightningPayment.PaymentHash.ToString(),
Id = lightningPayment.PaymentHash?.ToString(),
Amount = LightMoney.MilliSatoshis(lightningPayment.Value),
PaymentHash = lightningPayment.PaymentHash.ToString(),
PaymentHash = lightningPayment.PaymentHash?.ToString(),
Preimage = lightningPayment.Preimage,
BOLT11 = lightningPayment.PaymentRequest.ToString(),
BOLT11 = lightningPayment.PaymentRequest?.ToString(),
Status = lightningPayment.Status,
Fee = lightningPayment.AdditionalData.TryGetValue("feePaid", out var feePaid) ? LightMoney.MilliSatoshis((long)feePaid.GetInt64()) : null,
CreatedAt = lightningPayment.Timestamp

};
}

public static async Task<List<LightningPayment>> ToPayments(this Task<List<AppLightningPayment>> appLightningPayments)
{
var result = await appLightningPayments;
return result.Select(ToPayment).ToList();
}

public static async Task<List<LightningInvoice>> ToInvoices(this Task<List<AppLightningPayment>> appLightningPayments)
{
var result = await appLightningPayments;
return result.Select(ToInvoice).ToList();
}
}
}
117 changes: 70 additions & 47 deletions BTCPayApp.Core/BTCPayServer/BTCPayAppServerClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Microsoft.Extensions.Logging;
using NBitcoin;
using NBitcoin.Crypto;
using org.ldk.structs;

namespace BTCPayApp.Core.BTCPayServer;

Expand All @@ -23,34 +24,43 @@ public class BTCPayAppServerClient(ILogger<BTCPayAppServerClient> _logger, IServ
public event AsyncEventHandler<long?>? OnMasterUpdated;
public event AsyncEventHandler<ServerEvent>? OnNotifyServerEvent;

private LDKNode? Node => _serviceProvider.GetRequiredService<LightningNodeManager>().Node;
private PaymentsManager? PaymentsManager => Node?.PaymentsManager;
private LightningAPIKeyManager? ApiKeyManager => Node?.ApiKeyManager;

public async Task NotifyServerEvent(ServerEvent ev)
{
_logger.LogInformation("NotifyServerEvent: {ev}", ev);
await OnNotifyServerEvent?.Invoke(this, ev);
_logger.LogInformation("NotifyServerEvent: {Event}", ev.ToString());
if (OnNotifyServerEvent is null) return;
await OnNotifyServerEvent.Invoke(this, ev);
}

public async Task NotifyNetwork(string network)
{
_logger.LogInformation("NotifyNetwork: {network}", network);
await OnNotifyNetwork?.Invoke(this, network);
_logger.LogInformation("NotifyNetwork: {Network}", network);
if (OnNotifyNetwork is null) return;
await OnNotifyNetwork.Invoke(this, network);
}

public async Task NotifyServerNode(string nodeInfo)
{
_logger.LogInformation("NotifyServerNode: {nodeInfo}", nodeInfo);
await OnServerNodeInfo?.Invoke(this, nodeInfo);
_logger.LogInformation("NotifyServerNode: {NodeInfo}", nodeInfo);
if (OnServerNodeInfo is null) return;
await OnServerNodeInfo.Invoke(this, nodeInfo);
}

public async Task TransactionDetected(TransactionDetectedRequest request)
{
_logger.LogInformation($"OnTransactionDetected: {request.TxId}");
await OnTransactionDetected?.Invoke(this, request);
_logger.LogInformation("OnTransactionDetected: {TxId}", request.TxId);
if (OnTransactionDetected is null) return;
await OnTransactionDetected.Invoke(this, request);
}

public async Task NewBlock(string block)
{
_logger.LogInformation("NewBlock: {block}", block);
await OnNewBlock?.Invoke(this, block);
_logger.LogInformation("NewBlock: {Block}", block);
if (OnNewBlock is null) return;
await OnNewBlock.Invoke(this, block);
}

public async Task StartListen(string key)
Expand All @@ -63,22 +73,19 @@ public async Task StartListen(string key)
.StartListen();
}

private PaymentsManager PaymentsManager =>
_serviceProvider.GetRequiredService<LightningNodeManager>().Node?.PaymentsManager;
private LightningAPIKeyManager ApiKeyManager =>
_serviceProvider.GetRequiredService<LightningNodeManager>().Node?.ApiKeyManager;

private async Task AssertPermission(string key, APIKeyPermission permission)
{
if (ApiKeyManager is null)
throw new HubException("Api Key Manager not available");
if (!await ApiKeyManager.CheckPermission(key, permission))
{
throw new HubException("Permission denied");
}
}

public async Task<LightningInvoice> CreateInvoice(string key, CreateLightningInvoiceRequest createLightningInvoiceRequest)
{
await AssertPermission(key, APIKeyPermission.Read);
if (PaymentsManager is null) throw new HubException("Payments Manager not available");

var descHash = new uint256(Hashes.SHA256(Encoding.UTF8.GetBytes(createLightningInvoiceRequest.Description)),
false);
return (await PaymentsManager.RequestPayment(createLightningInvoiceRequest.Amount,
Expand All @@ -87,52 +94,61 @@ public async Task<LightningInvoice> CreateInvoice(string key, CreateLightningInv

public async Task<LightningInvoice?> GetLightningInvoice(string key, uint256 paymentHash)
{

await AssertPermission(key, APIKeyPermission.Read);
var invs = await PaymentsManager.List(payments =>
if (PaymentsManager is null) throw new HubException("Payments Manager not available");

var invoices = await PaymentsManager.List(payments =>
payments.Where(payment => payment.Inbound && payment.PaymentHash == paymentHash));
return invs.FirstOrDefault()?.ToInvoice();
return invoices.FirstOrDefault()?.ToInvoice();
}

public async Task<LightningPayment?> GetLightningPayment(string key, uint256 paymentHash)
{
await AssertPermission(key, APIKeyPermission.Read);
var invs = await PaymentsManager.List(payments =>
if (PaymentsManager is null) throw new HubException("Payments Manager not available");

var invoices = await PaymentsManager.List(payments =>
payments.Where(payment => !payment.Inbound && payment.PaymentHash == paymentHash));
return invs.FirstOrDefault()?.ToPayment();
return invoices.FirstOrDefault()?.ToPayment();
}

public async Task CancelInvoice(string key, uint256 paymentHash)
{
await AssertPermission(key, APIKeyPermission.Write);
if (PaymentsManager is null) throw new HubException("Payments Manager not available");

await PaymentsManager.CancelInbound(paymentHash);
}

public async Task<List<LightningPayment>> GetLightningPayments(string key, ListPaymentsParams request)
{

await AssertPermission(key, APIKeyPermission.Read);
return await PaymentsManager.List(payments => payments.Where(payment => !payment.Inbound), default)
if (PaymentsManager is null) throw new HubException("Payments Manager not available");

return await PaymentsManager.List(payments => payments.Where(payment => !payment.Inbound))
.ToPayments();
}

public async Task<List<LightningInvoice>> GetLightningInvoices(string key, ListInvoicesParams request)
{
await AssertPermission(key, APIKeyPermission.Read);
return await PaymentsManager.List(payments => payments.Where(payment => payment.Inbound), default).ToInvoices();
if (PaymentsManager is null) throw new HubException("Payments Manager not available");

return await PaymentsManager.List(payments => payments.Where(payment => payment.Inbound)).ToInvoices();
}

public async Task<PayResponse> PayInvoice(string key, string bolt11, long? amountMilliSatoshi)
{

await AssertPermission(key, APIKeyPermission.Write);
if (PaymentsManager is null) throw new HubException("Payments Manager not available");

var config = await _serviceProvider.GetRequiredService<OnChainWalletManager>().GetConfig();
var bolt = BOLT11PaymentRequest.Parse(bolt11, config.NBitcoinNetwork);
try
{
var result = await PaymentsManager.PayInvoice(bolt,
amountMilliSatoshi is null ? null : LightMoney.MilliSatoshis(amountMilliSatoshi.Value));
return new PayResponse()
return new PayResponse
{
Result = result.Status switch
{
Expand All @@ -142,7 +158,7 @@ public async Task<PayResponse> PayInvoice(string key, string bolt11, long? amoun
LightningPaymentStatus.Failed => PayResult.Error,
_ => throw new ArgumentOutOfRangeException()
},
Details = new PayDetails()
Details = new PayDetails
{
Preimage = result.Preimage is not null ? new uint256(result.Preimage) : null,
Status = result.Status
Expand All @@ -156,47 +172,54 @@ public async Task<PayResponse> PayInvoice(string key, string bolt11, long? amoun
}
}

public async Task MasterUpdated(long? deviceIdentifier)
public Task MasterUpdated(long? deviceIdentifier)
{
_logger.LogInformation("MasterUpdated: {deviceIdentifier}", deviceIdentifier);
_logger.LogInformation("MasterUpdated: {DeviceIdentifier}", deviceIdentifier);
OnMasterUpdated?.Invoke(this, deviceIdentifier);
return Task.CompletedTask;
}

public async Task<LightningNodeInformation> GetLightningNodeInfo(string key)
{

await AssertPermission(key, APIKeyPermission.Read);
var node = _serviceProvider.GetRequiredService<LightningNodeManager>().Node;
if (Node is null) throw new HubException("Lightning Node not available");

var config = await Node.GetConfig();
var peers = await Node.GetPeers();
var chans = await Node.GetChannels() ?? [];
var channels = chans
.Where(channel => channel.Value.channelDetails is not null)
.Select(channel => channel.Value.channelDetails)
.OfType<ChannelDetails>()
.ToArray();
var bb = await _serviceProvider.GetRequiredService<OnChainWalletManager>().GetBestBlock();
var config = await node.GetConfig();
var peers = await node.GetPeers();
var channels = (await node.GetChannels()).Where(channel => channel.Value.channelDetails is not null)
.Select(channel => channel.Value.channelDetails).ToArray();
return new LightningNodeInformation()
return new LightningNodeInformation
{
Alias = config.Alias,
Color = config.Color,
Version = "preprepreprealpha",
BlockHeight = bb.BlockHeight,
BlockHeight = bb?.BlockHeight ?? 0,
PeersCount = peers.Length,
ActiveChannelsCount = channels.Count(channel => channel.get_is_usable()),
InactiveChannelsCount =
channels.Count(channel => !channel.get_is_usable() && channel.get_is_channel_ready()),
PendingChannelsCount =
channels.Count(channel => !channel.get_is_usable() && !channel.get_is_channel_ready())
PendingChannelsCount = channels.Count(channel => !channel.get_is_usable() && !channel.get_is_channel_ready()),
InactiveChannelsCount = channels.Count(channel => !channel.get_is_usable() && channel.get_is_channel_ready())
};
}

public async Task<LightningNodeBalance> GetLightningBalance(string key)
{
await AssertPermission(key, APIKeyPermission.Read);
var channels = (await _serviceProvider.GetRequiredService<LightningNodeManager>().Node.GetChannels())
.Where(channel => channel.Value.channelDetails is not null).Select(channel => channel.Value.channelDetails)
.ToArray();
if (Node is null) throw new HubException("Lightning Node not available");

return new LightningNodeBalance()
var chans = await Node.GetChannels() ?? [];
var channels = chans
.Where(channel => channel.Value.channelDetails is not null)
.Select(channel => channel.Value.channelDetails)
.OfType<ChannelDetails>()
.ToArray();
return new LightningNodeBalance
{
OffchainBalance = new OffchainBalance()
OffchainBalance = new OffchainBalance
{
Local = LightMoney.MilliSatoshis(channels.Sum(channel => channel.get_balance_msat())),
Remote = LightMoney.MilliSatoshis(channels.Sum(channel => channel.get_inbound_capacity_msat())),
Expand Down
18 changes: 11 additions & 7 deletions BTCPayApp.Core/BTCPayServer/BTCPayConnectionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public IBTCPayAppHubServer? HubProxy
public event AsyncEventHandler<(BTCPayConnectionState Old, BTCPayConnectionState New)>? ConnectionChanged;
private BTCPayConnectionState _connectionState = BTCPayConnectionState.Init;

private SemaphoreSlim _lock = new(1, 1);
private readonly SemaphoreSlim _lock = new(1, 1);
public BTCPayConnectionState ConnectionState
{
get => _connectionState;
Expand Down Expand Up @@ -280,19 +280,22 @@ private async Task OnConnectionChanged(object? sender, (BTCPayConnectionState Ol
}
}

private async Task OnServerNodeInfo(object? sender, string e)
private Task OnServerNodeInfo(object? sender, string e)
{
ReportedNodeInfo = e;
return Task.CompletedTask;
}

private async Task OnNotifyServerEvent(object? sender, ServerEvent e)
private Task OnNotifyServerEvent(object? sender, ServerEvent e)
{
_logger.LogInformation("OnNotifyServerEvent: {Type} - {Details}", e.Type, e.ToString());
return Task.CompletedTask;
}

private async Task OnNotifyNetwork(object? sender, string e)
private Task OnNotifyNetwork(object? sender, string e)
{
ReportedNetwork = Network.GetNetwork(e);
return Task.CompletedTask;
}

private async void OnAuthenticationStateChanged(Task<AuthenticationState> task)
Expand Down Expand Up @@ -360,7 +363,6 @@ protected override async Task ExecuteStopAsync(CancellationToken cancellationTok
ConnectionChanged -= OnConnectionChanged;
}


public Task OnClosed(Exception? exception)
{
_logger.LogError(exception, "Hub connection closed");
Expand All @@ -372,16 +374,18 @@ public Task OnClosed(Exception? exception)
return Task.CompletedTask;
}

public async Task OnReconnected(string? connectionId)
public Task OnReconnected(string? connectionId)
{
_logger.LogInformation("Hub connection reconnected");
ConnectionState = BTCPayConnectionState.Syncing;
return Task.CompletedTask;
}

public async Task OnReconnecting(Exception? exception)
public Task OnReconnecting(Exception? exception)
{
_logger.LogWarning(exception, "Hub connection reconnecting");
ConnectionState = BTCPayConnectionState.Connecting;
return Task.CompletedTask;
}

public async Task SwitchToSlave()
Expand Down
Loading

0 comments on commit 87f9de6

Please sign in to comment.