Compare commits

..

103 Commits

Author SHA1 Message Date
Pavlenex
395495fef5
Merge pull request #236 from TChukwuleta/bg/centre_charge_button 2025-07-18 19:35:28 +05:00
Chukwuleta Tobechi
aee8c5f032 Fix charge button position on Bitcoinize POS 2025-07-18 15:23:16 +01:00
Ghander
0785a1ab39
Update build-test.yml
change workflow trigger from pull_request to pull_request_target, which runs in the context of the base repository and can access secrets.
2025-07-01 16:57:04 -05:00
Ghander
ae06fd4404
Merge pull request #225 from TChukwuleta/ft/Include_archive
Include receipt and archive CTA
2025-06-30 11:50:51 -05:00
Ghander
e2d9b4e87c
clean before build-test.yml 2025-06-29 21:28:51 -05:00
Ghander
621adc1804 fixed ambiguous class references for invoice request 2025-06-28 21:49:25 -05:00
Pavlenex
831f1e2c5b
Merge pull request #220 from TChukwuleta/feat/include_supporters
Include supporters to the login and create account view
2025-06-27 11:34:43 +05:00
Pavlenex
9f56451b41
Merge pull request #227 from NicolasDorier/fix-double-charge
Fix: The keypad is charging double of what it should be
2025-06-27 10:50:04 +05:00
nicolas.dorier
427ba10f5e
Fix instructions in README.md 2025-06-26 18:24:36 +09:00
nicolas.dorier
409822d1a2
Fix: The keypad is charging double of what it should be 2025-06-26 17:53:42 +09:00
Chukwuleta Tobechi
1e84841af1 fixing sshd 2025-06-24 13:41:14 +01:00
Chukwuleta Tobechi
29136fe4c4 Include receipt and archive CTA 2025-06-23 19:18:23 +01:00
rockstardev
1b462e81da
Improving NFC scan processing 2025-06-19 11:04:55 +02:00
Chukwuleta Tobechi
e75d011eb4 Include supporters to the login and create account view 2025-06-19 10:04:31 +01:00
Ghander
ef534215f9
Merge pull request #219 from btcpayserver/fix-store-build
Fix: Unable to build on the plugin builder
2025-06-15 16:07:34 -05:00
Ghander
b147ddba3f Running the app in the background is causing the app to lock up on restart. Turning this off for now until we can find a long term fix. 2025-06-13 23:05:23 -05:00
Ghander
fdd3e0fc33 prevent multiple simultaneous nfc scans 2025-06-13 22:49:45 -05:00
Ghander
797e7a33c7 added invoice paid with successful nfc payment since this happens outside the iframe. 2025-06-12 19:47:07 -05:00
Ghander
f4f988b113 lnurl nfc attempt #3 2025-06-11 20:44:28 -05:00
nicolas.dorier
b9000dfc75
Fix: Unable to build on the plugin builder 2025-06-10 22:30:26 +09:00
Ghander
9d44aee152 format INfcInterface 2025-06-09 17:27:01 -05:00
Ghander
698afcd033 nfc iframe checkout attempt 3 2025-06-09 16:23:08 -05:00
Ghander
ac98a426c0 enable web-nfc for checkout iframe 2025-06-08 15:28:14 -05:00
Ghander
d232fbc68c initialize nfc plugin 2025-06-08 15:00:27 -05:00
Ghander
c9d6f5d9d7 NFC permissions enabled for compatible devices 2025-06-08 14:41:05 -05:00
Ghander
336daad4c6 Merge branch 'master' of https://github.com/btcpayserver/app 2025-06-06 09:07:06 -05:00
Ghander
4dbab4038c login user with pos qr code and set to cashier mode - issue #212 2025-06-06 08:55:27 -05:00
Andrew Camilleri (Kukks)
5b86d4f28f
Provide global settings that lock wallet gen + disbale auto generation of wallets 2025-06-06 12:37:13 +02:00
Andrew Camilleri (Kukks)
f64768a383
add a ps1 setup variant 2025-06-06 11:21:04 +02:00
Ghander
ccd160c4e0 Merge branch 'master' of https://github.com/btcpayserver/app 2025-05-30 15:06:39 -05:00
Dennis Reimann
5bd52b6f86
Update submodule 2025-05-30 13:35:56 +02:00
Dennis Reimann
c2e7a79bb8
Withdraw: Make Next button more prominent 2025-05-30 13:31:02 +02:00
Dennis Reimann
4a0bedd7b0
Fix missing exception and stack trace in error logs 2025-05-30 13:08:40 +02:00
Dennis Reimann
7f917a2a92
Refactor EmailService for use in desktop/server apps 2025-05-30 09:34:33 +02:00
Ghander
957da11d89 Merge branch 'master' of https://github.com/btcpayserver/app 2025-05-29 11:50:47 -05:00
d11n
b489cd0ec7
Show Withdraw button regardless of price 2025-05-29 08:17:00 +02:00
Dennis Reimann
f86b996303
Withdraw: Add review/confirmation for sending Lightning payments 2025-05-28 11:47:49 +02:00
Dennis Reimann
5f59fa7987
Add closing amount to offchain balance API 2025-05-27 15:51:13 +02:00
Dennis Reimann
48368cecbb
Fix version mismatch with server 2025-05-27 12:46:02 +02:00
Dennis Reimann
df637acb54
UI: Fix channel messages 2025-05-27 12:44:02 +02:00
Dennis Reimann
9b8890d04e
Update submodule 2025-05-27 12:43:35 +02:00
Ghander
b5ce32c67b Merge branch 'master' of https://github.com/btcpayserver/app 2025-05-26 08:50:09 -05:00
Dennis Reimann
ad870cae50
UI: Withdraw page updates
Context: #162
2025-05-26 14:18:39 +02:00
Dennis Reimann
612ef699b7
UI: Withdraw page updates
Context: #162
2025-05-23 18:01:31 +02:00
Dennis Reimann
186e995c41
UI: Extract recent transactions to separate page 2025-05-23 12:45:05 +02:00
Dennis Reimann
489d78bc40
Minor channel-related updates 2025-05-23 11:12:23 +02:00
Dennis Reimann
74ec312c31
Peer Handler: Improve handling of failed socket connections to persistent peers 2025-05-23 10:28:19 +02:00
Ghander
796a512b50 undo breaking changes 2025-05-22 16:14:52 -05:00
Dennis Reimann
fd3bbf68e5
Use vector icons for modern Android versions 2025-05-22 22:13:30 +02:00
Dennis Reimann
2061e93db3
Update submodule 2025-05-22 22:12:58 +02:00
Ghander
3834ef4c4f Merge branch 'master' of https://github.com/btcpayserver/app 2025-05-21 17:18:32 -05:00
Ghander
cdf6c78b0a reverted LDK Resume changes. 2025-05-21 17:18:13 -05:00
Ghander
b0d1e83bda fixed merge 2025-05-21 17:00:27 -05:00
Ghander
a678ad4d9e reverted the breaking changes. 2025-05-21 16:59:27 -05:00
Ghander
855046c161 created powershell script for windows to mimic the lightning setup shell script 2025-05-21 16:28:37 -05:00
Ghander
f55c394c0c fixed exception cuased by releasing a non-existant semaphore and various store page errors preventing build 2025-05-21 16:27:28 -05:00
Dennis Reimann
f5486a087b
Android: Add foreground service to keep hub connection alive 2025-05-21 11:47:12 +02:00
Dennis Reimann
0b04dd03d4
Improve app state logging 2025-05-21 11:28:40 +02:00
Dennis Reimann
85ca2d9658
BTCPayServer.Plugins.App v0.3.1.0 2025-05-20 12:19:13 +02:00
Dennis Reimann
72885feea7
VSS: Extend logging
Context: #208
2025-05-20 12:17:56 +02:00
Dennis Reimann
0aa42e93a8
Update submodule 2025-05-20 11:21:30 +02:00
Dennis Reimann
ef7faed0d8
UI: Show Withdraw link regardless of balance 2025-05-20 11:20:46 +02:00
Dennis Reimann
d63ef814ca
BTCPayServer.Plugins.App v0.3.0.0 2025-05-19 12:00:11 +02:00
Dennis Reimann
4868cf9b1f
Add login info endpoint
Redirect to password reset if password is missing. Closes #184.
2025-05-19 11:57:34 +02:00
Dennis Reimann
d076afbd85
Update submodule 2025-05-19 07:49:55 +02:00
Ghander
3e6db4d9e9 add sendEmail service to web app 2025-05-18 22:45:05 -05:00
Dennis Reimann
22f1da33f3
UI: Fix withdraw amount input field display and validation
Fixes #192.
2025-05-16 17:30:06 +02:00
Dennis Reimann
d9dc06eb01
UI: Form validation fixes 2025-05-16 17:29:06 +02:00
Dennis Reimann
f94a1aa262
Minor cleanups 2025-05-16 16:04:08 +02:00
Dennis Reimann
4e047acc8e
UI: Channels list improvements 2025-05-16 12:51:10 +02:00
Dennis Reimann
e4e68c1cf4
UI: Add device ID to debug section 2025-05-16 12:47:12 +02:00
Dennis Reimann
28af1bfecb
Update submodule 2025-05-15 13:55:19 +02:00
Dennis Reimann
4e54057447
UI: Add per-word feedback for verifying recovery phase
Closes #206.
2025-05-15 13:53:53 +02:00
Dennis Reimann
25eadbd822
UI: Redirect to dashboard after verifying recovery phrase
Closes #205.
2025-05-15 12:35:47 +02:00
Dennis Reimann
e87131338b
UI: Channels list improvements 2025-05-15 11:33:03 +02:00
Dennis Reimann
9ff0c0166b
Add labelling support for peers 2025-05-14 16:19:17 +02:00
Dennis Reimann
ea8344f537
Add exception handling to LN node accessor 2025-05-14 15:05:54 +02:00
Dennis Reimann
6698d81efa
Update submodule and adapt to store template feature 2025-05-14 14:14:20 +02:00
Dennis Reimann
426f50e1cd
Add non-truncated NodeID for testing 2025-05-14 11:55:46 +02:00
Dennis Reimann
42af818d85
Re-add LN connection string and LN store payment method button 2025-05-14 10:56:59 +02:00
Dennis Reimann
8babd11c1e
Channels list fixes 2025-05-13 14:10:41 +02:00
Dennis Reimann
244682f390
Re-add LNURL channel request feature 2025-05-13 12:15:54 +02:00
Ghander
dfeb073c3c added default request for REQUEST_IGNORE_BATTERY_OPTIMIZATIONS to see if we can get access to running in background. 2025-05-12 23:28:09 -05:00
Ghander
8dd2a33d16 added button to send logs via email. 2025-05-12 23:06:10 -05:00
Ghander
3b3d82f873 merged send email branch with master 2025-05-12 22:51:26 -05:00
Dennis Reimann
d24e971a09
UI: Improve channels list 2025-05-12 15:09:23 +02:00
Dennis Reimann
206b569fd4
UI: Don't show superfluous Top Items tile
Hides the tile if only keypad amounts were used. Closes #203.
2025-05-09 16:41:49 +02:00
Dennis Reimann
cad7b343e4
UI: Fix crash on settings page when toggling primary/secondary device 2025-05-09 16:28:09 +02:00
Dennis Reimann
18acd479f1
Minor channel list fix 2025-05-09 16:12:15 +02:00
Dennis Reimann
553948a38c
UI: Fix threading issue when adding a new peer
Fixes #197.
2025-05-09 16:07:14 +02:00
Dennis Reimann
375a320fb0
Cleanups 2025-05-09 09:14:45 +02:00
Dennis Reimann
e00b9b8d7b
UI: Fix onchain and lightning settings for additional/secondary devices 2025-05-08 17:39:17 +02:00
Dennis Reimann
fe33ec8769
UI: Remove QR code scan logs to not leak data 2025-05-08 15:44:23 +02:00
Dennis Reimann
df790001c0
MAUI: Set PublishTrimmed to false for Android release 2025-05-08 13:46:05 +02:00
Dennis Reimann
83b567d02c
Create pre-releases for master only 2025-05-08 11:33:02 +02:00
Dennis Reimann
712f2a5e5c Use MAUI compatible SQLite logging lib 2025-05-08 11:29:06 +02:00
Dennis Reimann
128ee5b744 Log to SQLite
Unfortunately this doesn't build for the MAUI project. See saleem-mirza/serilog-sinks-sqlite#41.
2025-05-08 11:29:06 +02:00
Dennis Reimann
ab0bb4156a
MAUI: Remove unnecessary settings from csproj 2025-05-08 11:27:10 +02:00
Dennis Reimann
ff1489fba7
UI: Signed out pages improvements 2025-05-06 10:30:50 +02:00
Dennis Reimann
7cf70000f3
UI: Fix store select redirect
Fixes #186.
2025-05-06 09:59:46 +02:00
Dennis Reimann
e0b07afc80
Syntax cleanup for LDK classes 2025-05-05 17:10:19 +02:00
Dennis Reimann
7f4e12dd2c
LN Node: Fix startup order to prevent trying to start without best block 2025-05-05 15:50:04 +02:00
Dennis Reimann
c7f2c4781a
Fix setting LSP to none
Fixes #190.
2025-05-05 14:47:07 +02:00
131 changed files with 3041 additions and 1866 deletions

View File

@ -7,7 +7,7 @@ on:
- '**/*.md'
- '**/*.gitignore'
- '**/*.gitattributes'
pull_request:
pull_request_target:
branches:
- master
@ -36,7 +36,9 @@ jobs:
run: dotnet build --configuration Release BTCPayApp.Server
# Setup infrastructure
- name: Start containers
run: docker compose -f "submodules/btcpayserver/BTCPayServer.Tests/docker-compose.yml" up -d dev
run: |
docker compose -f "submodules/btcpayserver/BTCPayServer.Tests/docker-compose.yml" build
docker compose -f "submodules/btcpayserver/BTCPayServer.Tests/docker-compose.yml" up -d dev
- name: Start BTCPay
run: |
./setup.sh
@ -65,6 +67,9 @@ jobs:
dotnet-version: 8.0.x
- name: Install workloads
run: dotnet workload install maui
- name: Clean before build
run: |
dotnet clean BTCPayApp.Maui/BTCPayApp.Maui.csproj
- name: Build
# TODO: Use proper keystore once we switch to real releases
# https://learn.microsoft.com/en-us/dotnet/maui/android/deployment/publish-cli?view=net-maui-8.0#code-try-4
@ -78,6 +83,7 @@ jobs:
name: org.btcpayserver.BTCPayApp-Signed.apk
path: publish/android/org.btcpayserver.BTCPayApp-Signed.apk
- name: Create pre-release
if: success() && github.ref == 'refs/heads/master'
uses: marvinpinto/action-automatic-releases@latest
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}

View File

@ -55,11 +55,11 @@ public class AuthStateProvider(
}
}
public BTCPayAppClient GetClient(string? baseUri = null)
public BTCPayAppClient GetClient(string? baseUri = null, string? token = null)
{
if (string.IsNullOrEmpty(baseUri) && string.IsNullOrEmpty(Account?.BaseUri))
throw new ArgumentException("No base URI present or provided.", nameof(baseUri));
var token = Account?.ModeToken ?? Account?.OwnerToken;
token ??= Account?.ModeToken ?? Account?.OwnerToken;
return new BTCPayAppClient(baseUri ?? Account!.BaseUri, token, clientFactory.CreateClient());
}
@ -199,7 +199,7 @@ public class AuthStateProvider(
await CheckAuthenticated(true);
store = GetUserStore(store.Id)!;
}
catch (Exception)
catch (Exception ex)
{
// ignored
}
@ -243,6 +243,19 @@ public class AuthStateProvider(
}
}
public async Task<FormResult<LoginInfoResult>> LoginInfo(string serverUrl, string email, CancellationToken? cancellation = default)
{
try
{
var response = await GetClient(serverUrl).LoginInfo(email, cancellation.GetValueOrDefault());
return new FormResult<LoginInfoResult>(true, string.Empty, response);
}
catch (Exception e)
{
return new FormResult<LoginInfoResult>(false, e.Message, null);
}
}
public async Task<FormResult> Login(string serverUrl, string email, string password, string? otp = null, CancellationToken? cancellation = default)
{
var payload = new LoginRequest
@ -265,13 +278,19 @@ public class AuthStateProvider(
}
}
public async Task<FormResult> LoginWithCode(string serverUrl, string email, string code, CancellationToken? cancellation = default)
public async Task<FormResult> LoginWithCode(string serverUrl, string? email, string code, CancellationToken? cancellation = default)
{
try
{
var client = GetClient(serverUrl);
var response = await client.Login(code, cancellation.GetValueOrDefault());
if (string.IsNullOrEmpty(response.AccessToken)) throw new Exception("Did not obtain valid API token.");
if (string.IsNullOrEmpty(email))
{
var clientWithToken = GetClient(serverUrl, response.AccessToken);
var userInfo = await clientWithToken.GetUserInfo();
email = userInfo?.Email!;
}
var account = new BTCPayAccount(serverUrl, email, response.AccessToken);
await SetAccount(account);
return new FormResult(true);

View File

@ -9,15 +9,16 @@ public interface IAccountManager
public BTCPayAccount? Account { get; }
public AppUserInfo? UserInfo { get; }
public AppUserStoreInfo? CurrentStore { get; }
public BTCPayAppClient GetClient(string? baseUri = null);
public BTCPayAppClient GetClient(string? baseUri = null, string? token = null);
public Task<string?> GetEncryptionKey();
public Task SetEncryptionKey(string value);
public Task<bool> CheckAuthenticated(bool refreshUser = false);
public Task<bool> IsAuthorized(string policy, object? resource = null);
public Task<FormResult> AddAccountWithEncyptionKey(string serverUrl, string email, string key);
public Task<FormResult<AcceptInviteResult>> AcceptInvite(string inviteUrl, CancellationToken? cancellation = default);
public Task<FormResult<LoginInfoResult>> LoginInfo(string serverUrl, string email, CancellationToken? cancellation = default);
public Task<FormResult> Login(string serverUrl, string email, string password, string? otp, CancellationToken? cancellation = default);
public Task<FormResult> LoginWithCode(string serverUrl, string email, string code, CancellationToken? cancellation = default);
public Task<FormResult> LoginWithCode(string serverUrl, string? email, string code, CancellationToken? cancellation = default);
public Task<FormResult> Register(string serverUrl, string email, string password, CancellationToken? cancellation = default);
public Task<FormResult> ResetPassword(string serverUrl, string email, string? resetCode, string? newPassword, CancellationToken? cancellation = default);
public Task<FormResult<ApplicationUserData>> ChangePassword(string currentPassword, string newPassword, CancellationToken? cancellation = default);

View File

@ -25,13 +25,13 @@
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.1" />
<PackageReference Include="NBitcoin" Version="8.0.8" />
<PackageReference Include="NBitcoin" Version="8.0.13" />
<PackageReference Include="Microsoft.Extensions.Identity.Core" Version="8.0.11" />
<PackageReference Include="org.ldk" Version="0.1.2" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.SQLite.Maui" Version="1.9.7" />
<PackageReference Include="TypedSignalR.Client" Version="3.6.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>

View File

@ -37,6 +37,12 @@ public class BTCPayAppClient(string baseUri, string? apiKey = null, HttpClient?
return await SendHttpRequest<JObject>("btcpayapp/register", payload, HttpMethod.Post, cancellation);
}
public async Task<LoginInfoResult> LoginInfo(string email, CancellationToken cancellation = default)
{
var payload = new Dictionary<string, object> { { "email", email } };
return await SendHttpRequest<LoginInfoResult>("btcpayapp/login-info", payload, HttpMethod.Get, cancellation);
}
public async Task<AuthenticationResponse> Login(LoginRequest payload, CancellationToken cancellation = default)
{
return await SendHttpRequest<AuthenticationResponse>("btcpayapp/login", payload, HttpMethod.Post, cancellation);
@ -64,16 +70,20 @@ public class BTCPayAppClient(string baseUri, string? apiKey = null, HttpClient?
return await SendHttpRequest<JObject?>(path, payload, HttpMethod.Post, cancellation);
}
public async Task<JObject?> CreatePosInvoice(CreatePosInvoiceRequest req, CancellationToken cancellation = default)
public async Task<JObject?> CreatePosInvoice(Models.CreatePosInvoiceRequest req, CancellationToken cancellation = default)
{
var query = new Dictionary<string, object>();
if (req.Total != null) query.Add("amount", req.Total.Value.ToString(CultureInfo.InvariantCulture));
if (req.DiscountPercent != null) query.Add("discount", req.DiscountPercent.Value.ToString(CultureInfo.InvariantCulture));
if (req.Tip != null) query.Add("tip", req.Tip.Value.ToString(CultureInfo.InvariantCulture));
if (req.PosData != null) query.Add("posData", req.PosData);
return await SendHttpRequest<JObject?>($"apps/{req.AppId}/pos/light", query, HttpMethod.Post, cancellation);
}
public async Task<string> SubmitLNURLWithdrawForInvoice(SubmitLnUrlRequest req, CancellationToken cancellation = default)
{
return await SendHttpRequest<string>($"plugins/NFC", req, HttpMethod.Post, cancellation);
}
public virtual async Task<T> UploadFileRequest<T>(string apiPath, StreamContent fileContent, string fileName, string mimeType, CancellationToken token = default)
{
using MultipartFormDataContent multipartContent = new();

View File

@ -220,12 +220,17 @@ public class BTCPayAppServerClient(ILogger<BTCPayAppServerClient> _logger, IServ
.Select(channel => channel.channelDetails)
.OfType<ChannelDetails>()
.ToArray();
var balances = Node.ClaimableBalances;
var closing = balances
.Where(b => b is Balance.Balance_ClaimableAwaitingConfirmations)
.ToArray();
return new LightningNodeBalance
{
OffchainBalance = new OffchainBalance
{
Local = LightMoney.MilliSatoshis(channels.Sum(channel => channel.get_outbound_capacity_msat())),
Remote = LightMoney.MilliSatoshis(channels.Sum(channel => channel.get_inbound_capacity_msat())),
Closing = LightMoney.Satoshis(closing.Sum(balance => balance.claimable_amount_satoshis()))
}
};
}

View File

@ -38,6 +38,7 @@ public class BTCPayConnectionManager(
public Network? ReportedNetwork { get; private set; }
public string? ReportedNodeInfo { get; set; }
private bool ForceSlaveMode { get; set; }
public bool RunningInBackground { get; set; }
public event AsyncEventHandler<(BTCPayConnectionState Old, BTCPayConnectionState New)>? ConnectionChanged;
@ -52,7 +53,7 @@ public class BTCPayConnectionManager(
if (_connectionState == value) return;
var old = _connectionState;
_connectionState = value;
logger.LogInformation("Connection state changed: {Old} -> {ConnectionState}", old, _connectionState);
logger.LogInformation("Connection state changed{BgInfo}: {Old} -> {ConnectionState}", BgInfo, old, _connectionState);
ConnectionChanged?.Invoke(this, (old, _connectionState));
}
finally
@ -85,17 +86,17 @@ public class BTCPayConnectionManager(
var deviceId = await configProvider.GetDeviceIdentifier();
if (masterId is null && ConnectionState == BTCPayConnectionState.ConnectedAsSecondary && !ForceSlaveMode)
{
logger.LogInformation("OnMasterUpdated: Syncing slave {DeviceId}", deviceId);
logger.LogInformation("OnMasterUpdated{BgInfo}: Syncing slave {DeviceId}", BgInfo, deviceId);
ConnectionState = BTCPayConnectionState.Syncing;
}
else if (deviceId == masterId)
{
logger.LogInformation("OnMasterUpdated: Setting master to {DeviceId}", deviceId);
logger.LogInformation("OnMasterUpdated{BgInfo}: Setting master to {DeviceId}", BgInfo, deviceId);
ConnectionState = BTCPayConnectionState.ConnectedAsPrimary;
}
else if (ConnectionState == BTCPayConnectionState.ConnectedAsPrimary && masterId != deviceId)
{
logger.LogInformation("OnMasterUpdated: New master {MasterId} - Device: {DeviceId}", masterId, deviceId);
logger.LogInformation("OnMasterUpdated{BgInfo}: New master {MasterId} - Device: {DeviceId}", BgInfo, masterId, deviceId);
ConnectionState = BTCPayConnectionState.Syncing;
}
}, _cts.Token);
@ -173,13 +174,13 @@ public class BTCPayConnectionManager(
catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.Unauthorized)
{
await accountManager.Logout();
logger.LogInformation("Signed out user because of unauthorized response");
logger.LogInformation("Signed out user because of unauthorized response{BgInfo}", BgInfo);
}
catch (Exception ex)
{
await Task.Delay(500);
if (ex is not TaskCanceledException)
logger.LogError($"Error while connecting to hub: {ex.Message}");
logger.LogError("Error while connecting to hub{BgInfo}: {Message}", BgInfo, ex.Message);
}
}
Connection = connection;
@ -204,12 +205,12 @@ public class BTCPayConnectionManager(
var masterDevice = await HubProxy!.GetCurrentMaster();
if (deviceIdentifier == masterDevice)
{
logger.LogInformation("Syncing master to remote: {DeviceId}", deviceIdentifier);
logger.LogInformation("Syncing master to remote{BgInfo}: {DeviceId}", BgInfo, deviceIdentifier);
await syncService.SyncToRemote(CancellationToken.None);
}
else
{
logger.LogInformation("Syncing to local. Master: {MasterId} - Device: {DeviceId}", masterDevice, deviceIdentifier);
logger.LogInformation("Syncing to local{BgInfo}. Master: {MasterId} - Device: {DeviceId}", BgInfo, masterDevice, deviceIdentifier);
await syncService.SyncToLocal();
}
newState = BTCPayConnectionState.ConnectedFinishedInitialSync;
@ -246,12 +247,12 @@ public class BTCPayConnectionManager(
}
catch (System.Security.Cryptography.CryptographicException ex) when (newState is BTCPayConnectionState.Syncing or BTCPayConnectionState.Connecting)
{
logger.LogError(ex, "Error while changing connection state from {Old} to {New}", e.Old, e.New);
logger.LogError(ex, "Error while changing connection state from {Old} to {New}{BgInfo}", e.Old, e.New, BgInfo);
newState = BTCPayConnectionState.WaitingForEncryptionKey;
}
catch (Exception ex)
{
logger.LogError(ex, "Error while changing connection state from {Old} to {New}", e.Old, e.New);
logger.LogError(ex, "Error while changing connection state from {Old} to {New}{BgInfo}", e.Old, e.New, BgInfo);
throw;
}
finally
@ -268,7 +269,7 @@ public class BTCPayConnectionManager(
private Task OnNotifyServerEvent(object? sender, ServerEvent e)
{
logger.LogInformation("OnNotifyServerEvent: {Type} - {Details}", e.Type, e.ToString());
logger.LogInformation("OnNotifyServerEvent{BgInfo}: {Type} - {Details}", BgInfo, e.Type, e.ToString());
return Task.CompletedTask;
}
@ -297,7 +298,7 @@ public class BTCPayConnectionManager(
}
catch (Exception e)
{
logger.LogError(e, "Error while handling authentication state change");
logger.LogError(e, "Error while handling authentication state change{BgInfo}", BgInfo);
}
}, _cts.Token);
}
@ -306,7 +307,7 @@ public class BTCPayConnectionManager(
{
if (Connection is not null)
{
logger.LogWarning("Killing connection");
logger.LogWarning("Killing connection{BgInfo}", BgInfo);
}
var conn = Connection;
Connection = null;
@ -330,7 +331,7 @@ public class BTCPayConnectionManager(
if (_connectionState == BTCPayConnectionState.ConnectedAsPrimary)
{
var deviceId = await configProvider.GetDeviceIdentifier();
logger.LogInformation("Sending device master signal to turn off {DeviceId}", deviceId);
logger.LogInformation("Sending device master signal to turn off {DeviceId}{BgInfo}", deviceId, BgInfo);
await syncService.StopSync();
await syncService.SyncToRemote(CancellationToken.None);
if (HubProxy is not null)
@ -348,7 +349,7 @@ public class BTCPayConnectionManager(
public Task OnClosed(Exception? ex)
{
logger.LogError("Hub connection closed: {Message}", ex?.Message);
logger.LogError("Hub connection closed{BgInfo}: {Message}", BgInfo, ex?.Message);
if (Connection?.State == HubConnectionState.Disconnected && ConnectionState != BTCPayConnectionState.Connecting)
{
ConnectionState = BTCPayConnectionState.Disconnected;
@ -359,14 +360,14 @@ public class BTCPayConnectionManager(
public Task OnReconnected(string? connectionId)
{
logger.LogInformation("Hub connection reconnected");
logger.LogInformation("Hub connection reconnected{BgInfo}", BgInfo);
ConnectionState = BTCPayConnectionState.Syncing;
return Task.CompletedTask;
}
public Task OnReconnecting(Exception? ex)
{
logger.LogWarning("Hub connection reconnecting: {Message}", ex?.Message);
logger.LogWarning("Hub connection reconnecting{BgInfo}: {Message}", BgInfo, ex?.Message);
ConnectionState = BTCPayConnectionState.Connecting;
return Task.CompletedTask;
}
@ -383,4 +384,6 @@ public class BTCPayConnectionManager(
await HubProxy!.DeviceMasterSignal(deviceId, false);
}
}
private string BgInfo => RunningInBackground ? " (in background mode)" : string.Empty;
}

View File

@ -1,5 +1,8 @@
namespace BTCPayApp.Core.BTCPayServer;
using System.Text.Json.Serialization;
namespace BTCPayApp.Core.BTCPayServer;
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum BTCPayConnectionState
{
Init,

View File

@ -5,4 +5,5 @@ public static class Constants
public const string LoginCodeSeparator = ";";
public const string EncryptionKeySeparator = "*";
public const string InviteSeparator = "/invite/";
public const string POSQRLoginSeparator = "loginCode";
}

View File

@ -2,6 +2,6 @@
{
public interface IEmailService
{
Task SendAsync(string subject, string body, string? recipient = null, string? attachFilePath = null);
Task SendAsync(string subject, string body, string recipient, string? attachFilePath = null);
}
}

View File

@ -0,0 +1,15 @@
using BTCPayApp.Core.Models;
namespace BTCPayApp.Core.Contracts;
public interface INfcService: IDisposable
{
event EventHandler<NfcCardData> OnNfcDataReceived;
void StartNfc();
void EndNfc();
}
public class NfcCardData
{
public string Message { get; set; }
public byte[] Payload { get; set; }
}

View File

@ -1,5 +1,8 @@
using System.Text.Json.Serialization;
namespace BTCPayApp.Core.Contracts;
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum SetupState
{
Undetermined,

View File

@ -14,7 +14,6 @@ public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(op
public DbSet<AppLightningPayment> LightningPayments { get; set; }
public DbSet<Outbox> OutboxItems { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Outbox>()

View File

@ -0,0 +1,8 @@
using Microsoft.EntityFrameworkCore;
namespace BTCPayApp.Core.Data;
public class LogDbContext(DbContextOptions<LogDbContext> options) : DbContext(options)
{
public DbSet<LogEntry> Logs { get; set; }
}

View File

@ -0,0 +1,13 @@
using Serilog.Events;
namespace BTCPayApp.Core.Data;
public class LogEntry
{
public int Id { get; set; }
public string Level { get; set; }
public DateTime TimeStamp { get; set; }
public string RenderedMessage { get; set; }
public string Exception { get; set; }
public string Properties { get; set; }
}

View File

@ -1,40 +1,29 @@
using BTCPayApp.Core.Contracts;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using Serilog.Core;
using Serilog.Events;
namespace BTCPayApp.Core.Data;
public static class LoggingConfig
{
private const string OutputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} ({SourceContext}){NewLine}{Exception}";
public static void ConfigureLogging(IServiceCollection serviceCollection)
{
var serviceProvider = serviceCollection.BuildServiceProvider();
var configProvider = serviceProvider.GetRequiredService<ConfigProvider>();
var dirProvider = serviceProvider.GetRequiredService<IDataDirectoryProvider>();
var appDir = dirProvider.GetAppDataDirectory().ConfigureAwait(false).GetAwaiter().GetResult();
var dbPath = $"{appDir}/logs.db";
var isDevEnv = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development";
var logLevel = isDevEnv ? LogEventLevel.Debug : LogEventLevel.Information;
if (!isDevEnv)
{
try
{
var storedLevel = configProvider.Get<LogEventLevel?>("logLevel").ConfigureAwait(false).GetAwaiter().GetResult();
if (storedLevel is not null) logLevel = storedLevel.Value;
}
catch (Exception) { /* ignored */ }
}
var minLogLevel = isDevEnv ? LogEventLevel.Verbose : LogEventLevel.Information;
var levelSwitch = new LoggingLevelSwitch { MinimumLevel = logLevel };
serviceCollection.AddSingleton(levelSwitch);
serviceCollection.AddSerilog();
var outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} ({SourceContext}){NewLine}{Exception}";
var config = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console(outputTemplate: outputTemplate) // Write to the console (optional)
.MinimumLevel.ControlledBy(levelSwitch)
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning);
serviceCollection.AddDbContextFactory<LogDbContext>((_, options) =>
{
options.UseSqlite($"Data Source={dbPath}");
});
/*
"LDK": "Trace",
@ -43,22 +32,11 @@ public static class LoggingConfig
"LDK.BTCPayApp.Core.LDK.LDKPeerHandler": "Information",
"LDK.lightning_background_processor": "Information"*/
if (!isDevEnv)
{
var dirProvider = serviceProvider.GetRequiredService<IDataDirectoryProvider>();
var appDir = dirProvider.GetAppDataDirectory().ConfigureAwait(false).GetAwaiter().GetResult();
var logFilePath = Path.Combine(appDir, "logs", "btcpayapp-.log");
config.WriteTo.File(
logFilePath,
buffered: true,
fileSizeLimitBytes: 5 * 1024 * 1024, // 5 MB
rollOnFileSizeLimit: true,
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 7,
outputTemplate: outputTemplate
);
}
Log.Logger = config.CreateLogger();
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.SQLite(dbPath)
.WriteTo.Console(outputTemplate: OutputTemplate, restrictedToMinimumLevel: minLogLevel)
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning).CreateLogger();
}
}

View File

@ -1,8 +1,11 @@
namespace BTCPayApp.Core.Data;
using System.Text.Json.Serialization;
namespace BTCPayApp.Core.Data;
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum OutboxAction
{
Insert,
Update,
Delete
}
}

View File

@ -5,6 +5,7 @@ using BTCPayApp.Core.Contracts;
using BTCPayApp.Core.Data;
using BTCPayApp.Core.Helpers;
using BTCPayApp.Core.LDK;
using BTCPayApp.Core.Services;
using BTCPayApp.Core.Wallet;
using Laraue.EfCoreTriggers.SqlLite.Extensions;
using Microsoft.AspNetCore.Authorization;
@ -25,16 +26,17 @@ public static class StartupExtensions
options.UseSqlite($"Data Source={dir}/app.db");
options.UseSqlLiteTriggers();
});
serviceCollection.AddHostedService<AppDatabaseMigrator>();
serviceCollection.AddSingleton<ConfigProvider, DatabaseConfigProvider>();
// Configure logging
LoggingConfig.ConfigureLogging(serviceCollection);
serviceCollection.AddHostedService<AppDatabaseMigrator>();
serviceCollection.AddSingleton<ConfigProvider, DatabaseConfigProvider>();
serviceCollection.AddMemoryCache();
serviceCollection.AddHttpClient();
serviceCollection.AddSingleton<BTCPayConnectionManager>();
serviceCollection.AddSingleton<SyncService>();
serviceCollection.AddSingleton<LoggingService>();
serviceCollection.AddSingleton<LightningNodeManager>();
serviceCollection.AddSingleton<OnChainWalletManager>();
serviceCollection.AddSingleton<BTCPayAppServerClient>();

View File

@ -51,7 +51,7 @@ public static class StoreHelpers
// lightning
if (applyLighting && lightning is null && lightningNodeService is { IsActive: true, Node.ApiKeyManager: { } apiKeyManager })
{
var key = await apiKeyManager.Create("Automated BTCPay Store Setup", APIKeyPermission.Write);
var key = await apiKeyManager.GetKeyForStore(storeId, APIKeyPermission.Write);
lightning = await accountManager.GetClient().UpdateStorePaymentMethod(storeId,
LightningNodeManager.PaymentMethodId, new UpdatePaymentMethodRequest
{
@ -72,9 +72,7 @@ public static class StoreHelpers
if (jsonDoc.RootElement.TryGetProperty("accountDerivation", out var derivationSchemeElement) &&
derivationSchemeElement.GetString() is { } derivationScheme &&
config?.Derivations.Any(pair => pair.Value.Identifier == $"DERIVATIONSCHEME:{derivationScheme}") is true)
{
return true;
}
}
return false;
@ -92,10 +90,8 @@ public static class StoreHelpers
connectionStringElement.GetString() is { } connectionString &&
LightningConnectionStringHelper.ExtractValues(connectionString, out var lnConnectionString) is { } lnValues &&
lnConnectionString == "app" && lnValues.TryGetValue("key", out var key) && key is not null &&
await node!.ApiKeyManager!.CheckPermission(key, APIKeyPermission.Read))
{
await node!.ApiKeyManager.CheckPermission(key, APIKeyPermission.Read))
return true;
}
}
return false;

View File

@ -8,8 +8,8 @@
/// <param name="Permission">Read or Write permissions, read implies being able to receive payments, write enables spending as well</param>
public record APIKey(string Key, string Name, APIKeyPermission Permission)
{
public string ConnectionString(string user)
public string ConnectionString(string userId)
{
return $"type=app;key={Key};user={user}";
return $"type=app;user={userId};key={Key}";
}
}
}

View File

@ -1,7 +1,10 @@
namespace BTCPayApp.Core.LDK;
using System.Text.Json.Serialization;
namespace BTCPayApp.Core.LDK;
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum APIKeyPermission
{
Read,
Write,
}
}

View File

@ -3,7 +3,7 @@
namespace BTCPayApp.Core.LDK;
/// <summary>
/// A typed variant of <see cref="ILDKEventHandler"/> that handles a specific type of event
/// A typed variant of <see cref="ILDKEventHandler"/> that handles a specific type of event
/// </summary>
/// <typeparam name="TEvent"></typeparam>
public interface ILDKEventHandler<in TEvent>: ILDKEventHandler where TEvent : Event
@ -18,10 +18,10 @@ public interface ILDKEventHandler
Task Handle(Event @event)
{
var eventType = @event.GetType();
var result = this.GetType().GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ILDKEventHandler<>) && i.GetGenericArguments()[0] == eventType)
var result = GetType().GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ILDKEventHandler<>) && i.GetGenericArguments()[0] == eventType)
?.GetMethod(nameof(ILDKEventHandler<Event>.Handle))
?.Invoke(this, new object[] {@event});
?.Invoke(this, [@event]);
if (result is Task task)
return task;

View File

@ -6,44 +6,24 @@ namespace BTCPayApp.Core.LDK;
/// <summary>
/// Runs the LDK background processor which handles the main event loop for the LDK library.
/// </summary>
public class LDKBackgroundProcessor : IScopedHostedService
public class LDKBackgroundProcessor(
Persister persister,
EventHandler eventHandler,
ChainMonitor chainMonitor,
ChannelManager channelManager,
OnionMessenger onionMessenger,
GossipSync gossipSync,
PeerManager peerManager,
Logger logger,
WriteableScore scorer)
: IScopedHostedService
{
private readonly Persister _persister;
private readonly EventHandler _eventHandler;
private readonly ChainMonitor _chainMonitor;
private readonly ChannelManager _channelManager;
private readonly OnionMessenger _onionMessenger;
private readonly GossipSync _gossipSync;
private readonly PeerManager _peerManager;
private readonly Logger _logger;
private readonly WriteableScore _scorer;
private BackgroundProcessor? _processor;
public LDKBackgroundProcessor(Persister persister,
EventHandler eventHandler,
ChainMonitor chainMonitor,
ChannelManager channelManager,
OnionMessenger onionMessenger,
GossipSync gossipSync,
PeerManager peerManager,
Logger logger,
WriteableScore scorer)
{
_persister = persister;
_eventHandler = eventHandler;
_chainMonitor = chainMonitor;
_channelManager = channelManager;
_onionMessenger = onionMessenger;
_gossipSync = gossipSync;
_peerManager = peerManager;
_logger = logger;
_scorer = scorer;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
await StopAsync(CancellationToken.None);
_processor = BackgroundProcessor.start(_persister, _eventHandler, _chainMonitor, _channelManager, _onionMessenger, _gossipSync, _peerManager, _logger, Option_WriteableScoreZ.some(_scorer));
_processor = BackgroundProcessor.start(persister, eventHandler, chainMonitor, channelManager, onionMessenger, gossipSync, peerManager, logger, Option_WriteableScoreZ.some(scorer));
}
public Task StopAsync(CancellationToken cancellationToken)

View File

@ -7,28 +7,19 @@ namespace BTCPayApp.Core.LDK;
/// <summary>
/// Enables LDK to broadcast transactions through BTCPayServer.
/// </summary>
public class LDKBroadcaster : BroadcasterInterfaceInterface
public class LDKBroadcaster(
Network network,
IEnumerable<IBroadcastGateKeeper> broadcastGateKeepers,
OnChainWalletManager onChainWalletManager)
: BroadcasterInterfaceInterface
{
private readonly Network _network;
private readonly IEnumerable<IBroadcastGateKeeper> _broadcastGateKeepers;
private readonly OnChainWalletManager _onChainWalletManager;
public LDKBroadcaster(
Network network,
IEnumerable<IBroadcastGateKeeper> broadcastGateKeepers, OnChainWalletManager onChainWalletManager)
{
_network = network;
_broadcastGateKeepers = broadcastGateKeepers;
_onChainWalletManager = onChainWalletManager;
}
public void broadcast_transactions(byte[][] txs)
{
List<Task> tasks = new();
foreach (var tx in txs)
{
var loadedTx = Transaction.Load(tx, _network);
if(_broadcastGateKeepers.Any(gk => gk.DontBroadcast(loadedTx)))
var loadedTx = Transaction.Load(tx, network);
if(broadcastGateKeepers.Any(gk => gk.DontBroadcast(loadedTx)))
continue;
tasks.Add(Broadcast(loadedTx));
}
@ -37,7 +28,7 @@ public class LDKBroadcaster : BroadcasterInterfaceInterface
public async Task Broadcast(Transaction transaction, CancellationToken cancellationToken = default)
{
await _onChainWalletManager.BroadcastTransaction(transaction, cancellationToken);
await onChainWalletManager.BroadcastTransaction(transaction, cancellationToken);
}
}

View File

@ -2,17 +2,11 @@
namespace BTCPayApp.Core.LDK;
public class LDKBumpTransactionEventHandler: ILDKEventHandler<Event.Event_BumpTransaction>
public class LDKBumpTransactionEventHandler(BumpTransactionEventHandler bumpTransactionEventHandler) : ILDKEventHandler<Event.Event_BumpTransaction>
{
private readonly BumpTransactionEventHandler _bumpTransactionEventHandler;
public LDKBumpTransactionEventHandler(BumpTransactionEventHandler bumpTransactionEventHandler)
{
_bumpTransactionEventHandler = bumpTransactionEventHandler;
}
public Task Handle(Event.Event_BumpTransaction @event)
{
_bumpTransactionEventHandler.handle_event(@event.bump_transaction);
bumpTransactionEventHandler.handle_event(@event.bump_transaction);
return Task.CompletedTask;
}
}
}

View File

@ -173,7 +173,6 @@ public class LDKChannelSync(
private async Task OnTransactionUpdate(TransactionDetectedRequest txUpdate, CancellationToken cancellationToken)
{
logger.LogInformation("Transaction update {TxId}", txUpdate.TxId);
await PollForTransactionUpdates([new uint256(txUpdate.TxId)]);
logger.LogInformation("Transaction update {TxId} processed", txUpdate.TxId);
}

View File

@ -4,14 +4,8 @@ using org.ldk.structs;
namespace BTCPayApp.Core.LDK;
public class LDKCoinSelector : CoinSelectionSourceInterface
public class LDKCoinSelector(OnChainWalletManager onChainWalletManager) : CoinSelectionSourceInterface
{
private readonly OnChainWalletManager _onChainWalletManager;
public LDKCoinSelector(OnChainWalletManager onChainWalletManager)
{
_onChainWalletManager = onChainWalletManager;
}
public Result_CoinSelectionNoneZ select_confirmed_utxos(byte[] claim_id, Input[] must_spend,
org.ldk.structs.TxOut[] must_pay_to,
int target_feerate_sat_per_1000_weight)
@ -21,7 +15,7 @@ public class LDKCoinSelector : CoinSelectionSourceInterface
var coins = must_spend.Select(x => x.Coin()).ToList();
try
{
var tx = _onChainWalletManager.CreateTransaction(
var tx = onChainWalletManager.CreateTransaction(
txouts, feerate,
coins).GetAwaiter().GetResult();
@ -38,7 +32,7 @@ public class LDKCoinSelector : CoinSelectionSourceInterface
public Result_TransactionNoneZ sign_psbt(byte[] psbtBytes)
{
var signedPsbt = _onChainWalletManager.SignTransaction(psbtBytes).GetAwaiter().GetResult();
var signedPsbt = onChainWalletManager.SignTransaction(psbtBytes).GetAwaiter().GetResult();
return signedPsbt is null
? Result_TransactionNoneZ.err()
: Result_TransactionNoneZ.ok(signedPsbt.ExtractTransaction().ToBytes());

View File

@ -3,21 +3,12 @@ using org.ldk.structs;
namespace BTCPayApp.Core.LDK;
public class LDKEventHandler : EventHandlerInterface
public class LDKEventHandler(IEnumerable<ILDKEventHandler> eventHandlers, LDKWalletLogger ldkWalletLogger) : EventHandlerInterface
{
private readonly IEnumerable<ILDKEventHandler> _eventHandlers;
private readonly LDKWalletLogger _ldkWalletLogger;
public LDKEventHandler(IEnumerable<ILDKEventHandler> eventHandlers, LDKWalletLogger ldkWalletLogger)
{
_eventHandlers = eventHandlers;
_ldkWalletLogger = ldkWalletLogger;
}
public Result_NoneReplayEventZ handle_event(Event @event)
{
_ldkWalletLogger.LogInformation("Received event {Type}", @event.GetType());
_eventHandlers.AsParallel().ForAll(async void (handler) =>
ldkWalletLogger.LogInformation("Received event {Type}", @event.GetType());
eventHandlers.AsParallel().ForAll(async void (handler) =>
{
try
{
@ -25,7 +16,7 @@ public class LDKEventHandler : EventHandlerInterface
}
catch (Exception ex)
{
_ldkWalletLogger.LogError(ex, "Error handling event {EventType} with handler {HandlerType}", @event.GetType(), handler.GetType());
ldkWalletLogger.LogError(ex, "Error handling event {EventType} with handler {HandlerType}", @event.GetType(), handler.GetType());
}
});
return Result_NoneReplayEventZ.ok();

View File

@ -383,9 +383,8 @@ public static class LDKExtensions
var reason = evt.reason.GetType().Name;
switch (evt.reason)
{
case ClosureReason.ClosureReason_CounterpartyForceClosed closureReasonCounterpartyForceClosed:
reason += " with msg from peer: " +closureReasonCounterpartyForceClosed.peer_msg.get_a();
reason += " with msg from peer: " + closureReasonCounterpartyForceClosed.peer_msg.get_a();
break;
case ClosureReason.ClosureReason_ProcessingError closureReasonProcessingError:
reason += " " + closureReasonProcessingError.err;
@ -394,7 +393,6 @@ public static class LDKExtensions
return reason;
}
public static byte[]? GetPreimage(this PaymentPurpose purpose, out byte[]? secret)
{
switch (purpose)

View File

@ -5,18 +5,10 @@ using Script = NBitcoin.Script;
namespace BTCPayApp.Core.LDK;
public class LDKFilter : FilterInterface
public class LDKFilter(LDKNode ldkNode, ConfigProvider configProvider) : FilterInterface
{
private readonly LDKNode _ldkNode;
private readonly ConfigProvider _configProvider;
private readonly SemaphoreSlim _semaphore = new(1, 1);
public LDKFilter(LDKNode ldkNode, ConfigProvider configProvider)
{
_ldkNode = ldkNode;
_configProvider = configProvider;
}
public void register_tx(byte[] txid, byte[] script_pubkey)
{
var script = Script.FromBytesUnsafe(script_pubkey);
@ -33,7 +25,7 @@ public class LDKFilter : FilterInterface
public async Task<List<LDKWatchedOutput>> GetWatchedOutputs()
{
return await GetWatchedOutputs(_configProvider);
return await GetWatchedOutputs(configProvider);
}
public static async Task<List<LDKWatchedOutput>> GetWatchedOutputs(ConfigProvider configProvider)
@ -54,7 +46,7 @@ public class LDKFilter : FilterInterface
}
watchedOutputs.Add(output);
await _configProvider.Set("ln:watchedOutputs", watchedOutputs, true);
await configProvider.Set("ln:watchedOutputs", watchedOutputs, true);
}
finally
{
@ -62,16 +54,15 @@ public class LDKFilter : FilterInterface
}
}
private void Track(Script script)
{
_ = _ldkNode.TrackScripts([script]);
_ = ldkNode.TrackScripts([script]);
}
public async Task OutputsSpent(List<LDKWatchedOutput> spentWatchedOutputs)
{
var watchedOutputs = await GetWatchedOutputs();
watchedOutputs.RemoveAll(w => spentWatchedOutputs.Any(s => s.Outpoint == w.Outpoint));
await _configProvider.Set("ln:watchedOutputs", watchedOutputs, true);
await configProvider.Set("ln:watchedOutputs", watchedOutputs, true);
}
}

View File

@ -4,15 +4,8 @@ using org.ldk.structs;
namespace BTCPayApp.Core.LDK;
public class LDKKVStore:KVStoreInterface
public class LDKKVStore(ConfigProvider configProvider) : KVStoreInterface
{
private readonly ConfigProvider _configProvider;
public LDKKVStore(ConfigProvider configProvider)
{
_configProvider = configProvider;
}
private string CombineKey(string primary_namespace, string secondary_namespace, string key)
{
var str = "ln:";
@ -35,28 +28,28 @@ public class LDKKVStore:KVStoreInterface
public Result_CVec_u8ZIOErrorZ read(string primary_namespace, string secondary_namespace, string key)
{
var key1 = CombineKey(primary_namespace, secondary_namespace, key);
var result = _configProvider.Get<byte[]>(key1).ConfigureAwait(false).GetAwaiter().GetResult();
var result = configProvider.Get<byte[]>(key1).ConfigureAwait(false).GetAwaiter().GetResult();
return result == null ? Result_CVec_u8ZIOErrorZ.err(IOError.LDKIOError_NotFound) : Result_CVec_u8ZIOErrorZ.ok(result);
}
public Result_NoneIOErrorZ write(string primary_namespace, string secondary_namespace, string key, byte[] buf)
{
var key1 = CombineKey(primary_namespace, secondary_namespace, key);
_configProvider.Set(key1, buf, true).ConfigureAwait(false).GetAwaiter().GetResult();
configProvider.Set(key1, buf, true).ConfigureAwait(false).GetAwaiter().GetResult();
return Result_NoneIOErrorZ.ok();
}
public Result_NoneIOErrorZ remove(string primary_namespace, string secondary_namespace, string key, bool lazy)
{
var key1 = CombineKey(primary_namespace, secondary_namespace, key);
_configProvider.Set<byte[]>(key1, null, true).ConfigureAwait(false).GetAwaiter().GetResult();
configProvider.Set<byte[]>(key1, null, true).ConfigureAwait(false).GetAwaiter().GetResult();
return Result_NoneIOErrorZ.ok();
}
public Result_CVec_StrZIOErrorZ list(string primary_namespace, string secondary_namespace)
{
var key1 = CombineKey(primary_namespace, secondary_namespace, string.Empty);
var result = _configProvider.List(key1).ConfigureAwait(false).GetAwaiter().GetResult();
var result = configProvider.List(key1).ConfigureAwait(false).GetAwaiter().GetResult();
return Result_CVec_StrZIOErrorZ.ok(result.ToArray());
}
}
}

View File

@ -4,16 +4,9 @@ using org.ldk.structs;
namespace BTCPayApp.Core.LDK;
public class LDKLogger : LoggerInterface, ILogger
public class LDKLogger(ILoggerFactory loggerFactory) : LoggerInterface, ILogger
{
private readonly ILoggerFactory _loggerFactory;
private readonly ILogger _baseLogger;
public LDKLogger(ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
_baseLogger = loggerFactory.CreateLogger("");
}
private readonly ILogger _baseLogger = loggerFactory.CreateLogger("");
public virtual void log(Record record)
{
@ -26,7 +19,7 @@ public class LDKLogger : LoggerInterface, ILogger
Level.LDKLevel_Error => LogLevel.Error,
Level.LDKLevel_Gossip => LogLevel.Trace,
};
_loggerFactory.CreateLogger(record.get_module_path()).Log(level, "{Args}", record.get_args());
loggerFactory.CreateLogger(record.get_module_path()).Log(level, "{Args}", record.get_args());
}
public IDisposable? BeginScope<TState>(TState state) where TState : notnull
@ -44,4 +37,4 @@ public class LDKLogger : LoggerInterface, ILogger
{
_baseLogger.Log(logLevel, eventId, state, exception, formatter);
}
}
}

View File

@ -27,11 +27,10 @@ public partial class LDKNode :
return (await _memoryCache.GetOrCreateAsync(nameof(GetChannels), async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
var dbChannels = dbContext.LightningChannels.AsNoTracking()
.Include(channel => channel.Aliases).AsAsyncEnumerable();
var channels = ServiceProvider.GetRequiredService<ChannelManager>().list_channels();
var result = new List<(Channel channel, ChannelDetails? channelDetails)>();
await foreach (var dbChannel in dbChannels)
{
@ -49,7 +48,7 @@ public partial class LDKNode :
public async Task Handle(Event.Event_ChannelClosed evt)
{
_logger.LogInformation("Channel {ChannelId} closed: {Reason}", Convert.ToHexString(evt.channel_id.get_a()).ToLowerInvariant(), evt.GetReason());
await AddChannelData(evt.channel_id, new Dictionary<string, JsonElement>()
await AddChannelData(evt.channel_id, new Dictionary<string, JsonElement>
{
{"CloseReason", JsonSerializer.SerializeToElement(evt.reason.write())},
{"CloseReasonHuman", JsonSerializer.SerializeToElement(evt.GetReason())},
@ -60,17 +59,16 @@ public partial class LDKNode :
public async Task Handle(Event.Event_ChannelPending evt)
{
await AddChannelData(evt.channel_id, new Dictionary<string, JsonElement>()
await AddChannelData(evt.channel_id, new Dictionary<string, JsonElement>
{
{"PendingTimestamp", JsonSerializer.SerializeToElement(DateTimeOffset.UtcNow.ToUnixTimeSeconds())}
});
_memoryCache.Remove(nameof(GetChannels));
}
public async Task Handle(Event.Event_ChannelReady evt)
{
await AddChannelData(evt.channel_id, new Dictionary<string, JsonElement>()
await AddChannelData(evt.channel_id, new Dictionary<string, JsonElement>
{
{"ReadyTimestamp", JsonSerializer.SerializeToElement(DateTimeOffset.UtcNow.ToUnixTimeSeconds())}
});
@ -86,12 +84,7 @@ public partial class LDKNode :
}).WithCancellation(cancellationToken);
}
public void PeersChanged()
{
_memoryCache.Remove(nameof(GetPeers));
}
private void InvalidateCache()
public void InvalidateCache()
{
_memoryCache.Remove(nameof(GetPeers));
_memoryCache.Remove(nameof(GetChannels));
@ -140,10 +133,7 @@ public partial class LDKNode :
{
var config = await GetConfig();
var lsp = config.JITLSP;
if (lsp is null)
{
return null;
}
if (string.IsNullOrEmpty(lsp)) return null;
var jits = ServiceProvider.GetServices<IJITService>();
return jits.FirstOrDefault(jit => jit.ProviderName == lsp);
@ -205,22 +195,20 @@ public partial class LDKNode : IAsyncDisposable, IHostedService, IDisposable
return;
}
InvalidateCache();
var walletConfig = await _onChainWalletManager.GetConfig();
var lightningConfig = await _configProvider.Get<LightningConfig>(key: LightningConfig.Key) ?? new LightningConfig();
var keyPath = KeyPath.Parse(lightningConfig.LightningDerivationPath);
Seed = new Mnemonic(walletConfig.Mnemonic).DeriveExtKey().Derive(keyPath).PrivateKey.ToBytes();
var services = ServiceProvider.GetServices<IScopedHostedService>();
_logger.LogInformation("Starting LDKNode services");
var bb = await _onChainWalletManager.GetBestBlock();
if (bb is null)
{
throw new InvalidOperationException("Best block could not be retrieved. Killing the startup");
}
InvalidateCache();
var walletConfig = await _onChainWalletManager.GetConfig();
var lightningConfig = await _configProvider.Get<LightningConfig>(key: LightningConfig.Key) ?? new LightningConfig();
var keyPath = KeyPath.Parse(lightningConfig.LightningDerivationPath);
Seed = new Mnemonic(walletConfig.Mnemonic).DeriveExtKey().Derive(keyPath).PrivateKey.ToBytes();
var services = ServiceProvider.GetServices<IScopedHostedService>();
_logger.LogInformation("Starting LDKNode services");
foreach (var service in services)
{
_logger.LogInformation("Starting {Name}", service.GetType().Name);
@ -284,10 +272,11 @@ public partial class LDKNode : IAsyncDisposable, IHostedService, IDisposable
public byte[] Seed { get; private set; }
public PaymentsManager? PaymentsManager => ServiceProvider.GetRequiredService<PaymentsManager>();
public LightningAPIKeyManager? ApiKeyManager => ServiceProvider.GetRequiredService<LightningAPIKeyManager>();
public PaymentsManager PaymentsManager => ServiceProvider.GetRequiredService<PaymentsManager>();
public LightningAPIKeyManager ApiKeyManager => ServiceProvider.GetRequiredService<LightningAPIKeyManager>();
public LDKPeerHandler PeerHandler => ServiceProvider.GetRequiredService<LDKPeerHandler>();
public PubKey NodeId => new(ServiceProvider.GetRequiredService<ChannelManager>().get_our_node_id());
public Balance[] ClaimableBalances => ServiceProvider.GetRequiredService<ChainMonitor>().get_claimable_balances([]);
public async Task StopAsync(CancellationToken cancellationToken)
{
@ -306,7 +295,6 @@ public partial class LDKNode : IAsyncDisposable, IHostedService, IDisposable
return;
// var identifier = _onChainWalletManager.WalletConfig.Derivations[WalletDerivation.LightningScripts].Identifier;
_logger.LogInformation("Stopping LDKNode services");
var services = ServiceProvider.GetServices<IScopedHostedService>();
var tasks = services.Select(async service =>

View File

@ -25,6 +25,7 @@ public class LDKPeerHandler(
private CancellationTokenSource? _cts;
private TaskCompletionSource? _configTcs;
private readonly ObservableConcurrentDictionary<string, LDKTcpDescriptor> _descriptors = new();
private readonly ConcurrentDictionary<string, Task<LDKTcpDescriptor?>> _connectionTasks = new();
public EndPoint? Endpoint { get; set; }
public Task StartAsync(CancellationToken cancellationToken)
@ -45,7 +46,7 @@ public class LDKPeerHandler(
private void DescriptorsOnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
node.PeersChanged();
node.InvalidateCache();
}
private async Task PeerBtcPayServerHost(object? sender, string? e)
@ -80,7 +81,6 @@ public class LDKPeerHandler(
var chans = await node.GetChannels(ctsToken);
var channels = chans?.Where(pair => pair.channelDetails is not null)
.Select(pair => pair.channelDetails!).ToList() ?? [];
var channelPeers = channels
.Select(details => Convert.ToHexString(details.get_counterparty().get_node_id()).ToLower()).Distinct();
var config = await node.GetConfig();
@ -92,22 +92,26 @@ public class LDKPeerHandler(
foreach (var persistentPeer in missingConnections)
{
var kv = config.Peers[persistentPeer];
var nodeid = new PubKey(persistentPeer);
if (kv.Endpoint is {} endpoint)
{
var cts = CancellationTokenSource.CreateLinkedTokenSource(ctsToken);
cts.CancelAfter(10000);
tasks.Add(ConnectAsync(nodeid, endpoint, cts.Token));
}
if (kv.Endpoint is not { } endpoint) continue;
var nodeId = new PubKey(persistentPeer);
var cts = CancellationTokenSource.CreateLinkedTokenSource(ctsToken);
cts.CancelAfter(10000);
tasks.Add(ConnectAsync(nodeId, endpoint, cts.Token));
}
await Task.WhenAll(tasks);
await Task.Delay(5000, ctsToken);
}
catch (Exception e) when (e is { InnerException: SocketException })
{
_logger.LogError(e.Message);
}
catch (Exception e) when (e is not OperationCanceledException)
{
_logger.LogError(e, "Error while attempting to connect to persistent peers");
}
finally
{
await Task.Delay(5000, ctsToken);
}
}
}
@ -153,7 +157,7 @@ public class LDKPeerHandler(
using var listener = new TcpListener(new IPEndPoint(IPAddress.Any, 0));
listener.Start();
var ip = listener.LocalEndpoint;
Endpoint = new IPEndPoint(IPAddress.Loopback, (int) ip.Port());
Endpoint = new IPEndPoint(IPAddress.Loopback, (int)ip.Port());
while (!cancellationToken.IsCancellationRequested)
{
var result = LDKTcpDescriptor.Inbound(peerManager,
@ -177,33 +181,28 @@ public class LDKPeerHandler(
throw new ArgumentException($"Invalid endpoint: {remote}", nameof(nodeInfo));
}
private readonly ConcurrentDictionary<string, Task<LDKTcpDescriptor?>> _connectionTasks = new();
public async Task<LDKTcpDescriptor?> ConnectAsync(PubKey peerNodeId, PeerInfo peerInfo, CancellationToken cancellationToken = default)
{
if (peerInfo.Endpoint is {} endpoint)
{
if (peerInfo.Label is not null)
_logger.LogInformation("Attempting to connect to {NodeId} at {Endpoint} ({Label})", peerNodeId, endpoint.ToEndpointString(), peerInfo.Label);
return await ConnectAsync(peerNodeId, endpoint, cancellationToken);
}
return null;
if (peerInfo.Endpoint is not { } endpoint) return null;
if (peerInfo.Label is not null)
_logger.LogInformation("Attempting to connect to {NodeId} at {Endpoint} ({Label})", peerNodeId, endpoint.ToEndpointString(), peerInfo.Label);
return await ConnectAsync(peerNodeId, endpoint, cancellationToken);
}
public async Task<LDKTcpDescriptor?> ConnectAsync(PubKey theirNodeId, EndPoint remote, CancellationToken cancellationToken = default)
{
var nodeId = theirNodeId.ToString();
//cache this task so that we don't have multiple attempts to connect to the same place
if (_connectionTasks.TryGetValue(theirNodeId.ToString(), out var task))
if (_connectionTasks.TryGetValue(nodeId, out var task))
{
_logger.LogInformation("Already attempting to connect to {NodeId}", theirNodeId);
_logger.LogInformation("Already attempting to connect to {NodeId}", nodeId);
return await task.WithCancellation(cancellationToken);
}
var tcs = new TaskCompletionSource<LDKTcpDescriptor?>();
try
{
if (!_connectionTasks.TryAdd(theirNodeId.ToString(), tcs.Task))
if (!_connectionTasks.TryAdd(nodeId, tcs.Task))
return null;
if (channelManager.get_our_node_id().SequenceEqual(theirNodeId.ToBytes()))
@ -218,7 +217,7 @@ public class LDKPeerHandler(
{
var needsUpdate = false;
var config = await node.GetConfig();
if (!config.Peers.TryGetValue(theirNodeId.ToString(), out var peer))
if (!config.Peers.TryGetValue(nodeId, out var peer))
{
peer = new PeerInfo { Trusted = true };
needsUpdate = true;
@ -235,20 +234,25 @@ public class LDKPeerHandler(
}
if (needsUpdate)
await node.Peer(theirNodeId, peer);
_descriptors.TryAdd(result.Id, result);
peerManager.process_events();
await Task.Delay(TimeSpan.FromMilliseconds(250), cancellationToken);
}
tcs.TrySetResult(result);
}
catch (SocketException e)
{
// wrap the original exception to report on the failing node URI
tcs.TrySetException(new Exception($"Socket connection to {nodeId}@{remote} failed: {e.Message}", e));
}
catch (Exception e)
{
tcs.TrySetException(e);
}
finally
{
_connectionTasks.TryRemove(theirNodeId.ToString(), out _);
_connectionTasks.TryRemove(nodeId, out _);
}
return await tcs.Task;
@ -265,6 +269,8 @@ public class LDKPeerHandler(
peer.Persistent = false;
await node.Peer(id, peer);
}
peerManager.process_events();
_logger.LogInformation("Disconnected from {NodeId}", id);
}
}

View File

@ -147,7 +147,6 @@ public class LDKPersistInterface : PersistInterface, IScopedHostedService
if (otherId == fundingId)
{
otherId = null;
}
if (otherId != null)
{
@ -194,16 +193,7 @@ public class LDKPersistInterface : PersistInterface, IScopedHostedService
AsyncExtensions.RunInOtherThread(() =>
_node.ArchiveChannel(ChannelId.v1_from_funding_outpoint(channelFundingOutpoint))).GetAwaiter().GetResult();
}
//
// public async Task StartAsync(CancellationToken cancellationToken)
// {
// throw new NotImplementedException();
// }
//
// public async Task StopAsync(CancellationToken cancellationToken)
// {
// throw new NotImplementedException();
// }
public Task StartAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;

View File

@ -2,30 +2,23 @@ using org.ldk.structs;
namespace BTCPayApp.Core.LDK;
public class LDKPersister : PersisterInterface
public class LDKPersister(LDKNode ldkNode) : PersisterInterface
{
private readonly LDKNode _ldkNode;
public LDKPersister(LDKNode ldkNode)
public Result_NoneIOErrorZ persist_manager(ChannelManager channelManager)
{
_ldkNode = ldkNode;
}
public Result_NoneIOErrorZ persist_manager(ChannelManager channel_manager)
{
_ldkNode.UpdateChannelManager(channel_manager).ConfigureAwait(false).GetAwaiter().GetResult();
ldkNode.UpdateChannelManager(channelManager).ConfigureAwait(false).GetAwaiter().GetResult();
return Result_NoneIOErrorZ.ok();
}
public Result_NoneIOErrorZ persist_graph(NetworkGraph network_graph)
public Result_NoneIOErrorZ persist_graph(NetworkGraph networkGraph)
{
_ldkNode.UpdateNetworkGraph(network_graph).ConfigureAwait(false).GetAwaiter().GetResult();
ldkNode.UpdateNetworkGraph(networkGraph).ConfigureAwait(false).GetAwaiter().GetResult();
return Result_NoneIOErrorZ.ok();
}
public Result_NoneIOErrorZ persist_scorer(WriteableScore scorer)
{
_ldkNode.UpdateScore(scorer).ConfigureAwait(false).GetAwaiter().GetResult();
ldkNode.UpdateScore(scorer).ConfigureAwait(false).GetAwaiter().GetResult();
return Result_NoneIOErrorZ.ok();
}
}
}

View File

@ -6,32 +6,21 @@ using org.ldk.structs;
namespace BTCPayApp.Core.LDK;
public class LDKRapidGossipSyncer : IScopedHostedService
public class LDKRapidGossipSyncer(
LDKNode ldkNode,
RapidGossipSync rapidGossipSync,
NetworkGraph networkGraph,
IHttpClientFactory httpClientFactory,
ILogger<LDKRapidGossipSyncer> logger)
: IScopedHostedService
{
private readonly LDKNode _ldkNode;
private readonly RapidGossipSync _rapidGossipSync;
private readonly NetworkGraph _networkGraph;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<LDKRapidGossipSyncer> _logger;
private CancellationTokenSource? _cts;
private TaskCompletionSource _configUpdated = new();
public LDKRapidGossipSyncer(LDKNode ldkNode,
RapidGossipSync rapidGossipSync,
NetworkGraph networkGraph,
IHttpClientFactory httpClientFactory, ILogger<LDKRapidGossipSyncer> logger)
{
_ldkNode = ldkNode;
_rapidGossipSync = rapidGossipSync;
_networkGraph = networkGraph;
_httpClientFactory = httpClientFactory;
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_ldkNode.ConfigUpdated += OnConfigUpdated;
ldkNode.ConfigUpdated += OnConfigUpdated;
_ = UpdateNetworkGraph();
return Task.CompletedTask;
}
@ -49,7 +38,7 @@ public class LDKRapidGossipSyncer : IScopedHostedService
try
{
_configUpdated = new();
var config = await _ldkNode.GetConfig();
var config = await ldkNode.GetConfig();
if (config.RapidGossipSyncUrl is null)
{
try
@ -64,30 +53,30 @@ public class LDKRapidGossipSyncer : IScopedHostedService
// wait until config is updated or _cts is cancelled
}
var timestamp = _networkGraph.get_last_rapid_gossip_sync_timestamp() is Option_u32Z.Option_u32Z_Some some
var timestamp = networkGraph.get_last_rapid_gossip_sync_timestamp() is Option_u32Z.Option_u32Z_Some some
? some.some : 0;
var uri = new Uri(config.RapidGossipSyncUrl, $"/snapshot/{timestamp}");
var response = await _httpClientFactory.CreateClient("rgs").GetAsync(uri, _cts.Token);
var response = await httpClientFactory.CreateClient("rgs").GetAsync(uri, _cts.Token);
if (!response.IsSuccessStatusCode)
{
_logger.LogError("Failed to download snapshot from {uri}", uri);
logger.LogError("Failed to download snapshot from {uri}", uri);
continue;
}
var snapshot = await response.Content.ReadAsByteArrayAsync();
var result =
_rapidGossipSync.update_network_graph_no_std(snapshot,
rapidGossipSync.update_network_graph_no_std(snapshot,
Option_u64Z.some(DateTime.Now.ToUnixTimestamp()));
if (result is Result_u32GraphSyncErrorZ.Result_u32GraphSyncErrorZ_Err err)
{
switch (err.err)
{
case GraphSyncError.GraphSyncError_DecodeError graphSyncErrorDecodeError:
_logger.LogError(
logger.LogError(
$"Failed to decode snapshot from {uri} with error {graphSyncErrorDecodeError.decode_error.GetType().Name}");
break;
case GraphSyncError.GraphSyncError_LightningError graphSyncErrorLightningError:
_logger.LogError(
logger.LogError(
$"Failed to update network graph with error {graphSyncErrorLightningError.lightning_error.get_err()}");
// config = await _ldkNode.GetConfig();
// await _ldkNode.UpdateConfig(config);
@ -106,7 +95,7 @@ public class LDKRapidGossipSyncer : IScopedHostedService
}
catch (Exception e)
{
_logger.LogError(e, "Error while updating network graph");
logger.LogError(e, "Error while updating network graph");
await Task.Delay(10000, _cts.Token);
}
}
@ -114,7 +103,7 @@ public class LDKRapidGossipSyncer : IScopedHostedService
public async Task StopAsync(CancellationToken cancellationToken)
{
_ldkNode.ConfigUpdated -= OnConfigUpdated;
ldkNode.ConfigUpdated -= OnConfigUpdated;
if (_cts is not null)
{
await _cts.CancelAsync();

View File

@ -5,16 +5,9 @@ using UInt128 = org.ldk.util.UInt128;
namespace BTCPayApp.Core.LDK;
public class LDKSignerProvider : SignerProviderInterface
public class LDKSignerProvider(KeysManager innerSigner, LDKNode ldkNode) : SignerProviderInterface
{
private readonly LDKNode _ldkNode;
private readonly SignerProvider _innerSigner;
public LDKSignerProvider(KeysManager innerSigner, LDKNode ldkNode)
{
_ldkNode = ldkNode;
_innerSigner = innerSigner.as_SignerProvider();
}
private readonly SignerProvider _innerSigner = innerSigner.as_SignerProvider();
public byte[] generate_channel_keys_id(bool inbound, long channel_value_satoshis, UInt128 user_channel_id)
{
@ -33,13 +26,13 @@ public class LDKSignerProvider : SignerProviderInterface
public Result_CVec_u8ZNoneZ get_destination_script(byte[] channel_keys_id)
{
var script = _ldkNode.DeriveScript().GetAwaiter().GetResult();
var script = ldkNode.DeriveScript().GetAwaiter().GetResult();
return Result_CVec_u8ZNoneZ.ok(script.ToBytes());
}
public Result_ShutdownScriptNoneZ get_shutdown_scriptpubkey()
{
var script = _ldkNode.DeriveScript().GetAwaiter().GetResult();
var script = ldkNode.DeriveScript().GetAwaiter().GetResult();
if (!script.IsScriptType(ScriptType.Witness))
throw new NotSupportedException("Generated a non witness script.");

View File

@ -149,19 +149,6 @@ public class LDKTcpDescriptor : SocketDescriptorInterface
}
}
private void Resume()
{
try
{
_readSemaphore.Release();
_logger.LogDebug("Resuming read");
}
catch (Exception)
{
// ignored
}
}
public long send_data(byte[] data, bool resumeRead)
{
try
@ -169,7 +156,6 @@ public class LDKTcpDescriptor : SocketDescriptorInterface
_logger.LogTrace("Sending {Bytes} bytes of data to peer", data.Length);
var result = _tcpClient.Client.Send(data);
_logger.LogTrace("Sent {Bytes} bytes of data to peer", result);
if (resumeRead) Resume();
return result;
}
catch (Exception e)

View File

@ -1,8 +1,3 @@
namespace BTCPayApp.Core.LDK;
public class LDKWalletLogger : LDKLogger
{
public LDKWalletLogger(LDKWalletLoggerFactory ldkWalletLoggerFactory) : base(ldkWalletLoggerFactory)
{
}
}
public class LDKWalletLogger(LDKWalletLoggerFactory ldkWalletLoggerFactory) : LDKLogger(ldkWalletLoggerFactory);

View File

@ -2,15 +2,8 @@
namespace BTCPayApp.Core.LDK;
public class LDKWalletLoggerFactory : ILoggerFactory
public class LDKWalletLoggerFactory(ILoggerFactory loggerFactory) : ILoggerFactory
{
private readonly ILoggerFactory _inner;
public LDKWalletLoggerFactory(ILoggerFactory loggerFactory)
{
_inner = loggerFactory;
}
public void Dispose()
{
//ignore as this is scoped
@ -18,7 +11,7 @@ public class LDKWalletLoggerFactory : ILoggerFactory
public void AddProvider(ILoggerProvider provider)
{
_inner.AddProvider(provider);
loggerFactory.AddProvider(provider);
}
public List<string> Logs { get; } = new List<string>();
@ -26,11 +19,11 @@ public class LDKWalletLoggerFactory : ILoggerFactory
public ILogger CreateLogger(string category)
{
var categoryName = string.IsNullOrWhiteSpace(category) ? "LDK" : $"LDK.{category}";
LoggerWrapper logger = new LoggerWrapper(_inner.CreateLogger(categoryName));
LoggerWrapper logger = new LoggerWrapper(loggerFactory.CreateLogger(categoryName));
logger.LogEvent += (sender, message) =>
Logs.Add(DateTime.Now.ToShortTimeString() + " " + categoryName + message);
return logger;
}
}
}

View File

@ -2,42 +2,51 @@
namespace BTCPayApp.Core.LDK;
public class LightningAPIKeyManager
public class LightningAPIKeyManager(ConfigProvider configProvider)
{
private const string LightningAPIKeyConfigKey = "LightningAPIKeys";
private readonly ConfigProvider _configProvider;
public LightningAPIKeyManager(ConfigProvider configProvider)
public async Task<APIKey> GetKeyForStore(string storeId, APIKeyPermission permission)
{
_configProvider = configProvider;
}
public async Task<List<APIKey>> List()
{
var keys = await _configProvider.Get<List<APIKey>>(LightningAPIKeyConfigKey) ?? [];
return keys;
return await GetOrCreate($"BTCPay Store {storeId}", permission);
}
public async Task Revoke(string key)
{
var keys = await List();
if(keys.RemoveAll(k => k.Key == key)>0)
await _configProvider.Set(LightningAPIKeyConfigKey, keys, true);
if (keys.RemoveAll(k => k.Key == key)>0)
await configProvider.Set(LightningAPIKeyConfigKey, keys, true);
}
public async Task<APIKey> Create(string name, APIKeyPermission permission)
{
var keys = await List();
var newKey = new APIKey(Guid.NewGuid().ToString(), name, permission);
keys.Add(newKey);
await _configProvider.Set(LightningAPIKeyConfigKey, keys, true);
return newKey;
}
public async Task<bool> CheckPermission(string key, APIKeyPermission permission)
{
var keys = await List();
return keys.Any(k => k.Key == key && k.Permission >= permission);
}
}
private async Task<List<APIKey>> List()
{
var keys = await configProvider.Get<List<APIKey>>(LightningAPIKeyConfigKey) ?? [];
return keys;
}
private async Task<APIKey?> Get(string name, APIKeyPermission permission)
{
var keys = await List();
return keys.FirstOrDefault(k => k.Name == name && k.Permission == permission);
}
private async Task<APIKey> Create(string name, APIKeyPermission permission)
{
var keys = await List();
var newKey = new APIKey(Guid.NewGuid().ToString(), name, permission);
keys.Add(newKey);
await configProvider.Set(LightningAPIKeyConfigKey, keys, true);
return newKey;
}
private async Task<APIKey> GetOrCreate(string name, APIKeyPermission permission)
{
return await Get(name, permission) ?? await Create(name, permission);
}
}

View File

@ -2,31 +2,24 @@
namespace BTCPayApp.Core.LDK;
public class LoggerWrapper : ILogger
public class LoggerWrapper(ILogger inner) : ILogger
{
private readonly ILogger _inner;
public LoggerWrapper(ILogger inner)
{
_inner = inner;
}
public IDisposable? BeginScope<TState>(TState state) where TState : notnull
{
return _inner.BeginScope(state);
return inner.BeginScope(state);
}
public bool IsEnabled(LogLevel logLevel)
{
return _inner.IsEnabled(logLevel);
return inner.IsEnabled(logLevel);
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func<TState, Exception?, string> formatter)
{
_inner.Log(logLevel, eventId, state, exception, formatter);
inner.Log(logLevel, eventId, state, exception, formatter);
LogEvent?.Invoke(this, formatter(state, exception));
}
public event EventHandler<string>? LogEvent;
}
}

View File

@ -75,10 +75,8 @@ public class PaymentsManager :
public async Task<AppLightningPayment> RequestPayment(LightMoney amount, TimeSpan expiry, uint256 descriptionHash)
{
var amt = amount == LightMoney.Zero ? Option_u64Z.none() : Option_u64Z.some(amount.MilliSatoshi);
var now = DateTimeOffset.UtcNow;
var epoch = now.ToUnixTimeSeconds();
var descHashBytes = Sha256.from_bytes(descriptionHash.ToBytes());
var lsp = await _ldkNode.GetJITLSPService();
@ -117,7 +115,7 @@ public class PaymentsManager :
};
var parsedOriginalInvoice = BOLT11PaymentRequest.Parse(originalInvoice.to_str(), _network);
var lp = new AppLightningPayment()
var lp = new AppLightningPayment
{
Inbound = true,
PaymentId = "default",

View File

@ -1,13 +0,0 @@
using BTCPayServer.Lightning;
namespace BTCPayApp.Core.LDK;
public class PeersChangedEventArgs : EventArgs
{
public List<NodeInfo> PeerNodeIds { get; set; }
public PeersChangedEventArgs(List<NodeInfo> peerNodeIds)
{
PeerNodeIds = peerNodeIds;
}
}

View File

@ -0,0 +1,17 @@
using BTCPayServer.Client.Models;
using BTCPayServer.JsonConverters;
using Newtonsoft.Json;
namespace BTCPayApp.Core.Models;
public class CreatePosInvoiceRequest
{
public string? AppId { get; set; }
public List<AppCartItem>? Cart { get; set; }
public int? DiscountPercent { get; set; }
[JsonConverter(typeof(NumericStringJsonConverter))]
public decimal? DiscountAmount { get; set; }
[JsonConverter(typeof(NumericStringJsonConverter))]
public decimal? Tip { get; set; }
public string? PosData { get; set; }
}

View File

@ -2,7 +2,10 @@ namespace BTCPayApp.Core.Models;
public class CreateStoreData
{
public string? DefaultCurrency { get; set; }
public string? RecommendedExchangeId { get; set; }
public string? Name { get; set; }
public string DefaultCurrency { get; set; } = null!;
public Dictionary<string, string>? Exchanges { get; set; }
public string? PreferredExchangeId { get; set; }
public bool CanEditPreferredExchange { get; set; }
public bool CanAutoCreate { get; set; }
}

View File

@ -0,0 +1,10 @@
namespace BTCPayApp.Core.Models;
public class LoginInfoResult
{
public string? Email { get; set; }
public bool? HasPassword { get; set; }
public bool? IsEmailConfirmed { get; set; }
public bool? IsApproved { get; set; }
public bool? IsDisabled { get; set; }
}

View File

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BTCPayApp.Core.Models
{
public class NfcLnUrlRecord
{
public byte[]? Payload { get; set; }
//
// Summary:
// LnUrl
public string? LnUrl { get; set; }
//
// Summary:
// String formatted payload
public string? Message { get; set; }
//
// Summary:
// Two letters ISO 639-1 Language Code (ex: en, fr, de...)
public string? LanguageCode { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BTCPayApp.Core.Models
{
public class SubmitLnUrlRequest
{
public string? Lnurl { get; set; }
public string? InvoiceId { get; set; }
public long? Amount { get; set; }
}
}

View File

@ -1,38 +1,35 @@
using BTCPayApp.Core.Contracts;
using Serilog.Core;
using System.Text.Json;
using BTCPayApp.Core.Data;
using Microsoft.EntityFrameworkCore;
using Serilog.Events;
using Serilog.Parsing;
namespace BTCPayApp.Core.Services;
public class LoggingService(IDataDirectoryProvider dataDirectory, LoggingLevelSwitch levelSwitch)
public class LoggingService(IDbContextFactory<LogDbContext> dbContextFactory)
{
public async Task<string> GetLatestLogAsync()
public static readonly LogEventLevel[] Levels = [LogEventLevel.Verbose, LogEventLevel.Debug, LogEventLevel.Information, LogEventLevel.Warning, LogEventLevel.Error];
public async Task<string?> GetLatestLogAsync(LogEventLevel minLevel, int count = 100)
{
try
await using var dbContext = await dbContextFactory.CreateDbContextAsync();
var levels = Levels.Skip((int)minLevel).Select(l => l.ToString());
var parser = new MessageTemplateParser();
var logs = await dbContext.Logs
.Where(e => levels.Contains(e.Level))
.OrderByDescending(e => e.TimeStamp)
.Take(count)
.ToArrayAsync();
var lines = logs.Select(l =>
{
var logDir = Path.Combine(await dataDirectory.GetAppDataDirectory(), "logs");
var latestLog = Directory.GetFiles(logDir)
.OrderByDescending(f => f)
.FirstOrDefault();
return latestLog != null
? await File.ReadAllTextAsync(latestLog)
: "No logs available";
}
catch (Exception ex)
{
return $"Error reading logs: {ex.Message}";
}
}
public async Task<string> GetAppLogFilePath()
{
return Path.Combine(await dataDirectory.GetAppDataDirectory(), "logs");
}
public LogEventLevel LogLevel
{
get => levelSwitch.MinimumLevel;
set => levelSwitch.MinimumLevel = value;
var level = Enum.Parse<LogEventLevel>(l.Level, true);
var tmpl = parser.Parse(l.RenderedMessage);
var props = JsonSerializer.Deserialize<Dictionary<string, object>>(l.Properties);
var properties = props?.Select(p => new LogEventProperty(p.Key, new ScalarValue(p.Value))) ?? [];
var e = new LogEvent(l.TimeStamp, level, null, tmpl, properties);
var end = string.IsNullOrEmpty(l.Exception) ? string.Empty : $"{Environment.NewLine}{l.Exception}";
return $"[{e.Timestamp:yyyy-MM-dd HH:mm:ss} {e.Level.ToString()[..3].ToUpperInvariant()}] {e.RenderMessage()} ({e.Properties["SourceContext"]}){end}{Environment.NewLine}";
});
return logs.Length != 0 ? string.Join("", lines.Reverse()) : null;
}
}

View File

@ -1,3 +1,4 @@
using System.Linq.Expressions;
using BTCPayApp.Core.BTCPayServer;
using BTCPayApp.Core.Data;
using BTCPayApp.Core.Helpers;
@ -8,26 +9,37 @@ using Microsoft.Extensions.Logging;
namespace BTCPayApp.Core.Wallet;
public class LightningNodeManager : BaseHostedService
public class LightningNodeManager(
IDbContextFactory<AppDbContext> dbContextFactory,
ILogger<LightningNodeManager> logger,
OnChainWalletManager onChainWalletManager,
BTCPayConnectionManager btcPayConnectionManager,
IServiceScopeFactory serviceScopeFactory)
: BaseHostedService(logger)
{
public const string PaymentMethodId = "BTC-LN";
private readonly IDbContextFactory<AppDbContext> _dbContextFactory;
private readonly ILogger<LightningNodeManager> _logger;
private readonly OnChainWalletManager _onChainWalletManager;
private readonly BTCPayConnectionManager _btcPayConnectionManager;
private readonly IServiceScopeFactory _serviceScopeFactory;
private IServiceScope? _nodeScope;
public LDKNode? Node => _nodeScope?.ServiceProvider.GetService<LDKNode>();
private LightningNodeState _state = LightningNodeState.Init;
public bool IsHubConnected => _btcPayConnectionManager.ConnectionState is BTCPayConnectionState.ConnectedAsPrimary;
private async Task<bool> IsOnchainLightningDerivationConfigured() => (await _onChainWalletManager.GetConfig())?.Derivations.ContainsKey(WalletDerivation.LightningScripts) is true;
public async Task<bool> CanConfigureLightningNode () => IsHubConnected && await _onChainWalletManager.IsConfigured() && !await IsOnchainLightningDerivationConfigured() && State == LightningNodeState.NotConfigured;
// public string? ConnectionString => IsOnchainLightningDerivationConfigured && _accountManager.GetUserInfo() is {} acc
// ? $"type=app;user={acc.UserId}": null;
public bool IsActive => State == LightningNodeState.Loaded;
public bool IsHubConnected => btcPayConnectionManager.ConnectionState is BTCPayConnectionState.ConnectedAsPrimary;
private async Task<bool> IsOnchainLightningDerivationConfigured () => (await onChainWalletManager.GetConfig())?.Derivations.ContainsKey(WalletDerivation.LightningScripts) is true;
public async Task<bool> CanConfigureLightningNode () => IsHubConnected && await onChainWalletManager.IsConfigured() && !await IsOnchainLightningDerivationConfigured() && State == LightningNodeState.NotConfigured;
public event AsyncEventHandler<(LightningNodeState Old, LightningNodeState New)>? StateChanged;
public LDKNode? Node
{
get
{
try
{
return _nodeScope?.ServiceProvider.GetService<LDKNode>();
}
catch (Exception e)
{
logger.LogError(e, "Error while getting LDKNode");
return null;
}
}
}
public LightningNodeState State
{
@ -38,47 +50,29 @@ public class LightningNodeManager : BaseHostedService
return;
var old = _state;
_state = value;
_logger.LogInformation("Lightning node state changed: {Old} -> {State}", old, _state);
logger.LogInformation("Lightning node state changed: {Old} -> {State}", old, _state);
StateChanged?.Invoke(this, (old, value));
}
}
public event AsyncEventHandler<(LightningNodeState Old, LightningNodeState New)>? StateChanged;
public LightningNodeManager(
IDbContextFactory<AppDbContext> dbContextFactory,
ILogger<LightningNodeManager> logger,
OnChainWalletManager onChainWalletManager,
BTCPayConnectionManager btcPayConnectionManager,
IServiceScopeFactory serviceScopeFactory) : base(logger)
{
_dbContextFactory = dbContextFactory;
_logger = logger;
_onChainWalletManager = onChainWalletManager;
_btcPayConnectionManager = btcPayConnectionManager;
_serviceScopeFactory = serviceScopeFactory;
}
public async Task StartNode()
{
if (_nodeScope is not null || State is LightningNodeState.Loaded or LightningNodeState.NotConfigured)
return;
if (onChainWalletManager.State is not OnChainWalletState.Loaded)
{
State = LightningNodeState.WaitingForConnection;
return;
}
_logger.LogInformation("Starting lightning node");
logger.LogInformation("Starting lightning node");
await ControlSemaphore.WaitAsync();
try
{
if (_onChainWalletManager.State is not OnChainWalletState.Loaded)
{
State = LightningNodeState.WaitingForConnection;
return;
}
if (_nodeScope is null)
{
_nodeScope = _serviceScopeFactory.CreateScope();
_nodeScope = serviceScopeFactory.CreateScope();
CancellationTokenSource = new CancellationTokenSource();
}
await Node!.StartAsync(CancellationTokenSource.Token);
@ -88,7 +82,7 @@ public class LightningNodeManager : BaseHostedService
catch (Exception e)
{
_nodeScope?.Dispose();
_logger.LogError(e, "Error while starting lightning node");
logger.LogError(e, "Error while starting lightning node");
_nodeScope = null;
State = LightningNodeState.Error;
}
@ -107,12 +101,12 @@ public class LightningNodeManager : BaseHostedService
await ControlSemaphore.WaitAsync();
try
{
_logger.LogInformation("Stopping lightning node");
logger.LogInformation("Stopping lightning node");
if (Node != null) await Node.StopAsync(CancellationToken.None);
}
catch (Exception e)
{
_logger.LogError(e, "Error while stopping lightning node");
logger.LogError(e, "Error while stopping lightning node");
}
finally
{
@ -133,8 +127,8 @@ public class LightningNodeManager : BaseHostedService
await ControlSemaphore.WaitAsync();
try
{
await _onChainWalletManager.RemoveDerivation(WalletDerivation.LightningScripts);
await using var context = await _dbContextFactory.CreateDbContextAsync();
await onChainWalletManager.RemoveDerivation(WalletDerivation.LightningScripts);
await using var context = await dbContextFactory.CreateDbContextAsync();
context.LightningPayments.RemoveRange(context.LightningPayments);
// context.OutboxItems.RemoveRange(context.OutboxItems);
context.Settings.RemoveRange(context.Settings.Where(s => s.Key.StartsWith("ln:")));
@ -156,13 +150,13 @@ public class LightningNodeManager : BaseHostedService
if (!IsHubConnected)
throw new InvalidOperationException("Cannot configure lightning node without BTCPay connection");
if (!await _onChainWalletManager.IsConfigured())
if (!await onChainWalletManager.IsConfigured())
throw new InvalidOperationException("Cannot configure lightning node without on-chain wallet configuration");
if (await IsOnchainLightningDerivationConfigured())
throw new InvalidOperationException("On-chain wallet is already configured with a lightning derivation");
_logger.LogInformation("Generating lightning node");
await _onChainWalletManager.AddDerivation(WalletDerivation.LightningScripts, "Lightning", null);
logger.LogInformation("Generating lightning node");
await onChainWalletManager.AddDerivation(WalletDerivation.LightningScripts, "Lightning", null);
// await _onChainWalletManager.AddDerivation(WalletDerivation.SpendableOutputs, "Lightning Spendables", null);
State = LightningNodeState.WaitingForConnection;
}
@ -219,7 +213,7 @@ public class LightningNodeManager : BaseHostedService
newState = LightningNodeState.WaitingForConnection;
break;
}
if (!await _onChainWalletManager.IsConfigured() || !await IsOnchainLightningDerivationConfigured())
if (!await onChainWalletManager.IsConfigured() || !await IsOnchainLightningDerivationConfigured())
{
newState = LightningNodeState.NotConfigured;
break;
@ -244,13 +238,13 @@ public class LightningNodeManager : BaseHostedService
StateChanged += OnStateChanged;
await StateChanged.Invoke(this, (LightningNodeState.Init, LightningNodeState.Init));
// _btcPayConnectionManager.ConnectionChanged += OnConnectionChanged;
_onChainWalletManager.StateChanged += OnChainWalletManagerOnStateChanged;
onChainWalletManager.StateChanged += OnChainWalletManagerOnStateChanged;
}
protected override Task ExecuteStopAsync(CancellationToken cancellationToken)
{
// _btcPayConnectionManager.ConnectionChanged -= OnConnectionChanged;
_onChainWalletManager.StateChanged += OnChainWalletManagerOnStateChanged;
onChainWalletManager.StateChanged += OnChainWalletManagerOnStateChanged;
StateChanged -= OnStateChanged;
_nodeScope?.Dispose();
return Task.CompletedTask;

View File

@ -1,5 +1,8 @@
namespace BTCPayApp.Core.Wallet;
using System.Text.Json.Serialization;
namespace BTCPayApp.Core.Wallet;
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum LightningNodeState
{
Init,
@ -8,6 +11,5 @@ public enum LightningNodeState
Loading,
Loaded,
Stopped,
Error,
Inactive
Error
}

View File

@ -1,3 +1,4 @@
using System.Text.Json.Serialization;
using BTCPayApp.Core.Backup;
using BTCPayApp.Core.BTCPayServer;
using BTCPayApp.Core.Contracts;
@ -729,6 +730,7 @@ public class OnChainWalletManager : BaseHostedService
}
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum OnChainWalletState
{
Init,

View File

@ -12,6 +12,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.DataProtection" Version="8.0.11" />
<PackageReference Include="Microsoft.JSInterop" Version="8.0.16" />
<PackageReference Include="Plugin.Fingerprint" Version="3.0.0-beta.1" />
</ItemGroup>

View File

@ -0,0 +1,12 @@
using BTCPayApp.Core.Contracts;
using Microsoft.JSInterop;
namespace BTCPayApp.Desktop.Services;
public class EmailService(IJSRuntime jSRuntime) : IEmailService
{
public async Task SendAsync(string subject, string body, string recipient, string? attachFilePath = null)
{
await jSRuntime.InvokeVoidAsync("Interop.sendEmail", subject, body, recipient);
}
}

View File

@ -1,6 +1,5 @@
using BTCPayApp.Core.Contracts;
using BTCPayApp.Core.Data;
using BTCPayApp.Core.Helpers;
using BTCPayApp.Desktop.Services;
using Microsoft.Extensions.DependencyInjection;
using Plugin.Fingerprint.Abstractions;
@ -15,9 +14,9 @@ public static class StartupExtensions
options.ApplicationDiscriminator = "BTCPayApp";
});
serviceCollection.AddSingleton<IDataDirectoryProvider, DesktopDataDirectoryProvider>();
// serviceCollection.AddSingleton<IConfigProvider, DesktopConfigProvider>();
serviceCollection.AddSingleton<ISecureConfigProvider, DesktopSecureConfigProvider>();
serviceCollection.AddSingleton<IFingerprint, StubFingerprintProvider>();
serviceCollection.AddScoped<IEmailService, EmailService>();
return serviceCollection;
}

View File

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">
<Project Sdk="Microsoft.NET.Sdk.Razor">
<PropertyGroup>
<TargetFrameworks>net8.0-android;</TargetFrameworks>
<TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('linux'))">net8.0-android;</TargetFrameworks>
@ -23,7 +23,7 @@
<ApplicationVersion>1</ApplicationVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">14.2</SupportedOSPlatformVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">24.0</SupportedOSPlatformVersion>
<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">26.0</SupportedOSPlatformVersion>
</PropertyGroup>
<PropertyGroup Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">
@ -41,12 +41,7 @@
<EmbedAssembliesIntoApk>True</EmbedAssembliesIntoApk>
</PropertyGroup>
<PropertyGroup Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android' And $(Configuration) == 'Debug'">
<DebugSymbols>True</DebugSymbols>
</PropertyGroup>
<PropertyGroup Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android' And '$(Configuration)' == 'Release'">
<DebugSymbols>False</DebugSymbols>
<PublishTrimmed>False</PublishTrimmed>
<AndroidKeyStore>True</AndroidKeyStore>
<AndroidSigningKeyStore>../btcpayapp.keystore</AndroidSigningKeyStore>
@ -75,6 +70,7 @@
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.3" />
<PackageReference Include="Microsoft.Maui.Controls" Version="8.0.100" />
<PackageReference Include="Microsoft.Maui.Essentials" Version="8.0.100" />
<PackageReference Include="Plugin.NFC" Version="0.1.26" />
</ItemGroup>
<ItemGroup Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">

View File

@ -1,16 +1,23 @@
using BTCPayApp.Core.Contracts;
using BTCPayApp.Core.Extensions;
using BTCPayApp.Maui.Services;
using BTCPayApp.Core.Extensions;
using BTCPayApp.UI;
using Microsoft.Extensions.Logging;
using Microsoft.Maui.LifecycleEvents;
using Plugin.Fingerprint;
using Serilog;
using BTCPayApp.Core.Contracts;
#if ANDROID
using Android.Content;
#endif
namespace BTCPayApp.Maui;
public static class MauiProgram
{
public static IServiceProvider Services { get; private set; }
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
@ -25,28 +32,50 @@ public static class MauiProgram
builder.Services.AddBTCPayAppUIServices();
builder.Services.ConfigureBTCPayAppMaui();
builder.Services.ConfigureBTCPayAppCore();
builder.Services.AddSingleton<IEmailService, EmailService>();
builder.Services.AddSingleton<INfcService, NfcService>();
var serviceProvider = builder.Services.BuildServiceProvider();
var logger = serviceProvider.GetRequiredService<ILogger<MauiApp>>();
builder.ConfigureLifecycleEvents(events =>
{
// https://learn.microsoft.com/de-de/dotnet/maui/fundamentals/app-lifecycle#platform-lifecycle-events
#if ANDROID
events.AddAndroid(android => android
.OnStart((activity) => LogEvent(nameof(AndroidLifecycle.OnStart)))
.OnCreate((activity, bundle) =>
.OnCreate((activity, _) =>
{
logger.LogDebug("Lifecycle event: {Name}", nameof(AndroidLifecycle.OnCreate));
CrossFingerprint.SetCurrentActivityResolver(() => activity);
LogEvent(nameof(AndroidLifecycle.OnCreate));
})
.OnStop((activity) => { LogEvent(nameof(AndroidLifecycle.OnStop)); }).OnDestroy(activity =>
.OnStart(_ =>
{
logger.LogDebug("Lifecycle event: {Name}", nameof(AndroidLifecycle.OnStart));
var context = Android.App.Application.Context;
var intent = new Intent(context, typeof(HubConnectionForegroundService));
context.StopService(intent); // App is in foreground — stop background service
})
.OnStop(_ =>
{
logger.LogDebug("Lifecycle event: {Name}", nameof(AndroidLifecycle.OnStop));
var context = Android.App.Application.Context;
var intent = new Intent(context, typeof(HubConnectionForegroundService));
//context.StartForegroundService(intent); // App is in background — start service
})
.OnDestroy(activity =>
{
logger.LogDebug("Lifecycle event: {Name}", nameof(AndroidLifecycle.OnDestroy));
// This event is called whenever we use File.OpenReadStream().CopyToAsync(fs)
// Immersive is being used to prevent the services from being disposed when the above method is used.
if (activity.Immersive)
{
IPlatformApplication.Current?.Services.GetRequiredService<HostedServiceInitializer>().Dispose();
}
// Stop foreground service
var context = Android.App.Application.Context;
var intent = new Intent(context, typeof(HubConnectionForegroundService));
context.StopService(intent);
}));
#endif
#if IOS
@ -54,26 +83,20 @@ public static class MauiProgram
.OnActivated((app) => LogEvent(nameof(iOSLifecycle.OnActivated)))
.OnResignActivation((app) => LogEvent(nameof(iOSLifecycle.OnResignActivation)))
.DidEnterBackground((app) => LogEvent(nameof(iOSLifecycle.DidEnterBackground)))
.WillTerminate((app) =>{
LogEvent(nameof(iOSLifecycle.WillTerminate));
.WillTerminate((app) => LogEvent(nameof(iOSLifecycle.WillTerminate));
IPlatformApplication.Current.Services.GetRequiredService<HostedServiceInitializer>().Dispose();
}
));
}
));
#endif
static bool LogEvent(string eventName, string? type = null)
{
System.Diagnostics.Debug.WriteLine(
$"Lifecycle event: {eventName}{(type == null ? string.Empty : $" ({type})")}");
return true;
}
});
#if DEBUG
builder.Services.AddBlazorWebViewDeveloperTools();
builder.Services.AddDangerousSSLSettingsForDev();
#endif
return builder.Build();
var app = builder.Build();
Services = app.Services;
return app;
}
}

View File

@ -1,14 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:supportsRtl="true"></application>
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:supportsRtl="true">
<service android:name=".HubConnectionForegroundService" android:enabled="true" android:exported="false"/>
</application>
<queries>
<intent>
<action android:name="android.intent.action.SENDTO" />
<data android:scheme="mailto" />
</intent>
</queries>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
@ -16,6 +22,8 @@
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="false" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
</manifest>
</manifest>

View File

@ -0,0 +1,61 @@
using _Microsoft.Android.Resource.Designer;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using BTCPayApp.Core.BTCPayServer;
namespace BTCPayApp.Maui;
[Service(Enabled = true, ForegroundServiceType = ForegroundService.TypeDataSync)]
public class HubConnectionForegroundService : Service
{
private BTCPayConnectionManager _connectionManager;
private const string ChannelId = "HubConnectionForegroundService";
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
CreateNotificationChannel();
StartForeground(1, BuildNotification());
_connectionManager = MauiProgram.Services.GetRequiredService<BTCPayConnectionManager>();
_connectionManager.RunningInBackground = true;
return StartCommandResult.Sticky;
}
public override IBinder OnBind(Intent intent) => null;
public override void OnDestroy()
{
_connectionManager.RunningInBackground = false;
base.OnDestroy();
}
// https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/local-notifications?view=net-maui-8.0&pivots=devices-android
private void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
#pragma warning disable CA1416
var channel = new NotificationChannel(ChannelId, "Hub Connection Service", NotificationImportance.Default)
{
Description = "Keeps the server connection alive."
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService)!;
notificationManager.CreateNotificationChannel(channel);
#pragma warning restore CA1416
}
}
private Notification BuildNotification()
{
return new Notification.Builder(this, ChannelId)
.SetContentTitle("BTCPay Server")
.SetContentText("Maintaining server connection...")
.SetSmallIcon(ResourceConstant.Drawable.ic_notification)
.SetOngoing(true)
.Build();
}
}

View File

@ -1,5 +1,8 @@
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Plugin.NFC;
namespace BTCPayApp.Maui;
@ -8,4 +11,30 @@ namespace BTCPayApp.Maui;
ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
{
protected override void OnCreate(Bundle? savedInstanceState)
{
CrossNFC.Init(this);
base.OnCreate(savedInstanceState);
#if DEBUG
// Enable WebView debugging
if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
{
Android.Webkit.WebView.SetWebContentsDebuggingEnabled(true); // Fully qualify the WebView class
}
#endif
}
protected override void OnResume()
{
base.OnResume();
CrossNFC.OnResume();
}
protected override void OnNewIntent(Intent? intent)
{
base.OnNewIntent(intent);
CrossNFC.OnNewIntent(intent);
}
}

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#FFFFFF"
android:pathData="M0,0h108v108h-108z" />
</vector>

View File

@ -0,0 +1,42 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<group>
<clip-path
android:pathData="M-12.23,20.41l95.24,-0L83,79.93L-12.23,79.93Z"/>
<path
android:pathData="m45.74,79.07a2.94,2.94 0,0 1,-2.94 -2.94l0,-44.26a2.94,2.94 0,0 1,5.88 -0L48.68,76.13A2.94,2.94 0,0 1,45.74 79.07"
android:fillColor="#cedc21"
android:strokeColor="#00000000"
android:fillType="nonZero"/>
<path
android:pathData="m45.74,79.07a2.94,2.94 0,0 1,-1.26 -5.6l17.73,-8.42 -18.22,-13.42a2.94,2.94 0,0 1,-0.62 -4.11,2.94 2.94,0 0,1 4.11,-0.62L69.66,63.24A2.94,2.94 45,0 1,69.18 68.26L47,78.79A2.93,2.93 79.23,0 1,45.74 79.07"
android:fillColor="#51b13e"
android:strokeColor="#00000000"
android:fillType="nonZero"/>
<path
android:pathData="M45.74,61.67A2.94,2.94 0,0 1,44 56.37L62.21,42.94 44.48,34.53a2.94,2.94 135,0 1,-1.4 -3.92c0.7,-1.47 2.45,-2.09 3.92,-1.4L69.18,39.74A2.94,2.94 0,0 1,69.66 44.76L47.49,61.1A2.93,2.93 135,0 1,45.74 61.67"
android:fillColor="#cedc21"
android:strokeColor="#00000000"
android:fillType="nonZero"/>
<path
android:pathData="m48.68,47.78l0,12.44l8.44,-6.22z"
android:fillColor="#1e7a44"
android:strokeColor="#00000000"
android:fillType="nonZero"/>
<path
android:pathData="m48.68,56.9l-5.88,-0l0,-14.34l5.88,-0z"
android:strokeWidth="0.36"
android:fillColor="#ffffff"
android:strokeColor="#00000000"
android:fillType="nonZero"/>
<path
android:pathData="M45.74,28.93A2.94,2.94 45,0 0,42.8 31.87L42.8,68.88L48.68,68.88L48.68,31.87A2.94,2.94 135,0 0,45.74 28.93"
android:fillColor="#cedc21"
android:strokeColor="#00000000"
android:fillType="nonZero"/>
</group>
</vector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@mipmap/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<monochrome android:drawable="@mipmap/ic_launcher_monochrome"/>
</adaptive-icon>
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

View File

@ -13,24 +13,15 @@ namespace BTCPayApp.Maui.Services
Subject = subject, //"App Log File",
Body = body, //"Attached is the log file for review.",
BodyFormat = EmailBodyFormat.PlainText,
To = new List<string> { recipient }
To = [recipient]
};
if(!string.IsNullOrWhiteSpace(attachFilePath))
if (!string.IsNullOrWhiteSpace(attachFilePath))
{
message.Attachments?.Add(new EmailAttachment(attachFilePath));
}
try
{
await Email.Default.ComposeAsync(message);
}
catch (Exception ex)
{
throw;
}
await Email.Default.ComposeAsync(message);
}
else
{

View File

@ -0,0 +1,52 @@
using BTCPayApp.Core.Contracts;
using BTCPayApp.Core.Models;
using Plugin.NFC;
public class NfcService : INfcService, IDisposable
{
public event EventHandler<NfcCardData> OnNfcDataReceived = delegate { };
public void StartNfc()
{
if (!CrossNFC.IsSupported)
{
return;
}
if (!CrossNFC.Current.IsEnabled)
{
return;
}
CrossNFC.Current.OnMessageReceived += Current_OnMessageReceived;
CrossNFC.Current.StartListening();
}
public void EndNfc()
{
CrossNFC.Current.StopListening();
Dispose();
}
private void Current_OnMessageReceived(ITagInfo tagInfo)
{
if (tagInfo == null || tagInfo.Records == null || !tagInfo.Records.Any())
{
//throw new ArgumentException("No NFC records found in the tag info.");
return;
}
var record = tagInfo.Records[0];
// Pass the raw tag info up - let the consumer decide what to do with it
OnNfcDataReceived?.Invoke(this, new NfcCardData
{
Message = record.Message,
Payload = record.Payload
});
}
public void Dispose()
{
CrossNFC.Current.OnMessageReceived -= Current_OnMessageReceived;
}
}

View File

@ -1,6 +1,4 @@
using BTCPayApp.Core.Contracts;
using BTCPayApp.Core.Data;
using BTCPayApp.Core.Helpers;
using BTCPayApp.Maui.Services;
using Plugin.Fingerprint;
@ -16,6 +14,7 @@ public static class StartupExtensions
serviceCollection.AddSingleton(CrossFingerprint.Current);
serviceCollection.AddSingleton<HostedServiceInitializer>();
serviceCollection.AddSingleton<IMauiInitializeService, HostedServiceInitializer>();
serviceCollection.AddScoped<IEmailService, EmailService>();
return serviceCollection;
}

View File

@ -12,6 +12,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Photino.Blazor;
using Photino.NET;
using Size = System.Drawing.Size;
namespace BTCPayApp.Photino;

View File

@ -1,5 +1,7 @@
using BTCPayApp.Core.Contracts;
using BTCPayApp.Core.Extensions;
using BTCPayApp.Desktop;
using BTCPayApp.Server.Services;
using BTCPayApp.UI;
using Serilog;
@ -17,6 +19,8 @@ builder.Services.ConfigureBTCPayAppCore();
builder.Services.AddDangerousSSLSettingsForDev();
#endif
builder.Services.AddSingleton<INfcService, NfcService>();
// Configure the HTTP request pipeline.
var app = builder.Build();
if (!app.Environment.IsDevelopment())

View File

@ -0,0 +1,23 @@
using BTCPayApp.Core.Contracts;
using BTCPayApp.Core.Models;
namespace BTCPayApp.Server.Services
{
public class NfcService : INfcService
{
public event EventHandler<NfcCardData> OnNfcDataReceived = delegate { };
public void Dispose()
{
}
public void EndNfc()
{
}
public void StartNfc()
{
// NFC for web is supported within the btcpayserver iframe, so we dont need to implement NFC support here.
}
}
}

View File

@ -2,14 +2,11 @@
@using BTCPayApp.UI.Features
@using BTCPayApp.UI.Pages
@using BTCPayApp.Core.Contracts
@using BTCPayApp.Core.Services
@using BTCPayApp.UI.Pages.SignedOut
@using Serilog.Events
@inherits Fluxor.Blazor.Web.Components.FluxorComponent
@inject IDispatcher Dispatcher
@inject IAccountManager AccountManager
@inject ConfigProvider ConfigProvider
@inject LoggingService LoggingService
<PageTitle>BTCPay Server</PageTitle>
<Fluxor.Blazor.Web.StoreInitializer />

File diff suppressed because one or more lines are too long

View File

@ -5,16 +5,18 @@
<div class="accordion-item">
<div id="channel-@Channel.Id" class="d-flex flex-column gap-2 accordion-header">
<div class="d-flex align-items-center justify-content-between gap-2">
<TruncateCenter Text="@Channel.Id" Padding="10" class="fw-semibold me-auto"/>
@if (!string.IsNullOrEmpty(Channel.CounterpartyLabel))
{
<span class="me-auto">@Channel.CounterpartyLabel</span>
}
<div class="me-auto">
<TruncateCenter Text="@Channel.Id" Padding="10" class="fw-semibold me-auto"/>
@if (!string.IsNullOrEmpty(Channel.CounterpartyLabel))
{
<div class="text-muted">@Channel.CounterpartyLabel</div>
}
</div>
@if (Loading)
{
<LoadingIndicator/>
}
<span class="btcpay-status btcpay-status--@(Channel.Active ? "enabled" : "pending")"></span>
<span class="btcpay-status btcpay-status--@ChannelState"></span>
<button class="accordion-button collapsed w-auto p-0" type="button" data-bs-toggle="collapse" data-bs-target="#peer-@Channel.Id-details" aria-expanded="false" aria-controls="peer-@Channel.Id-details">
<Icon Symbol="caret-down"/>
</button>
@ -24,17 +26,26 @@
var inbound = (long)Channel.CapacityInbound.ToUnit(LightMoneyUnit.Satoshi);
var outbound = (long)Channel.CapacityOutbound.ToUnit(LightMoneyUnit.Satoshi);
var ourPerc = (int)(outbound * 100 / (inbound + outbound));
<div class="d-flex align-items-center justify-content-between gap-2">
<AmountDisplay Sats="@outbound" Currency="@CurrencyDisplay.SATS" />
<AmountDisplay Sats="@inbound" Currency="@CurrencyDisplay.SATS" />
</div>
<div class="progress w-100" role="progressbar" aria-label="Channel Capacity" aria-valuenow="@ourPerc" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar bg-success" style="width:@(ourPerc)%"></div>
<div>
<div class="progress w-100 mb-1" role="progressbar" aria-label="Channel Capacity" aria-valuenow="@ourPerc" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar progress-bar-@(ChannelState)" style="width:@(ourPerc)%"></div>
</div>
<div class="d-flex align-items-center justify-content-between gap-2">
<AmountDisplay Sats="@outbound" Currency="@CurrencyDisplay.SATS" />
<AmountDisplay Sats="@inbound" Currency="@CurrencyDisplay.SATS" />
</div>
</div>
}
</div>
<div id="peer-@Channel.Id-details" class="accordion-collapse collapse" aria-labelledby="peer-@Channel.Id">
<div class="pt-2">
<div class="pt-3">
@if (!string.IsNullOrEmpty(Channel.CounterpartyLabel))
{
<div class="form-floating">
<TruncateCenter Text="@Channel.CounterpartyLabel" Padding="20" Elastic="true" class="form-control-plaintext"/>
<label>Counterparty</label>
</div>
}
@if (!string.IsNullOrEmpty(Channel.CounterpartyNodeId))
{
<div class="form-floating">
@ -49,32 +60,46 @@
<label>Funding Transaction</label>
</div>
}
<dl>
<div>
<dt>State:</dt>
<dd>@Channel.State</dd>
</div>
<div>
<dt>Connected:</dt>
<dd>@Channel.Connected</dd>
</div>
<div>
<dt>Usable:</dt>
<dd>@Channel.Usable</dd>
</div>
<div>
<dt>Ready:</dt>
<dd>@Channel.Ready</dd>
</div>
<div>
<dt>Announced:</dt>
<dd>@Channel.Announced</dd>
<dl class="mt-2 mb-0">
<div class="align-items-center">
<dt>@(Channel.Connected ? "Connected" : "Not connected")</dt>
<span class="btcpay-status btcpay-status--@(Channel.Connected ? "enabled" : "disabled")"></span>
</div>
@if (Channel is { Connected: true, Ready: not null })
{
<div class="align-items-center">
<dt class="text-wrap">@(Channel.Ready.Value ? "Ready" : $"Not ready: {Channel.Confirmations} of {Channel.ConfirmationsRequired} confirmations")</dt>
<span class="btcpay-status btcpay-status--@(Channel.Ready.Value ? "enabled" : "pending")"></span>
</div>
@if (Channel is { Connected: true, Ready: true, Usable: not null })
{
<div class="align-items-center">
<dt>@(Channel.Usable.Value ? "Usable" : "Not usable")</dt>
<span class="btcpay-status btcpay-status--@(Channel.Usable.Value ? "enabled" : "pending")"></span>
</div>
}
}
@if (!string.IsNullOrEmpty(Channel.State) || Channel.Announced.HasValue)
{
<div class="align-items-center">
<dt>State:</dt>
<dd class="d-inline-flex flex-wrap gap-1">
@if (!string.IsNullOrEmpty(Channel.State))
{
<span>@Channel.State</span>
}
@if (Channel.Announced.HasValue)
{
<span>(@(Channel.Announced.Value ? "Announced" : "Unannounced"))</span>
}
</dd>
</div>
}
</dl>
@if (Channel.Active && OnCloseChannel.HasDelegate)
{
<div class="d-grid d-sm-flex flex-wrap gap-3 buttons mt-3">
<button type="button" class="btn btn-outline-danger btn-sm" @onclick="CloseChannel">Close</button>
<button type="button" class="btn btn-outline-danger btn-sm" @onclick="CloseChannel">@(Channel.Connected ? "Close" : "Force-close (not connected)")</button>
</div>
}
</div>
@ -91,6 +116,10 @@
[Parameter]
public bool Loading { get; set; }
private string ChannelState => Channel.Active
? Channel.Ready is true ? "enabled" : "pending"
: Channel.Connected ? "pending" : "disabled";
private async Task CloseChannel()
{
if (OnCloseChannel.HasDelegate)

View File

@ -0,0 +1,12 @@
.progress {
background-color: var(--btcpay-neutral-400);
}
.progress-bar-enabled {
background-color: var(--btcpay-success);
}
.progress-bar-pending,
.progress-bar-disabled {
background-color: var(--btcpay-neutral-500);
}

View File

@ -0,0 +1,5 @@
::deep .form-control[readonly] {
background-color: var(--btcpay-form-bg-addon);
border-color: var(--btcpay-form-bg-addon);
pointer-events: none;
}

View File

@ -1,4 +1,8 @@
@using BTCPayApp.Core.Auth
@using BTCPayApp.UI.Features
@using BTCPayServer.Client.Models
@inject IAccountManager AccountManager
@inject IDispatcher Dispatcher
<div @attributes="InputAttributes" class="@CssClass">
@if (Invoices is not null)
{
@ -44,4 +48,21 @@
public Dictionary<string, object>? InputAttributes { get; set; }
private string CssClass => $"invoice-list {(InputAttributes?.ContainsKey("class") is true ? InputAttributes["class"] : "")}".Trim();
private string? StoreId => AccountManager.CurrentStore?.Id;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
if (!string.IsNullOrEmpty(StoreId))
{
Dispatcher.Dispatch(new StoreState.FetchInvoices(StoreId));
}
}
}
private async void OnStateChanged(object? sender, EventArgs e)
{
await InvokeAsync(StateHasChanged);
}
}

View File

@ -2,6 +2,7 @@
@using System.Globalization
@using System.Text.Json
@using System.Text.Json.Nodes
@using BTCPayApp.Core.Models
@using BTCPayServer.Client
@using BTCPayServer.Client.Models
@inject IJSRuntime JS
@ -97,18 +98,21 @@
</button>
}
</div>
<button class="btn btn-lg btn-primary mx-3" type="submit" disabled="@(IsSubmitting || amount == 0)" id="pay-button" @onclick="HandleSubmit">
@if (IsSubmitting)
{
<div class="spinner-border spinner-border-sm" role="status">
<span class="visually-hidden">Loading...</span>
</div>
}
else
{
<span>Charge</span>
}
</button>
<div class="d-flex justify-content-center">
<button class="btn btn-lg btn-primary mx-3" type="submit" disabled="@(IsSubmitting || amount == 0)" id="pay-button" @onclick="HandleSubmit">
@if (IsSubmitting)
{
<div class="spinner-border spinner-border-sm" role="status">
<span class="visually-hidden">Loading...</span>
</div>
}
else
{
<span>Charge</span>
}
</button>
</div>
@if (CanAccessRecentTransactions)
{
@ -248,7 +252,7 @@
</div>
@code {
#nullable enable
#nullable enable
[Parameter, EditorRequired]
public string StoreId { get; set; } = null!;
[Parameter, EditorRequired]
@ -274,7 +278,7 @@
[Parameter]
public EventCallback LoadRecentTransactions { get; set; }
[Parameter]
public EventCallback<CreatePosInvoiceRequest> CreateInvoice { get; set; }
public EventCallback<Core.Models.CreatePosInvoiceRequest> CreateInvoice { get; set; }
[Parameter]
public IEnumerable<RecentTransaction>? RecentTransactions { get; set; }
[Parameter]
@ -436,8 +440,6 @@
{
var data = new JsonObject
{
["subTotal"] = GetAmount(),
["total"] = GetTotal(),
["cart"] = JsonValue.Create(Model.Cart)
};
@ -667,16 +669,12 @@
StateHasChanged();
if (CreateInvoice.HasDelegate)
{
var req = new CreatePosInvoiceRequest
var req = new Core.Models.CreatePosInvoiceRequest
{
Cart = Model.Cart,
DiscountPercent = Model.DiscountPercent,
TipPercent = Model.TipPercent,
Tip = GetTip(),
Amounts = GetAmounts(),
DiscountAmount = GetDiscount(),
Subtotal = GetAmount(),
Total = GetTotal(),
PosData = GetData()
};
await CreateInvoice.InvokeAsync(req);

View File

@ -1,47 +1,47 @@
@using BTCPayApp.Core.BTCPayServer
@using BTCPayApp.Core.Wallet
@if (State is LightningNodeState.Error)
@if (NodeState == LightningNodeState.Error)
{
<div class="alert alert-danger" role="alert">
<h4 class="alert-heading">Lightning Node failure</h4>
<p class="mb-0">There was an error with the lightning node. Please try again later.</p>
<h4 class="alert-heading">Lightning Node @(Status)</h4>
<p class="mb-0">
There was an error with the lightning node. Please
<NavLink href="@Routes.AppLogs">check the app logs</NavLink>
and try again later.
</p>
</div>
}
else if (State is LightningNodeState.Stopped)
{
<div class="alert alert-warning" role="alert">
<h4 class="alert-heading">Lightning Node stopped</h4>
<p class="mb-0">This instance of the lightning node is not running currently.</p>
</div>
}
else if (State is LightningNodeState.Inactive)
else
{
<div class="alert alert-info" role="alert">
<h4 class="alert-heading">Lightning Node inactive</h4>
<p class="mb-0">There seems to be another instance of this lightning node running. This instance is inactive.</p>
</div>
}
else if (State is not LightningNodeState.Loaded)
{
<div class="alert alert-info" role="alert">
<h4 class="alert-heading">Lightning Node loading</h4>
<p class="mb-0">The lightning node is currently @Status.</p>
<h4 class="alert-heading">Lightning Node @(Status)</h4>
<p class="mb-0">
@if (ConnectionState == BTCPayConnectionState.ConnectedAsSecondary)
{
<span>This device is currently connected as an additional device for communication with the BTCPay Server.</span>
}
<span>The lightning node is currently @(Status).</span>
</p>
</div>
}
@code {
[Parameter, EditorRequired]
public LightningNodeState? State { get; set; }
public LightningNodeState? NodeState { get; set; }
[Parameter, EditorRequired]
public BTCPayConnectionState? ConnectionState { get; set; }
private string Status =>
State switch
NodeState switch
{
LightningNodeState.Init => "initializing",
LightningNodeState.NotConfigured => "not configured",
LightningNodeState.WaitingForConnection => "waiting for connection",
LightningNodeState.WaitingForConnection => ConnectionState == BTCPayConnectionState.ConnectedAsSecondary ? "inactive" : "waiting for connection",
LightningNodeState.Loaded => "loaded",
LightningNodeState.Stopped => "stopped",
LightningNodeState.Error => "in failure mode",
LightningNodeState.Inactive => "inactive",
_ => "loading"
_ => ConnectionState == BTCPayConnectionState.Syncing ? "syncing" : "loading"
};
}

View File

@ -16,6 +16,13 @@
</div>
<div id="peer-@Peer.NodeId-details" class="accordion-collapse collapse" aria-labelledby="peer-@Peer.NodeId">
<div class="pt-2">
@if (OnUpdatePeer.HasDelegate)
{
<div class="form-group mb-2">
<label for="Label" class="form-label">Label</label>
<InputText @bind-Value="Label" @bind-Value:after="UpdatePeerLabel" id="Label" class="form-control"/>
</div>
}
<div class="form-floating">
<TruncateCenter Text="@Peer.NodeId" Padding="10" Copy="true" Elastic="true" class="form-control-plaintext"/>
<label>Node ID</label>
@ -69,6 +76,16 @@
[Parameter]
public bool Loading { get; set; }
private string Label
{
get => Peer.Info?.Label ?? string.Empty;
set
{
Peer.Info ??= new PeerInfo();
Peer.Info.Label = value;
}
}
private async Task ConnectPeer()
{
if (OnConnectPeer.HasDelegate)
@ -89,4 +106,13 @@
await OnUpdatePeer.InvokeAsync(Peer);
}
}
private async Task UpdatePeerLabel()
{
if (OnUpdatePeer.HasDelegate)
{
Peer.Info = (Peer.Info ?? new PeerInfo()) with { Label = Label };
await OnUpdatePeer.InvokeAsync(Peer);
}
}
}

View File

@ -74,7 +74,7 @@
clss += $" badge-{(status == "unconfirmed" ? "pending" : "settled")}";
break;
case TransactionPaymentMethod.Lightning:
clss += $" badge-{status}";
clss += $" badge-{(status == "failed" ? "invalid" : status)}";
break;
}
return clss;

View File

@ -67,8 +67,8 @@
private void EditContextOnOnFieldChanged(object? sender, FieldChangedEventArgs e)
{
if (!EditContext?.GetValidationMessages(e.FieldIdentifier).Any() is true) return;
MessageStore?.Clear(e.FieldIdentifier);
if (EditContext?.GetValidationMessages(e.FieldIdentifier).Any() is false)
MessageStore?.Clear(e.FieldIdentifier);
EditContext?.NotifyValidationStateChanged();
}
@ -77,6 +77,11 @@
EditContext?.NotifyFieldChanged(FieldIdentifier.Create(field));
}
public void NotifyValidationStateChanged()
{
EditContext?.NotifyValidationStateChanged();
}
private void EditContextOnOnValidationStateChanged(object? sender, ValidationStateChangedEventArgs e)
{
StateHasChanged();

View File

@ -2,7 +2,6 @@
@using BTCPayServer.Client.Models
@implements IDisposable
@inject IJSRuntime JS
@inject DisplayFormatter DisplayFormatter
<div @attributes="InputAttributes" class="@CssClass">
@if (Sats != null)

View File

@ -0,0 +1,46 @@
@using BTCPayApp.Core.BTCPayServer
@using BTCPayApp.Core.Wallet
@if (WalletState == OnChainWalletState.Error)
{
<div class="alert alert-danger" role="alert">
<h4 class="alert-heading">Onchain Wallet @(Status)</h4>
<p class="mb-0">
There was an error with the onchain wallet. Please
<NavLink href="@Routes.AppLogs">check the app logs</NavLink>
and try again later.
</p>
</div>
}
else
{
<div class="alert alert-info" role="alert">
<h4 class="alert-heading">Onchain Wallet @(Status)</h4>
<p class="mb-0">
@if (ConnectionState == BTCPayConnectionState.ConnectedAsSecondary)
{
<span>This device is currently connected as an additional device for communication with the BTCPay Server.</span>
}
<span>The onchain wallet is currently @(Status).</span>
</p>
</div>
}
@code {
[Parameter, EditorRequired]
public OnChainWalletState? WalletState { get; set; }
[Parameter, EditorRequired]
public BTCPayConnectionState? ConnectionState { get; set; }
private string Status =>
WalletState switch
{
OnChainWalletState.Init => "initializing",
OnChainWalletState.NotConfigured => "not configured",
OnChainWalletState.WaitingForConnection => ConnectionState == BTCPayConnectionState.ConnectedAsSecondary ? "inactive" : "waiting for connection",
OnChainWalletState.Loaded => "loaded",
OnChainWalletState.Error => "in failure mode",
_ => ConnectionState == BTCPayConnectionState.Syncing ? "syncing" : "loading"
};
}

View File

@ -10,12 +10,10 @@ public class LoginModel
[Required]
public string? Uri { get; set; }
[Required]
[EmailAddress]
[Required, EmailAddress]
public string? Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Required, DataType(DataType.Password)]
public string? Password { get; set; }
[RequiredIf(nameof(RequireTwoFactor), true)]

View File

@ -1,25 +1,87 @@
@attribute [Route(Routes.Checkout)]
@using BTCPayApp.Core
@using BTCPayApp.Core.Auth
@using BTCPayApp.Core.BTCPayServer
@using BTCPayApp.Core.Contracts
@using BTCPayApp.Core.Models
@inject IJSRuntime JS
@inject IAccountManager AccountManager
@inject INfcService NfcService
@inject NavigationManager NavigationManager
@inherits Fluxor.Blazor.Web.Components.FluxorComponent
<PageTitle>Checkout</PageTitle>
<iframe id="AppCheckout" name="checkout" allowfullscreen src="@CheckoutUrl" @onload="OnIframeLoad"></iframe>
@if (!_iframeLoaded)
{
<section class="loading-container">
<LoadingIndicator Size="lg"/>
<LoadingIndicator Size="lg" />
<div class="fs-4">Loading</div>
</section>
}
<iframe id="AppCheckout" name="checkout" allow="clipboard-read;clipboard-write" allowfullscreen src="@CheckoutUrl" @onload="OnIframeLoad"></iframe>
@if (_toast.IsVisible)
{
<div class="toast-container @(_toast.IsError ? "toast-error" : "toast-success")">
<div class="toast-message">@_toast.Message</div>
</div>
}
<style>
.toast-container {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
z-index: 9999;
padding: 12px 24px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
max-width: 90%;
min-width: 200px;
text-align: center;
animation: slideUp 0.3s ease-out;
}
.toast-success {
background-color: #28a745;
color: white;
border: 1px solid #1e7e34;
}
.toast-error {
background-color: #dc3545;
color: white;
border: 1px solid #c82333;
}
.toast-message {
font-size: 14px;
font-weight: 500;
line-height: 1.4;
}
@@keyframes slideUp {
from {
opacity: 0;
transform: translateX(-50%) translateY(20px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
</style>
@code {
[Parameter, EditorRequired]
public string? InvoiceId { get; set; }
[Parameter, EditorRequired] public string? InvoiceId { get; set; }
private bool _iframeLoaded;
private bool _scanInProgress;
private Toast _toast = new();
private string BaseUri => AccountManager.Account!.BaseUri;
private string? CheckoutUrl => string.IsNullOrEmpty(InvoiceId) ? null : $"{BaseUri}i/{InvoiceId}";
@ -28,5 +90,126 @@
{
_iframeLoaded = true;
await JS.InvokeVoidAsync("Interop.setContext", "#AppCheckout", BaseUri);
NfcService.OnNfcDataReceived += OnNfcDataReceived;
NfcService.StartNfc();
_toast.OnUpdated = StateHasChanged;
}
private async void OnNfcDataReceived(object? sender, NfcCardData record)
{
if (_scanInProgress)
return;
_scanInProgress = true;
try
{
if (record == null || record.Message == null)
{
_toast.ShowError("No NFC data found");
return;
}
var message = record.Message;
if (string.IsNullOrEmpty(message))
{
_toast.ShowError("Empty NFC message");
return;
}
var btcPayClient = new BTCPayAppClient(BaseUri);
var req = new SubmitLnUrlRequest
{
InvoiceId = InvoiceId,
Lnurl = message
};
_toast.ShowSuccess("Submitting NFC data to Server", 5000);
var result = await btcPayClient.SubmitLNURLWithdrawForInvoice(req);
if (result == null)
{
_toast.Hide();
NfcService.EndNfc();
NfcService.OnNfcDataReceived -= OnNfcDataReceived;
}
}
catch (Exception ex)
{
try
{
var errorFromServer = ex.Message.Split("\"")[1].Trim('"');
_toast.ShowError("ERROR: " + errorFromServer);
}
catch
{
_toast.ShowError("NFC call to server ERROR");
}
}
finally
{
_scanInProgress = false;
}
}
public void Dispose()
{
NfcService.OnNfcDataReceived -= OnNfcDataReceived;
}
public class Toast
{
private CancellationTokenSource? _cts;
public bool IsVisible { get; private set; }
public bool IsError { get; private set; }
public string Message { get; private set; } = string.Empty;
public Action? OnUpdated { get; set; }
public void ShowSuccess(string message, int delayTime = 3000)
{
Show(message, false);
}
public void ShowError(string message, int delayTime = 3000)
{
Show(message, true);
}
private void Show(string message, bool isError, int delayTime = 3000)
{
_cts?.Cancel();
_cts = new CancellationTokenSource();
Message = message;
IsError = isError;
IsVisible = true;
OnUpdated?.Invoke();
var token = _cts.Token;
_ = HideAfterDelayAsync(token);
}
private async Task HideAfterDelayAsync(CancellationToken token, int delayTime = 3000)
{
try
{
await Task.Delay(delayTime, token);
if (!token.IsCancellationRequested)
{
IsVisible = false;
OnUpdated?.Invoke();
}
}
catch (TaskCanceledException) { }
}
public void Hide()
{
_cts?.Cancel();
IsVisible = false;
OnUpdated?.Invoke();
}
}
}

View File

@ -1,15 +1,28 @@
.container {
max-width: 560px;
padding-top: var(--btcpay-space-l);
padding-bottom: var(--btcpay-space-l);
max-width: 560px;
padding-top: var(--btcpay-space-l);
padding-bottom: var(--btcpay-space-l);
}
iframe {
position: fixed;
z-index: 1;
top: 0;
left: 0;
width: 100%;
height: 100%; /* fallback for older webviews */
height: calc(100% - var(--navbar-bottom-height));
position: fixed;
z-index: 1;
top: 0;
left: 0;
width: 100%;
height: 100%; /* fallback for older webviews */
height: calc(100% - var(--navbar-bottom-height));
}
.section-complete ::deep .checkout-complete {
width: 110px; /* Increase size */
height: 100px;
fill: var(--btcpay-primary) !important; /* Change fill color */
stroke: var(--btcpay-primary) !important; /* Change stroke color */
/*fill: var(--btcpay-primary);*/
}
.section-complete {
height: 80vh;
}

View File

@ -104,8 +104,9 @@
_errorMessage = null;
_data = await AccountManager.GetClient().GetCreateStore();
Model.Name = _data?.Name;
Model.DefaultCurrency = _data?.DefaultCurrency;
Model.PreferredExchange = _data?.RecommendedExchangeId;
Model.PreferredExchange = _data?.PreferredExchangeId;
}
catch (Exception e)
{
@ -143,11 +144,12 @@
var rateConfig = new StoreRateConfiguration { PreferredSource = Model.PreferredExchange };
await AccountManager.GetClient().UpdateStoreRateConfiguration(store.Id, rateConfig);
// refresh store info and set id of new store
// refresh store info and set id of the new store
await AccountManager.CheckAuthenticated(true);
var result = await AccountManager.SetCurrentStoreId(store.Id);
if (!result.Succeeded)
{
_sending = false;
_errorMessage = result.Messages != null
? string.Join(",", result.Messages)
: "Store creation failed.";
@ -157,11 +159,9 @@
catch (Exception e)
{
_errorMessage = e.Message;
}
finally
{
_sending = false;
}
// on success, keep _sending = true to show the loading indicator until the redirect occurs
}
private class CreateStoreModel

View File

@ -22,7 +22,7 @@
<section class="container py-4">
@if (!string.IsNullOrEmpty(_successMessage))
{
<Alert Type="success" Margin="0" Dismissible>@_successMessage</Alert>
<Alert Type="success" Margin="0" Dismissible class="mb-4">@_successMessage</Alert>
}
@if (string.IsNullOrEmpty(StoreId))
{
@ -36,7 +36,7 @@
</div>
<WalletOverview Sats="@TotalBalance" Histogram="@Histogram" Currency="@DisplayCurrency" Rate="@Rate"
Error="@BalanceError" Loading="@BalanceLoading" OnBalanceClick="ToggleDisplayCurrency"
class="my-3"/>
class="mt-4 mb-3"/>
<div class="btn-group w-100 justify-content-center" role="group" aria-label="Period">
<InputRadioGroup Name="HistogramPeriod" @bind-Value="@HistogramPeriod">
<InputRadio Name="HistogramPeriod" Value="HistogramType.Day" class="btn-check" id="BalancePeriodDay"/>
@ -53,7 +53,7 @@
<label class="btn btn-link" for="BalancePeriodTwoYears">2Y</label>
</InputRadioGroup>
</div>
@if (TotalBalance is > 0)
@if (true || TotalBalance is > 0)
{
<div class="text-center my-5">
<NavLink href="@Routes.Withdraw" class="d-inline-flex align-items-center gap-1 fs-5 bg-light rounded-pill px-5 py-2 fw-semibold">
@ -79,7 +79,7 @@
{
<AppSalesStats AppId="@PosAppId" Stats="PosSalesStats" Loading="PosSalesStatsLoading" Error="@PosSalesStatsError" class="mt-5"/>
}
@if (PosItemStatsLoading || PosItemStats is not null)
@if (ShowPosItemStats)
{
<AppItemStats AppId="@PosAppId" Stats="PosItemStats" Loading="PosItemStatsLoading" Error="@PosItemStatsError" class="mt-5"/>
}
@ -143,4 +143,5 @@
private List<AppItemStats>? PosItemStats => StoreState.Value.PosItemStats?.Data;
private string? PosSalesStatsError => StoreState.Value.PosSalesStats?.Error;
private string? PosItemStatsError => StoreState.Value.PosItemStats?.Error;
private bool ShowPosItemStats => PosItemStats is not null && PosItemStats is not [{ Title: "Keypad" }];
}

View File

@ -36,6 +36,10 @@
{
<Alert Type="danger">@Error</Alert>
}
@if (!string.IsNullOrEmpty(_successMessage))
{
<Alert Type="success">@_successMessage</Alert>
}
@if (Invoice is not null)
{
@if (CanCheckout)
@ -56,45 +60,64 @@
<InvoiceStatusDisplay Invoice="@Invoice"/>
</div>
<div class="invoice-actions mt-3 mb-3">
<div class="row g-2">
@if (!string.IsNullOrEmpty(ReceiptUrl))
{
<div class="col-4">
<a class="btn btn-outline-secondary btn-sm w-100" href="@ReceiptUrl" rel="noreferrer noopener" target="_blank">Receipt</a>
</div>
}
@if (!Invoice.Archived)
{
<div class="col-4">
<button class="btn btn-outline-secondary btn-sm w-100" @onclick="ToggleArchive">
Archive
</button>
</div>
}
</div>
</div>
<h4 class="mt-4">General Information</h4>
<div class="box">
<table class="table my-0">
<tbody>
@if (Invoice.Metadata.TryGetValue("orderId", out var orderId))
{
@if (Invoice.Metadata.TryGetValue("orderId", out var orderId))
{
<tr>
<th>Order Id</th>
<td>
@if (Invoice.Metadata.TryGetValue("orderUrl", out var orderUrl))
{
<a href="@orderUrl" rel="noreferrer noopener" target="_blank">@orderId</a>
}
else
{
<span>@orderId</span>
}
</td>
</tr>
}
@if (Invoice.Metadata.TryGetValue("paymentRequestId", out var paymentRequestId))
{
<tr>
<th>Payment Request Id</th>
<td>@paymentRequestId</td>
</tr>
}
<tr>
<th>Order Id</th>
<th>Created</th>
<td>
@if (Invoice.Metadata.TryGetValue("orderUrl", out var orderUrl))
{
<a href="@orderUrl" rel="noreferrer noopener" target="_blank">@orderId</a>
}
else
{
<span>@orderId</span>
}
<DateDisplay DateTimeOffset="@Invoice.CreatedTime"/>
</td>
</tr>
}
@if (Invoice.Metadata.TryGetValue("paymentRequestId", out var paymentRequestId))
{
<tr>
<th>Payment Request Id</th>
<td>@paymentRequestId</td>
<th>Expired</th>
<td>
<DateDisplay DateTimeOffset="@Invoice.ExpirationTime"/>
</td>
</tr>
}
<tr>
<th>Created</th>
<td>
<DateDisplay DateTimeOffset="@Invoice.CreatedTime"/>
</td>
</tr>
<tr>
<th>Expired</th>
<td>
<DateDisplay DateTimeOffset="@Invoice.ExpirationTime"/>
</td>
</tr>
</tbody>
</table>
</div>
@ -111,27 +134,27 @@
<div class="box">
<table class="table my-0">
<tbody>
@if (!string.IsNullOrEmpty(itemCode?.ToString()))
{
<tr>
<th>Item code</th>
<td>@itemCode</td>
</tr>
}
@if (!string.IsNullOrEmpty(itemDesc?.ToString()))
{
<tr>
<th>Item Description</th>
<td>@itemDesc</td>
</tr>
}
@if (taxIncluded is not null)
{
<tr>
<th>Tax Included</th>
<td>@taxIncluded</td>
</tr>
}
@if (!string.IsNullOrEmpty(itemCode?.ToString()))
{
<tr>
<th>Item code</th>
<td>@itemCode</td>
</tr>
}
@if (!string.IsNullOrEmpty(itemDesc?.ToString()))
{
<tr>
<th>Item Description</th>
<td>@itemDesc</td>
</tr>
}
@if (taxIncluded is not null)
{
<tr>
<th>Tax Included</th>
<td>@taxIncluded</td>
</tr>
}
</tbody>
</table>
</div>
@ -150,80 +173,80 @@
Invoice.Metadata.TryGetValue("buyerZip", out var buyerZip);
}
@if (!string.IsNullOrEmpty(buyerName?.ToString()) || !string.IsNullOrEmpty(buyerEmail?.ToString()) ||
!string.IsNullOrEmpty(buyerPhone?.ToString()) || !string.IsNullOrEmpty(buyerAddress1?.ToString()) ||
!string.IsNullOrEmpty(buyerAddress2?.ToString()) || !string.IsNullOrEmpty(buyerCity?.ToString()) ||
!string.IsNullOrEmpty(buyerState?.ToString()) || !string.IsNullOrEmpty(buyerCountry?.ToString()) ||
!string.IsNullOrEmpty(buyerZip?.ToString()))
!string.IsNullOrEmpty(buyerPhone?.ToString()) || !string.IsNullOrEmpty(buyerAddress1?.ToString()) ||
!string.IsNullOrEmpty(buyerAddress2?.ToString()) || !string.IsNullOrEmpty(buyerCity?.ToString()) ||
!string.IsNullOrEmpty(buyerState?.ToString()) || !string.IsNullOrEmpty(buyerCountry?.ToString()) ||
!string.IsNullOrEmpty(buyerZip?.ToString()))
{
<h4 class="mt-4">Buyer Information</h4>
<div class="box">
<table class="table my-0">
<tbody>
@if (!string.IsNullOrEmpty(buyerName?.ToString()))
{
<tr>
<th>Name</th>
<td>@buyerName</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerEmail?.ToString()))
{
<tr>
<th>Email</th>
<td>
<a href="mailto:@buyerEmail">@buyerEmail</a>
</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerPhone?.ToString()))
{
<tr>
<th>Phone</th>
<td>@buyerPhone</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerAddress1?.ToString()))
{
<tr>
<th>Address 1</th>
<td>@buyerAddress1</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerAddress2?.ToString()))
{
<tr>
<th>Address 2</th>
<td>@buyerAddress2</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerCity?.ToString()))
{
<tr>
<th>City</th>
<td>@buyerCity</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerState?.ToString()))
{
<tr>
<th>State</th>
<td>@buyerState</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerCountry?.ToString()))
{
<tr>
<th>Country</th>
<td>@buyerCountry</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerZip?.ToString()))
{
<tr>
<th>Zip</th>
<td>@buyerZip</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerName?.ToString()))
{
<tr>
<th>Name</th>
<td>@buyerName</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerEmail?.ToString()))
{
<tr>
<th>Email</th>
<td>
<a href="mailto:@buyerEmail">@buyerEmail</a>
</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerPhone?.ToString()))
{
<tr>
<th>Phone</th>
<td>@buyerPhone</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerAddress1?.ToString()))
{
<tr>
<th>Address 1</th>
<td>@buyerAddress1</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerAddress2?.ToString()))
{
<tr>
<th>Address 2</th>
<td>@buyerAddress2</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerCity?.ToString()))
{
<tr>
<th>City</th>
<td>@buyerCity</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerState?.ToString()))
{
<tr>
<th>State</th>
<td>@buyerState</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerCountry?.ToString()))
{
<tr>
<th>Country</th>
<td>@buyerCountry</td>
</tr>
}
@if (!string.IsNullOrEmpty(buyerZip?.ToString()))
{
<tr>
<th>Zip</th>
<td>@buyerZip</td>
</tr>
}
</tbody>
</table>
</div>
@ -327,13 +350,13 @@
if (!string.IsNullOrEmpty(StoreId) && !string.IsNullOrEmpty(InvoiceId))
{
if (Invoice == null)
Dispatcher.Dispatch(new StoreState.FetchInvoice(StoreId, InvoiceId));
Dispatcher.Dispatch(new StoreState.FetchInvoice(StoreId, InvoiceId));
if (PaymentMethods == null)
Dispatcher.Dispatch(new StoreState.FetchInvoicePaymentMethods(StoreId, InvoiceId));
}
}
private string? _successMessage;
private string? StoreId => AccountManager.CurrentStore?.Id;
private AppUserStoreInfo? StoreInfo => StoreState.Value.StoreInfo;
private InvoiceData? Invoice => !string.IsNullOrEmpty(InvoiceId) ? StoreState.Value.GetInvoice(InvoiceId!)?.Data : null;
@ -353,4 +376,14 @@
private string GetTitle() => $"Invoice {Invoice?.Id}".Trim();
private bool CanCheckout => Invoice is { Status: InvoiceStatus.New };
private async Task ToggleArchive()
{
await AccountManager.GetClient().ArchiveInvoice(StoreId, InvoiceId);
_successMessage = "The invoice has been archived and will no longer appear in the invoice list by default";
if (!string.IsNullOrEmpty(StoreId) && !string.IsNullOrEmpty(InvoiceId))
{
Dispatcher.Dispatch(new StoreState.FetchInvoice(StoreId, InvoiceId));
}
}
}

View File

@ -1,4 +1,5 @@
@attribute [Route(Routes.ChannelsPeers)]
@using System.Text.RegularExpressions
@using BTCPayApp.Core.Auth
@using BTCPayApp.Core.Data
@using BTCPayApp.UI.Components.Layout
@ -11,7 +12,6 @@
@using BTCPayServer.Lightning
@using LNURL
@using NBitcoin
@using Newtonsoft.Json
@using org.ldk.enums
@using org.ldk.structs
@using NodeInfo = BTCPayServer.Lightning.NodeInfo
@ -45,62 +45,76 @@
<h2>Peers</h2>
<PeersList Peers="_peers" OnConnectPeer="ConnectPeer" OnDisconnectPeer="DisconnectPeer" OnUpdatePeer="UpdatePeer" UpdatingPeerId="@_updatingPeer" class="mb-4"/>
@if (PeerModel != null)
{
<h2>Connect Peer</h2>
<ValidationEditContext @ref="_connectEditContext" Model="PeerModel" OnValidSubmit="ConnectToNewPeer" SuccessMessage="@_connectSuccessMessage" ErrorMessage="@_connectErrorMessage">
<DataAnnotationsValidator/>
<fieldset class="box">
<div class="form-group">
<label for="PeerUrl" class="form-label" data-required>Peer URL</label>
<InputText @bind-Value="PeerModel.PeerUrl" id="PeerUrl" class="form-control"/>
<ValidationMessage For="@(() => PeerModel.PeerUrl)"/>
</div>
<button type="submit" class="btn btn-primary w-100" disabled="@(_connectEditContext!.Invalid || _connectingNewPeer)">
@if (_connectingNewPeer)
{
<LoadingIndicator/>
}
else
{
<span>Connect Peer</span>
}
</button>
</fieldset>
</ValidationEditContext>
}
<h2>Connect Peer</h2>
<ValidationEditContext @ref="_connectEditContext" Model="PeerModel" OnValidSubmit="ConnectToNewPeer" SuccessMessage="@_connectSuccessMessage" ErrorMessage="@_connectErrorMessage">
<DataAnnotationsValidator/>
<fieldset class="box">
<div class="form-group">
<label for="PeerUrl" class="form-label" data-required>Peer URL</label>
<InputText @bind-Value="PeerModel.PeerUrl" id="PeerUrl" class="form-control"/>
<ValidationMessage For="@(() => PeerModel.PeerUrl)"/>
</div>
<button type="submit" class="btn btn-primary w-100" disabled="@(_connectEditContext!.Invalid || _connectingNewPeer)">
@if (_connectingNewPeer)
{
<LoadingIndicator/>
}
else
{
<span>Connect Peer</span>
}
</button>
</fieldset>
</ValidationEditContext>
<h2>Channels</h2>
<ChannelsList Channels="_channels" OnCloseChannel="CloseChannel" UpdatingPeerId="@_updatingPeer" class="mb-4"/>
<ChannelsList Channels="_channels" OnCloseChannel="CloseChannel" UpdatingChannelId="@_updatingChannel" class="mb-4"/>
@if (_peers?.Any() is true && ChannelModel != null)
@if (_peers?.Any() is true)
{
<h2>Open Channel</h2>
<ValidationEditContext @ref="_openChannelEditContext" Model="ChannelModel" OnValidSubmit="() => OpenChannel()" SuccessMessage="@_channelSuccessMessage" ErrorMessage="@_channelErrorMessage">
<ValidationEditContext @ref="_openChannelEditContext" Model="ChannelModel" OnValidSubmit="HandleOpenChannel" SuccessMessage="@_channelSuccessMessage" ErrorMessage="@_channelErrorMessage">
<DataAnnotationsValidator/>
<fieldset class="box">
<div class="form-group">
<label for="PeerId" class="form-label" data-required>Peer</label>
<InputSelect @bind-Value="ChannelModel.PeerId" id="PeerId" class="form-select">
<option>Select peer</option>
@foreach (var peer in _peers)
{
<option value="@peer.NodeId">
@peer.NodeId
@if (!string.IsNullOrEmpty(peer.Info?.Label))
{
@($" - {peer.Info.Label}")
}
</option>
}
</InputSelect>
<ValidationMessage For="@(() => ChannelModel.PeerId)"/>
</div>
<div class="form-group">
<label for="Amount" class="form-label" data-required>Amount</label>
<InputAmount Id="Amount" @bind-Value="ChannelModel.Amount" Unit="@UnitMoney" Rate="@Rate" Currency="@Currency" OnToggleDisplayCurrency="ToggleDisplayCurrency" />
<ValidationMessage For="@(() => ChannelModel.Amount)"/>
</div>
@if (!ChannelModel.UseLNURL)
{
<div class="form-group">
<div class="d-flex justify-content-between">
<label for="PeerId" class="form-label" data-required>Peer</label>
<button type="button" class="btn btn-link p-0" @onclick="() => { ChannelModel.UseLNURL = true; }">Use LNURL</button>
</div>
<InputSelect @bind-Value="ChannelModel.PeerId" id="PeerId" class="form-select">
<option>Select peer</option>
@foreach (var peer in _peers)
{
<option value="@peer.NodeId">
@if (!string.IsNullOrEmpty(peer.Info?.Label))
{
@($"{peer.Info.Label} - ")
}
@peer.NodeId
</option>
}
</InputSelect>
<ValidationMessage For="@(() => ChannelModel.PeerId)"/>
</div>
<div class="form-group">
<label for="Amount" class="form-label" data-required>Amount</label>
<InputAmount Id="Amount" @bind-Value="ChannelModel.Amount" Unit="@UnitMoney" Rate="@Rate" Currency="@Currency" OnToggleDisplayCurrency="ToggleDisplayCurrency"/>
<ValidationMessage For="@(() => ChannelModel.Amount)"/>
</div>
}
else
{
<div class="form-group">
<div class="d-flex justify-content-between">
<label for="PeerId" class="form-label" data-required>LNURL Channel Request</label>
<button type="button" class="btn btn-link p-0" @onclick="() => { ChannelModel.UseLNURL = false; }">Select peer</button>
</div>
<InputText @bind-Value="ChannelModel.LNURL" id="LNURL" class="form-control"/>
<ValidationMessage For="@(() => ChannelModel.LNURL)"/>
</div>
}
<button type="submit" class="btn btn-primary w-100" disabled="@(_openChannelEditContext!.Invalid || _openingChannel)">
@if (_openingChannel)
{
@ -117,7 +131,7 @@
}
else
{
<LightningNodeStateAlert State="State.Value.LightningNodeState"/>
<LightningNodeStateAlert NodeState="State.Value.LightningNodeState" ConnectionState="State.Value.ConnectionState"/>
}
</Authorized>
<NotAuthorized>
@ -145,23 +159,30 @@
private string? _channelSuccessMessage;
private string? _channelErrorMessage;
private ValidationEditContext? _openChannelEditContext;
private OpenChannelModel? ChannelModel { get; set; } = new();
private OpenChannelModel ChannelModel { get; set; } = new();
private bool _connectingNewPeer;
private string? _connectSuccessMessage;
private string? _connectErrorMessage;
private ValidationEditContext? _connectEditContext;
private ConnectPeerModel? PeerModel { get; set; } = new();
private readonly CancellationTokenSource _refreshCts = new ();
private ConnectPeerModel PeerModel { get; set; } = new();
private class OpenChannelModel
{
[Required] public string? PeerId { get; set; }
[Required] public decimal? Amount { get; set; }
public bool UseLNURL { get; set; }
[RequiredIf(nameof(UseLNURL), false)]
public string? PeerId { get; set; }
[RequiredIf(nameof(UseLNURL), false)]
public decimal? Amount { get; set; }
[RequiredIf(nameof(UseLNURL), true)]
public string? LNURL { get; set; }
}
private class ConnectPeerModel
{
[Required] public string? PeerUrl { get; set; }
[Required]
public string? PeerUrl { get; set; }
}
protected override async Task OnInitializedAsync()
@ -171,7 +192,25 @@
if (await LightningNodeManager.CanConfigureLightningNode())
NavigationManager.NavigateTo(Routes.LightningSettings);
else
_ = RefreshData(_refreshCts.Token);
}
protected override ValueTask DisposeAsyncCore(bool disposing)
{
base.DisposeAsyncCore(disposing);
_refreshCts.Cancel();
return ValueTask.CompletedTask;
}
private async Task RefreshData(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
await FetchData();
await Task.Delay(TimeSpan.FromSeconds(15), token);
}
}
private async Task FetchData()
@ -193,15 +232,19 @@
return chans.Select(channel =>
{
var details = channel.channelDetails;
var counterpartyId = details?.get_counterparty().get_node_id();
var counterpartyNodeId = counterpartyId is not null ? Convert.ToHexString(counterpartyId).ToLowerInvariant() : null;
var channelId = details?.get_channel_id().get_a();
var outbound = details?.get_outbound_capacity_msat();
var inbound = details?.get_inbound_capacity_msat();
var peer = peers.FirstOrDefault(p => string.Equals(p.NodeId, counterpartyNodeId, StringComparison.InvariantCultureIgnoreCase));
var chan = new LightningChannelModel
{
Id = channel.channel.Id,
CounterpartyNodeId = counterpartyNodeId,
CounterpartyLabel = peer?.Info?.Label,
ChannelId = channelId,
Connected = _peers?.Any(p => string.Equals(p.NodeId, details?.get_counterparty().get_node_id().ToString(), StringComparison.InvariantCultureIgnoreCase)) is true,
Connected = counterpartyId is not null && peer is not null,
Confirmations = details?.get_confirmations() is Option_u32Z.Option_u32Z_Some x1 ? x1.some : null,
ConfirmationsRequired = details?.get_confirmations_required() is Option_u32Z.Option_u32Z_Some x2 ? x2.some : null,
FundingTxHash = details != null ? Convert.ToHexString(details.get_funding_txo().get_txid()).ToLowerInvariant() : null,
@ -224,21 +267,21 @@
alternates.Remove(channel.channel.Id);
chan.AlternateIds = alternates.ToArray();
if (details?.get_counterparty() is { } counterparty)
{
chan.CounterpartyNodeId = Convert.ToHexString(counterparty.get_node_id()).ToLowerInvariant();
chan.CounterpartyLabel = peers.FirstOrDefault(p => p.NodeId == chan.CounterpartyNodeId && !string.IsNullOrEmpty(p.Info?.Label))?.Info?.Label;
}
if (channel.channel.Archived)
{
chan.State = "Archived";
}
else if (details is null)
{
chan.State = channel.channel.AdditionalData.TryGetValue("CloseReasonHuman", out var reasonHuman)
? reasonHuman.GetString()
: "Unknown but probably closed";
if (channel.channel.AdditionalData.TryGetValue("CloseReasonHuman", out var reasonHuman))
{
var state = reasonHuman.GetString()?.Replace("ClosureReason_", "") ?? "Closed";
chan.State = Regex.Replace(state, "([A-Z])", " $1", RegexOptions.Compiled).Trim();
}
else
{
chan.State = "Unknown, probably closed";
}
}
else if (details.get_channel_shutdown_state() is Option_ChannelShutdownStateZ.Option_ChannelShutdownStateZ_Some some && some.some != ChannelShutdownState.LDKChannelShutdownState_NotShuttingDown)
{
@ -254,7 +297,7 @@
});
}
private async Task<IEnumerable<LightningPeerModel>?> GetPeers(Dictionary<string, PeerInfo> peerInfos)
private async Task<IEnumerable<LightningPeerModel>> GetPeers(Dictionary<string, PeerInfo> peerInfos)
{
if (Node == null) return [];
var peers = await Node.GetPeers();
@ -295,7 +338,7 @@
private async Task ConnectToNewPeer()
{
if (Node == null || PeerModel == null) return;
if (Node == null) return;
_connectSuccessMessage = _connectErrorMessage = _channelSuccessMessage = _channelErrorMessage = null;
try
@ -307,7 +350,8 @@
}
_connectingNewPeer = true;
var result = await Node.PeerHandler.ConnectAsync(nodeInfo, CancellationToken.None);
var result = await AsyncExtensions.RunInOtherThread(async () =>
await Node.PeerHandler.ConnectAsync(nodeInfo, CancellationToken.None));
if (result is not null)
{
_connectSuccessMessage = $"Connection to {PeerModel.PeerUrl} initiated";
@ -325,7 +369,16 @@
_connectingNewPeer = false;
if (string.IsNullOrEmpty(_connectErrorMessage))
await FetchData();
_ = RunAsyncWithDelay(FetchData);
}
// run with delay to allow peer manager to process events
private async Task RunAsyncWithDelay(Func<Task> t)
{
var token = _refreshCts.Token;
await Task.Delay(TimeSpan.FromSeconds(1), token);
await t();
await InvokeAsync(StateHasChanged);
}
private async Task ConnectPeer(LightningPeerModel peer)
@ -337,7 +390,8 @@
try
{
if (EndPointParser.TryParse(peer.Socket, 9735, out var endpoint))
await Node.PeerHandler.ConnectAsync(new PubKey(peer.NodeId), endpoint);
await AsyncExtensions.RunInOtherThread(async () =>
await Node.PeerHandler.ConnectAsync(new PubKey(peer.NodeId), endpoint));
else
_connectErrorMessage = $"Could not resolve endpoint for socket {peer.Socket}";
}
@ -347,7 +401,8 @@
}
_updatingPeer = null;
await FetchData();
_ = RunAsyncWithDelay(FetchData);
}
private async Task DisconnectPeer(LightningPeerModel peer)
@ -358,7 +413,8 @@
try
{
await Node.PeerHandler.DisconnectAsync(new PubKey(peer.NodeId));
await AsyncExtensions.RunInOtherThread(async () =>
await Node.PeerHandler.DisconnectAsync(new PubKey(peer.NodeId)));
}
catch (Exception e)
{
@ -366,7 +422,8 @@
}
_updatingPeer = null;
await FetchData();
_ = RunAsyncWithDelay(FetchData);
}
private async Task UpdatePeer(LightningPeerModel peer)
@ -379,9 +436,17 @@
await FetchData();
}
private async Task HandleOpenChannel()
{
if (ChannelModel.UseLNURL)
await ParseChannelRequest();
else
await OpenChannel();
}
private async Task OpenChannel()
{
if (Loading || Node == null || ChannelModel?.Amount is null || string.IsNullOrEmpty(ChannelModel.PeerId)) return;
if (Loading || Node == null || ChannelModel.Amount is null || string.IsNullOrEmpty(ChannelModel.PeerId)) return;
_connectSuccessMessage = _connectErrorMessage = _channelSuccessMessage = _channelErrorMessage = null;
_openingChannel = true;
@ -389,14 +454,14 @@
{
var amount = new Money(ChannelModel.Amount.Value, MoneyUnit.Satoshi);
var result = await Node.OpenChannel(amount, new PubKey(ChannelModel.PeerId));
if (result is Result_ChannelIdAPIErrorZ.Result_ChannelIdAPIErrorZ_OK ok)
if (result is Result_ChannelIdAPIErrorZ.Result_ChannelIdAPIErrorZ_OK)
{
_channelSuccessMessage = $"Channel creation started with id {Convert.ToHexString(ok.res.get_a())}";
_channelSuccessMessage = "Channel open initiated";
ChannelModel = new OpenChannelModel();
}
else if (result is Result_ChannelIdAPIErrorZ.Result_ChannelIdAPIErrorZ_Err err)
{
_channelErrorMessage = $"Error: {err.err.GetError()}";
_channelErrorMessage = err.err.GetError();
}
}
catch (Exception e)
@ -406,25 +471,26 @@
_openingChannel = false;
if (string.IsNullOrEmpty(_channelErrorMessage))
await FetchData();
_ = RunAsyncWithDelay(FetchData);
}
private async Task ParseChannelRequest(string lnurl, string name, bool trusted)
private async Task ParseChannelRequest()
{
if (Loading || Node == null || ChannelModel?.Amount is null || string.IsNullOrEmpty(ChannelModel.PeerId)) return;
if (Loading || Node == null || string.IsNullOrEmpty(ChannelModel.LNURL)) return;
_connectSuccessMessage = _connectErrorMessage = _channelSuccessMessage = _channelErrorMessage = null;
_openChannelEditContext!.MessageStore!.Clear();
try
{
var uri = LNURL.Parse(lnurl, out var tag);
var uri = LNURL.Parse(ChannelModel.LNURL, out var tag);
var http = HttpClientFactory.CreateClient();
var channelRequest = (LNURLChannelRequest) await LNURL.FetchInformation(uri, tag, http, new CancellationTokenSource(TimeSpan.FromSeconds(5)).Token);
if (channelRequest is null)
{
_channelErrorMessage = "The channel request is invalid";
_openChannelEditContext!.MessageStore!.Add(() => ChannelModel.LNURL, "The channel request is invalid");
_openChannelEditContext!.NotifyValidationStateChanged();
return;
}
if (!EndPointParser.TryParse($"{channelRequest.Uri.Host}:{channelRequest.Uri.Port}", 9735, out var endpoint))
{
_channelErrorMessage = "The channel request provided an invalid endpoint for the peer";
@ -432,21 +498,22 @@
}
_openingChannel = true;
await Node.Peer(channelRequest.Uri.NodeId, new PeerInfo { Endpoint = endpoint, Label = name, Trusted = trusted });
await Node.Peer(channelRequest.Uri.NodeId, new PeerInfo { Endpoint = endpoint, Trusted = true });
await ConnectPeer(new LightningPeerModel { NodeId = channelRequest.Uri.NodeId.ToString(), Socket = endpoint.ToEndpointString() });
await channelRequest.SendRequest(Node.NodeId, true, http, new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token);
_channelSuccessMessage = "Successfully initiated channel creation. Please wait for the peer to execute.";
}
catch (Exception e)
{
_channelErrorMessage = e.Message;
_openChannelEditContext!.MessageStore!.Add(() => ChannelModel.LNURL, e.Message);
_openChannelEditContext!.NotifyValidationStateChanged();
}
_openingChannel = false;
if (_channelSuccessMessage is null && _channelErrorMessage is null)
_channelErrorMessage = "Error opening channel";
else
await FetchData();
_ = RunAsyncWithDelay(FetchData);
}
private async Task CloseChannel(LightningChannelModel channel)
@ -475,12 +542,12 @@
var result = await Node.CloseChannel(channelId, counterparty, force);
if (result is Result_NoneAPIErrorZ.Result_NoneAPIErrorZ_OK)
{
_channelSuccessMessage = $"{(force ? "Force-closing" : "Closing")} channel {channelId} with {counterparty}.";
_channelSuccessMessage = $"{(force ? "Force-closing" : "Closing")} channel with {counterparty}.";
ChannelModel = new OpenChannelModel();
}
else if (result is Result_NoneAPIErrorZ.Result_NoneAPIErrorZ_Err err)
{
_channelErrorMessage = $"{(force ? "Force-closing" : "Closing")} channel {channelId} with {counterparty} failed: {err.err.GetError()}";
_channelErrorMessage = $"{(force ? "Force-closing" : "Closing")} channel with {counterparty} failed: {err.err.GetError()}";
}
}
catch (Exception e)
@ -489,7 +556,7 @@
}
_updatingChannel = null;
await FetchData();
_ = RunAsyncWithDelay(FetchData);
}
private void ToggleDisplayCurrency()

View File

@ -68,7 +68,7 @@
}
else
{
<LightningNodeStateAlert State="State.Value.LightningNodeState"/>
<LightningNodeStateAlert NodeState="State.Value.LightningNodeState" ConnectionState="State.Value.ConnectionState" />
}
</Authorized>
<NotAuthorized>

View File

@ -60,7 +60,7 @@
}
else
{
<LightningNodeStateAlert State="State.Value.LightningNodeState"/>
<LightningNodeStateAlert NodeState="State.Value.LightningNodeState" ConnectionState="State.Value.ConnectionState"/>
}
</Authorized>
<NotAuthorized>

View File

@ -5,6 +5,7 @@
@using Microsoft.Extensions.Logging
@using BTCPayApp.UI.Components.Layout
@using BTCPayApp.Core.Auth
@using BTCPayApp.Core.BTCPayServer
@using BTCPayApp.Core.LDK
@using BTCPayApp.Core.Wallet
@using BTCPayServer.Client.Models
@ -30,7 +31,11 @@
<section class="container">
<AuthorizeView Policy="@AppPolicies.CanModifySettings">
<Authorized>
@if (State.Value.LightningNodeState is LightningNodeState.NotConfigured)
@if (State.Value.LightningNodeState is not LightningNodeState.Loaded)
{
<LightningNodeStateAlert NodeState="State.Value.LightningNodeState" ConnectionState="State.Value.ConnectionState" />
}
@if (State.Value.LightningNodeState is LightningNodeState.NotConfigured && AppSettings.AllowWalletGeneration)
{
<button class="btn btn-primary" @onclick="ConfigureLNWallet">Configure Lightning Wallet</button>
}
@ -38,20 +43,19 @@
{
<h2 class="d-flex flex-wrap align-items-center gap-2">
<span>@(_config?.Alias ?? "Lightning Node")</span>
@if (!string.IsNullOrEmpty(_storePaymentMethodIdentifier)
// && _storePaymentMethodIdentifier == ConnectionString
)
@if (IsStorePaymentMethod is true)
{
<span class="badge bg-info">Lightning Payment Method</span>
}
</h2>
<div class="box mb-5">
@if (Node is not null)
<div class="box">
@if (LightningNodeManager.IsActive)
{
<div class="form-floating">
<TruncateCenter Text="@Node.NodeId.ToString()" Padding="15" Copy="true" Elastic="true" class="form-control-plaintext"/>
<label>Node ID</label>
</div>
<code class="text-wrap">@Node.NodeId.ToString()</code>
}
@if (!string.IsNullOrEmpty(_config?.LightningDerivationPath))
@ -62,25 +66,20 @@
</div>
}
@* @if (!string.IsNullOrEmpty(ConnectionString)) *@
@* { *@
@* <div class="form-floating"> *@
@* <TruncateCenter Text="@ConnectionString" Padding="15" Copy="true" Elastic="true" class="form-control-plaintext"/> *@
@* <label>Connection String</label> *@
@* </div> *@
@* *@
@* @if (!string.IsNullOrEmpty(StoreId) && _storePaymentMethodIdentifier != ConnectionString) *@
@* { *@
@* <button class="btn btn-primary my-3" @onclick="SetStorePaymentMethod">Set as lightning payment method for store</button> *@
@* } *@
@* } *@
@if (!string.IsNullOrEmpty(ConnectionString))
{
<div class="form-floating">
<TruncateCenter Text="@ConnectionString" Padding="15" Copy="true" Elastic="true" class="form-control-plaintext"/>
<label>Connection String</label>
</div>
@if (IsStorePaymentMethod is false)
{
<button class="btn btn-primary my-3" @onclick="SetStorePaymentMethod">Set as lightning payment method for store</button>
}
}
</div>
}
else
{
<LightningNodeStateAlert State="State.Value.LightningNodeState" />
}
@if (State.Value.LightningNodeState is LightningNodeState.Init or LightningNodeState.Loaded or LightningNodeState.Stopped or LightningNodeState.Error)
@if (State.Value.LightningNodeState is LightningNodeState.Init or LightningNodeState.Loaded or LightningNodeState.Stopped or LightningNodeState.Error && State.Value.ConnectionState != BTCPayConnectionState.ConnectedAsSecondary)
{
<h2>Lightning Control</h2>
<div class="box mb-2 d-grid d-sm-flex flex-wrap gap-3 buttons">
@ -112,7 +111,7 @@
@if (Node is not null)
{
<h2>Lightning Settings</h2>
<ValidationEditContext @ref="_validationEditContext" Model="Model" OnValidSubmit="UpdateConfig" SuccessMessage="@SuccessMessage" ErrorMessage="@ErrorMessage">
<ValidationEditContext @ref="_validationEditContext" Model="Model" OnValidSubmit="UpdateConfig" SuccessMessage="@SuccessMessage" ErrorMessage="@ErrorMessage">
<DataAnnotationsValidator/>
<fieldset class="box">
@if (_jitOptions?.Any() is true)
@ -151,12 +150,14 @@
@code {
private LightningConfig? _config;
private LDKNode? Node => LightningNodeManager.Node;
private APIKey? _apiKey;
private string? StoreId => AccountManager.CurrentStore?.Id;
private static string PaymentMethodId => LightningNodeManager.PaymentMethodId;
private string? _storePaymentMethodIdentifier;
// We need a ui/component for the api keys now.
// private string? ConnectionString => LightningNodeManager.ConnectionString;
private string? ConnectionString => AccountManager.UserInfo?.UserId is {} userId && _apiKey is not null ? _apiKey.ConnectionString(userId) : null;
private bool? IsStorePaymentMethod => !string.IsNullOrEmpty(ConnectionString) && string.Equals(_storePaymentMethodIdentifier, ConnectionString);
private string[]? _jitOptions;
private SettingsModel Model { get; set; } = new();
private string? SuccessMessage { get; set; }
private string? ErrorMessage { get; set; }
@ -180,6 +181,9 @@
if (!string.IsNullOrEmpty(StoreId))
await GetStorePaymentMethod();
if (!string.IsNullOrEmpty(StoreId) && Node?.ApiKeyManager is not null)
_apiKey = await Node.ApiKeyManager.GetKeyForStore(StoreId, APIKeyPermission.Write);
}
protected override ValueTask DisposeAsyncCore(bool disposing)
@ -200,7 +204,7 @@
{
await Node.UpdateConfig(config =>
{
config.JITLSP = Model.JitLsp;
config.JITLSP = string.IsNullOrEmpty(Model.JitLsp) ? null : Model.JitLsp;
config.RapidGossipSyncUrl = string.IsNullOrEmpty(Model.RgsUrl) ? null : Uri.TryCreate(Model.RgsUrl, UriKind.Absolute, out var uri) ? uri: null;
return Task.FromResult((config, true));
});
@ -234,29 +238,29 @@
Logger.LogDebug(ex, "Payment method {PaymentMethodId} unset for store {StoreId}", PaymentMethodId, StoreId);
}
}
//
// private async Task SetStorePaymentMethod()
// {
// if (string.IsNullOrEmpty(StoreId) || string.IsNullOrEmpty(ConnectionString)) return;
// _successMessage = _errorMessage = null;
// try
// {
// var pm = await AccountManager.GetClient().UpdateStorePaymentMethod(StoreId, PaymentMethodId, new UpdatePaymentMethodRequest
// {
// Enabled = true,
// Config = ConnectionString
// });
// _storePaymentMethodIdentifier = GetConnectionString(pm);
// _successMessage = "Store payment method set.";
// }
// catch (Exception ex)
// {
// _errorMessage = $"Error setting store payment method: {ex.Message}";
// Logger.LogError(ex, "Error setting payment method {PaymentMethodId} for store {StoreId}", PaymentMethodId, StoreId);
// }
//
// await InvokeAsync(StateHasChanged);
// }
private async Task SetStorePaymentMethod()
{
if (string.IsNullOrEmpty(StoreId) || string.IsNullOrEmpty(ConnectionString)) return;
SuccessMessage = ErrorMessage = null;
try
{
var pm = await AccountManager.GetClient().UpdateStorePaymentMethod(StoreId, PaymentMethodId, new UpdatePaymentMethodRequest
{
Enabled = true,
Config = ConnectionString
});
_storePaymentMethodIdentifier = GetConnectionString(pm);
SuccessMessage = "Store payment method set.";
}
catch (Exception ex)
{
ErrorMessage = $"Error setting store payment method: {ex.Message}";
Logger.LogError(ex, "Error setting payment method {PaymentMethodId} for store {StoreId}", PaymentMethodId, StoreId);
}
await InvokeAsync(StateHasChanged);
}
private async Task ConfigureLNWallet()
{

View File

@ -82,7 +82,7 @@ else
return ValueTask.CompletedTask;
}
private async Task CreateInvoice(CreatePosInvoiceRequest req)
private async Task CreateInvoice(Core.Models.CreatePosInvoiceRequest req)
{
_errorMessage = null;
req.AppId = AppId;

View File

@ -1,25 +1,28 @@
@attribute [Route(Routes.AppLogs)]
@using System.Text
@using BTCPayApp.Core.Contracts
@using BTCPayApp.Core.Services
@using BTCPayApp.UI.Components.Layout
@using Serilog.Events
@inject ConfigProvider ConfigProvider
@inject LoggingService LogService
@inject IJSRuntime JS
@inject IEmailService EmailService
<PageTitle>Application Logs</PageTitle>
<SectionContent SectionId="_Layout.Top">
<Titlebar Back>
<h1>Logs</h1>
<SectionContent SectionId="Titlebar.End">
<InputSelect @bind-Value="LogService.LogLevel" @bind-Value:after="() => PersistLogLevel(LogService.LogLevel)" id="LogLevel" class="form-select form-select-sm px-2 py-1 w-auto" style="padding-right: var(--btcpay-space-l) !important;background-position-x:90%;">
@foreach (var lvl in LogLevels)
<InputSelect @bind-Value="_logLevel" @bind-Value:after="LevelChanged" id="LogLevel" class="form-select form-select-sm px-2 py-1 w-auto" style="padding-right: var(--btcpay-space-l) !important;background-position-x:90%;">
@foreach (var lvl in LoggingService.Levels)
{
<option value="@lvl" selected="@(LogService.LogLevel == lvl)">@lvl</option>
<option value="@lvl" selected="@(_logLevel == lvl)">@(lvl == LogEventLevel.Information ? "Info" : lvl)</option>
}
</InputSelect>
<InputSelect @bind-Value="_logCount" @bind-Value:after="CountChanged" id="LogCount" class="form-select form-select-sm px-2 py-1 w-auto" style="padding-right: var(--btcpay-space-l) !important;background-position-x:90%;">
@foreach (var count in Counts)
{
<option value="@count" selected="@(_logCount == count)">@count</option>
}
</InputSelect>
</SectionContent>
@ -39,6 +42,10 @@
}
@if (HasLogs)
{
<div id="CtaContainer" class="container d-flex flex-column gap-3">
<button type="button" class="btn btn-secondary" data-clipboard-target="#logs">Copy logs</button>
<button type="button" class="btn btn-primary" @onclick="SendLogs">Send via email</button>
</div>
<pre><code id="logs">@_logContent</code></pre>
}
else
@ -47,20 +54,15 @@
<p class="text-muted my-0">There are no logs, yet.</p>
</div>
}
@if (HasLogs)
{
<div id="CtaContainer" class="container d-flex align-items-center justify-content-between">
<button type="button" class="btn btn-primary w-100" @onclick="SaveLogs">Send logs</button>
</div>
}
</section>
@code {
private bool _isLoading;
private string? _logContent;
private int _logCount = Counts.First();
private string? _errorMessage;
private static LogEventLevel[] LogLevels => [LogEventLevel.Error, LogEventLevel.Warning, LogEventLevel.Information, LogEventLevel.Debug, LogEventLevel.Verbose];
private LogEventLevel _logLevel = LogEventLevel.Information;
private static readonly int[] Counts = [50, 100, 200, 500];
private bool HasLogs => !string.IsNullOrEmpty(_logContent);
protected override async Task OnInitializedAsync()
@ -68,7 +70,8 @@
try
{
_isLoading = true;
_logContent = await LogService.GetLatestLogAsync();
_logLevel = await ConfigProvider.Get<LogEventLevel?>("logLevel") ?? LogEventLevel.Information;
await RefreshLogContent();
}
catch (Exception ex)
{
@ -80,16 +83,24 @@
}
}
private async Task PersistLogLevel(LogEventLevel logLevel)
private async Task LevelChanged()
{
await ConfigProvider.Set("logLevel", logLevel, false);
await ConfigProvider.Set("logLevel", _logLevel, false);
await RefreshLogContent();
}
private async Task SaveLogs()
private async Task CountChanged()
{
//var bytes = Encoding.UTF8.GetBytes(_logContent!);
//await JS.InvokeAsync<object>("Interop.saveAsFile", "btcpayapp.log", Convert.ToBase64String(bytes));
var logFilePath = await LogService.GetAppLogFilePath();
await EmailService.SendAsync("App Log File", _logContent!);
await RefreshLogContent();
}
private async Task RefreshLogContent()
{
_logContent = await LogService.GetLatestLogAsync(_logLevel, _logCount);
}
private async Task SendLogs()
{
await EmailService.SendAsync("App Log File", _logContent!, "app@btcpayserver.org");
}
}

View File

@ -3,6 +3,7 @@
@using BTCPayApp.Core.Auth
@using BTCPayApp.Core.BTCPayServer
@using BTCPayApp.Core.Contracts
@using BTCPayApp.Core.Helpers
@using BTCPayApp.Core.Models
@using BTCPayApp.Core.Wallet
@using BTCPayApp.UI.Features
@ -214,27 +215,30 @@
</div>
</AuthorizeView>
<AuthorizeView Policy="@AppPolicies.CanModifySettings">
<h2>Bitcoin</h2>
<div class="box">
<ul class="list-group list-group-flush list-group-links">
<li class="list-group-item">
<a href="@Routes.WalletSettings">
<Icon Symbol="wallet-wallet"/>
<span>Onchain Wallet</span>
<Icon Symbol="caret-right"/>
</a>
</li>
<li class="list-group-item">
<a href="@Routes.LightningSettings">
<Icon Symbol="lightning-node"/>
<span>Lightning Node</span>
<Icon Symbol="caret-right"/>
</a>
</li>
</ul>
</div>
</AuthorizeView>
@if (State.Value.ConnectionState == BTCPayConnectionState.ConnectedAsPrimary)
{
<AuthorizeView Policy="@AppPolicies.CanModifySettings">
<h2>Bitcoin</h2>
<div class="box">
<ul class="list-group list-group-flush list-group-links">
<li class="list-group-item">
<a href="@Routes.WalletSettings">
<Icon Symbol="wallet-wallet"/>
<span>Onchain Wallet</span>
<Icon Symbol="caret-right"/>
</a>
</li>
<li class="list-group-item">
<a href="@Routes.LightningSettings">
<Icon Symbol="lightning-node"/>
<span>Lightning Node</span>
<Icon Symbol="caret-right"/>
</a>
</li>
</ul>
</div>
</AuthorizeView>
}
}
<AuthorizeView Policy="@AppPolicies.CanModifySettings">
@ -305,12 +309,10 @@
</button>
}
</div>
</li>
@if (InstanceInfo != null)
{
<li class="list-group-item">
@if (InstanceInfo != null)
{
<div class="justify-content-start">
<span class="m-2 me-3 btcpay-status btcpay-status--@(State.Value.ConnectionState switch { BTCPayConnectionState.ConnectedAsPrimary or BTCPayConnectionState.ConnectedAsSecondary or BTCPayConnectionState.ConnectedFinishedInitialSync => "enabled", BTCPayConnectionState.Disconnected => "disabled", _ => "pending" })"></span>
<span class="ms-2 me-3 btcpay-status invisible"></span>
<span>
Instance: @InstanceInfo.BaseUrl
@if (!string.IsNullOrEmpty(InstanceInfo.ServerName))
@ -319,8 +321,17 @@
}
</span>
</div>
</li>
}
}
@if (_deviceId != 0)
{
<div class="justify-content-start">
<span class="m-2 me-3 btcpay-status invisible"></span>
<span>
Device ID: @_deviceId
</span>
</div>
}
</li>
@if (State.Value.ConnectionState == BTCPayConnectionState.ConnectedAsPrimary)
{
<li class="list-group-item">
@ -379,22 +390,22 @@
</li>
</ul>
</div>
<h2>Logout</h2>
<div class="box">
@switch (State.Value.ConnectionState)
{
case BTCPayConnectionState.ConnectedAsPrimary:
<p>This device is currently connected as primary device for communication with the BTCPay Server.</p>
<p>Please note, that when you sign out of the account on this device, your Lightning node will go offline and you will not be able to receive any payments.</p>
break;
case BTCPayConnectionState.ConnectedAsSecondary:
<p>This device is currently connected as additional device for communication with the BTCPay Server.</p>
<p>Please ensure, that your primary device is still connected to the BTCPay Server, because otherwise you will not be able to receive any payments.</p>
break;
}
<button class="btn btn-outline-danger w-100 mt-2" type="button" @onclick="Logout">Logout</button>
</div>
</AuthorizeView>
<h2>Logout</h2>
<div class="box">
@switch (State.Value.ConnectionState)
{
case BTCPayConnectionState.ConnectedAsPrimary:
<p>This device is currently connected as the primary device for communication with the BTCPay Server.</p>
<p>Please note that when you sign out of the account on this device, your Lightning node will go offline, and you will not be able to receive any payments.</p>
break;
case BTCPayConnectionState.ConnectedAsSecondary:
<p>This device is currently connected as an additional device for communication with the BTCPay Server.</p>
<p>Please ensure that your primary device is still connected to the BTCPay Server, because otherwise you will not be able to receive any payments.</p>
break;
}
<button class="btn btn-outline-danger w-100 mt-2" type="button" @onclick="Logout">Logout</button>
</div>
</section>
}
@ -412,6 +423,7 @@
private bool _sending;
private string? _errorMessage;
private int[]? _fees;
private long _deviceId;
private class SettingsModel
{
@ -436,6 +448,7 @@
_account = AccountManager.Account;
_config = await ConfigProvider.Get<BTCPayAppConfig>(BTCPayAppConfig.Key);
_deviceId = await ConfigProvider.GetDeviceIdentifier();
Model.Theme = UiState.Value.SelectedTheme;
ConnectionManager.ConnectionChanged += OnConnectionChanged;

View File

@ -141,7 +141,6 @@
// prevent duplicate submission due to quirk in QR reader lib
if (code == _qrInput) return;
_qrInput = code;
Logger.LogInformation("Scanned QR code: {QrCode}", code);
Model.EncryptionKey = code;
StateHasChanged();

View File

@ -130,7 +130,7 @@
{
if (Stores?.Any() is not true)
NavigationManager.NavigateTo(Routes.CreateStore);
else if (Stores?.Count() == 1)
else if (Stores?.Count() == 1 && string.IsNullOrEmpty(_initialStoreId))
await SelectStore(Stores!.First().Id);
}

Some files were not shown because too many files have changed in this diff Show More