Skip to content

Commit

Permalink
Minor refactorings
Browse files Browse the repository at this point in the history
dennisreimann committed Jan 23, 2025
1 parent 697466f commit 5ff026d
Showing 16 changed files with 64 additions and 76 deletions.
10 changes: 3 additions & 7 deletions BTCPayApp.Core/Backup/SingleKeyDataProtector.cs
Original file line number Diff line number Diff line change
@@ -11,9 +11,7 @@ public class SingleKeyDataProtector : IDataProtector
public SingleKeyDataProtector(byte[] key)
{
if (key.Length != 32) // AES-256 key size
{
throw new ArgumentException("Key length must be 32 bytes.");
}

_key = key;
}
@@ -43,14 +41,12 @@ public byte[] Unprotect(byte[] protectedData)
using var aes = Aes.Create();
aes.Key = _key;

if(protectedData.Length == 0)
{
if (protectedData.Length == 0)
return protectedData;
}

var iv = protectedData.Take(16).ToArray();
var cipherText = protectedData.Skip(16).ToArray();

return aes.DecryptCbc(cipherText, iv);
}

}
}
42 changes: 19 additions & 23 deletions BTCPayApp.Core/Backup/SyncService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Net.Http.Headers;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using BTCPayApp.Core.Auth;
@@ -44,9 +44,9 @@ public class SyncService(
public async Task<bool> EncryptionKeyRequiresImport()
{
var dataProtector = await GetDataProtector();

if (dataProtector is not null)
return false;

var api = await GetUnencryptedVSSAPI();
try
{
@@ -60,6 +60,7 @@ public async Task<bool> EncryptionKeyRequiresImport()

if (dataProtector is null)
return true;

var decrypted = dataProtector.Unprotect(res.Value.ToByteArray());
return "kukks" == Encoding.UTF8.GetString(decrypted);
}
@@ -92,7 +93,7 @@ public async Task<bool> SetEncryptionKey(string key)

try
{
var res = await api.GetObjectAsync(new GetObjectRequest()
var res = await api.GetObjectAsync(new GetObjectRequest
{
Key = "encryptionKeyTest"
});
@@ -106,18 +107,15 @@ public async Task<bool> SetEncryptionKey(string key)
EncryptionKeyChanged?.Invoke(this);
return true;
}
else
{
return false;
}
return false;
}
}
catch (VSSClientException e) when (e.Error.ErrorCode == ErrorCode.NoSuchKeyException)
{
}
catch (Exception e)
{
logger.LogError("Error while setting encryption key: {message}", e.Message);
logger.LogError("Error while setting encryption key: {Message}", e.Message);
return false;
}

@@ -158,17 +156,17 @@ private Task<IVSSAPI> GetUnencryptedVSSAPI()

private static async Task<KeyValue[]> CreateLocalVersions(AppDbContext dbContext)
{
var settings = dbContext.Settings.Where(setting => setting.Backup).Select(setting => new KeyValue()
var settings = dbContext.Settings.Where(setting => setting.Backup).Select(setting => new KeyValue
{
Key = setting.EntityKey,
Version = setting.Version
});
var channels = dbContext.LightningChannels.Select(channel => new KeyValue()
var channels = dbContext.LightningChannels.Select(channel => new KeyValue
{
Key = channel.EntityKey,
Version = channel.Version
});
var payments = dbContext.LightningPayments.Select(payment => new KeyValue()
var payments = dbContext.LightningPayments.Select(payment => new KeyValue
{
Key = payment.EntityKey,
Version = payment.Version
@@ -206,21 +204,19 @@ await db.Database.ExecuteSqlRawAsync(
var toUpsert = remoteVersions.KeyVersions.Where(remoteVersion => localVersions.All(localVersion =>
localVersion.Key != remoteVersion.Key || localVersion.Version < remoteVersion.Version)).Where(value => value.Key != "encryptionKeyTest").ToArray();

if (toDelete.Length == 0 && !toUpsert.Any())
if (toDelete.Length == 0 && toUpsert.Length == 0)
return;
logger.LogInformation("Syncing to local: {ToDelete} to delete, {ToUpsert} to upsert", toDelete.Length,
toUpsert.Count());
toUpsert.Length);

foreach (var upsertItem in toUpsert)
{
if (upsertItem.Value is null or {Length: 0})
if (upsertItem.Value is not (null or { Length: 0 })) continue;
var item = await backupApi.GetObjectAsync(new GetObjectRequest()
{
var item = await backupApi.GetObjectAsync(new GetObjectRequest()
{
Key = upsertItem.Key,
}, cancellationToken);
upsertItem.MergeFrom(item.Value);
}
Key = upsertItem.Key,
}, cancellationToken);
upsertItem.MergeFrom(item.Value);
}

var settingsToDelete = toDelete.Where(key => key.Key.StartsWith("Setting_")).Select(key => key.Key);
@@ -281,7 +277,7 @@ await db.Database.ExecuteSqlRawAsync(
setting1.EntityKey == outbox.Key && setting1.Backup);
if (setting == null)
return null;
return new KeyValue()
return new KeyValue
{
Key = outbox.Key,
Value = ByteString.CopyFrom(setting.Value),
@@ -413,14 +409,14 @@ private async Task ContinuouslySync(bool local, CancellationToken cancellationTo
if (local)
await SyncToLocal(cancellationToken);
else
await SyncToRemote( cancellationToken);
await SyncToRemote(cancellationToken);
}
catch (OperationCanceledException)
{
}
catch (Exception e)
{
logger.LogError(e, "Error while syncing to {Local}", local ? "local" : "remote");
logger.LogError(e, "Error while syncing to {Target}", local ? "local" : "remote");
}
finally
{
4 changes: 2 additions & 2 deletions BTCPayApp.Core/LDK/LDKPeerHandler.cs
Original file line number Diff line number Diff line change
@@ -55,7 +55,6 @@ public async Task StartAsync(CancellationToken cancellationToken)
private void DescriptorsOnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
_node.PeersChanged();

}

private async Task BtcPayAppServerClientOnOnServerNodeInfo(object? sender, string? e)
@@ -76,9 +75,10 @@ private async Task BtcPayAppServerClientOnOnServerNodeInfo(object? sender, strin

private TaskCompletionSource? _configTcs;

private async Task ConfigUpdated(object? sender, LightningConfig e)
private Task ConfigUpdated(object? sender, LightningConfig e)
{
_configTcs?.TrySetResult();
return Task.CompletedTask;
}

private async Task ContinuouslyAttemptToConnectToPersistentPeers(CancellationToken ctsToken)
4 changes: 2 additions & 2 deletions BTCPayApp.Core/LSP/JIT/VoltageFlow2Jit.cs
Original file line number Diff line number Diff line change
@@ -73,7 +73,7 @@ public VoltageFlow2Jit(IHttpClientFactory httpClientFactory, Network network, LD

private async Task<FlowInfoResponse> GetInfo(CancellationToken cancellationToken = default)
{
var path = "/api/v1/info";
const string path = "/api/v1/info";
var response = await _httpClient.GetAsync(path, cancellationToken);
try
{
@@ -91,7 +91,7 @@ private async Task<FlowInfoResponse> GetInfo(CancellationToken cancellationToken
private async Task<FlowFeeResponse> GetFee(LightMoney amount, PubKey pubkey,
CancellationToken cancellationToken = default)
{
var path = "/api/v1/fee";
const string path = "/api/v1/fee";
var request = new FlowFeeRequest(amount, pubkey);
var response = await _httpClient.PostAsJsonAsync(path, request, cancellationToken);
try
6 changes: 3 additions & 3 deletions BTCPayApp.UI/Components/AmountDisplay.razor
Original file line number Diff line number Diff line change
@@ -2,14 +2,14 @@

@inject DisplayFormatter DisplayFormatter

<span @onclick="ToggleDisplayCurrency" @onclick:stopPropagation class="@CssClass">@DisplayFormatter.Currency(Value!.Value, Unit!, DisplayFormatter.CurrencyFormat.Symbol)</span>
<span @onclick="ToggleDisplayCurrency" @onclick:stopPropagation class="@CssClass">@DisplayFormatter.Currency(Value, Unit, DisplayFormatter.CurrencyFormat.Symbol)</span>

@code {
[Parameter, EditorRequired]
public decimal? Value { get; set; }
public required decimal Value { get; set; }

[Parameter, EditorRequired]
public string? Unit { get; set; }
public required string Unit { get; set; }

[Parameter]
public EventCallback OnToggleDisplayCurrency { get; set; }
5 changes: 2 additions & 3 deletions BTCPayApp.UI/Components/AppItemsEditor.razor
Original file line number Diff line number Diff line change
@@ -32,10 +32,10 @@
{
<span class="fw-semibold badge text-bg-info">@(context.PriceType == AppItemPriceType.Topup ? "Any amount" : "Free")</span>
}
else
else if (context.Price.HasValue)
{
<span class="fw-semibold text-muted">
<AmountDisplay Value="@context.Price" Unit="@Currency"/> @(context.PriceType == AppItemPriceType.Minimum ? " minimum" : null)
<AmountDisplay Value="@context.Price.Value" Unit="@Currency"/> @(context.PriceType == AppItemPriceType.Minimum ? " minimum" : null)
</span>
}
@if (context.Inventory.HasValue)
@@ -180,7 +180,6 @@
private Guid _inputFileId = Guid.NewGuid();
private ValidationEditContext? _validationEditContext;
private AppItemModel? SelectedItem { get; set; }
private string? _successMessage;
private string? _errorMessage;

private async Task SelectItem(AppItem? item)
2 changes: 1 addition & 1 deletion BTCPayApp.UI/Components/LightningPaymentItem.razor
Original file line number Diff line number Diff line change
@@ -3,7 +3,7 @@

<div>
<div class="d-flex flex-wrap align-items-center justify-content-between gap-2" @onclick="() => _showDetails = !_showDetails">
<AmountDisplay Value="Payment.Value.ToDecimal(UnitLightMoney)" Unit="@Unit" OnToggleDisplayCurrency="ToggleDisplayCurrency" class="text-end fw-semibold" />
<AmountDisplay Value="Payment.Value!.ToDecimal(UnitLightMoney)" Unit="@Unit" OnToggleDisplayCurrency="ToggleDisplayCurrency" class="text-end fw-semibold" />
<span class="text-muted">
<DateDisplay DateTimeOffset="@Payment.Timestamp"/>
</span>
4 changes: 2 additions & 2 deletions BTCPayApp.UI/Models/TransactionModel.cs
Original file line number Diff line number Diff line change
@@ -19,9 +19,9 @@ public enum TransactionType
public class TransactionModel
{
public string? Id { get; set; }
public LightMoney? Value { get; set; }
public required LightMoney Value { get; set; }
public required string Status { get; set; }
public DateTimeOffset Timestamp { get; set; }
public string? Status { get; set; }
public TransactionType Type { get; set; }
public TransactionPaymentMethod PaymentMethod { get; set; }
public AppLightningPayment? LightningPayment { get; set; }
4 changes: 2 additions & 2 deletions BTCPayApp.UI/Pages/Lightning/ChannelsPage.razor
Original file line number Diff line number Diff line change
@@ -136,7 +136,7 @@
}

<h2>Channels</h2>
@if (_channels?.Any() is true)
@if (Node != null && _config != null && _channels?.Any() is true)
{
<div class="table-responsive">
<table class="table">
@@ -228,7 +228,7 @@
}
</td>
<td>
@if (active)
@if (active && channel.Value.channelDetails != null)
{
<button type="button" class="btn btn-primary btn-sm" @onclick="() => Node.CloseChannel(channel.Value.channelDetails.get_channel_id(), new PubKey(channel.Value.channelDetails.get_counterparty().get_node_id()), !connected) ">Close</button>
}
2 changes: 1 addition & 1 deletion BTCPayApp.UI/Pages/Lightning/ReceivePage.razor
Original file line number Diff line number Diff line change
@@ -116,7 +116,7 @@
var result = await PaymentsManager.RequestPayment(LightMoney.Satoshis(Model.Amount ?? 0), TimeSpan.FromDays(1), hash);

_successMessage = "Payment request created";
_paymentRequest = result.PaymentRequest.ToString();
_paymentRequest = result.PaymentRequest!.ToString();
Model = new ReceiveModel();
}
catch (Exception e)
4 changes: 2 additions & 2 deletions BTCPayApp.UI/Pages/Lightning/SendPage.razor
Original file line number Diff line number Diff line change
@@ -98,15 +98,15 @@

private async void SendPayment()
{
if (Node is null || string.IsNullOrEmpty(Model.PaymentRequest)) return;
if (Node is null || PaymentsManager is null || string.IsNullOrEmpty(Model.PaymentRequest)) return;
_successMessage = _errorMessage = null;
_paymentSending = true;
await Wrap(async () =>
{
try
{
var invoice = BOLT11PaymentRequest.Parse(Model.PaymentRequest, Node.Network);
var result = await Node.PaymentsManager.PayInvoice(invoice, Model.Amount is null ? null : LightMoney.Satoshis((long)Model.Amount.Value));
var result = await PaymentsManager.PayInvoice(invoice, Model.Amount is null ? null : LightMoney.Satoshis((long)Model.Amount.Value));
_successMessage = $"Payment {result.PaymentId} sent with status {result.Status}";
Model = new SendModel();
}
2 changes: 1 addition & 1 deletion BTCPayApp.UI/Pages/Settings/AccountPage.razor
Original file line number Diff line number Diff line change
@@ -67,7 +67,7 @@
</section>

@code {
private AccountModel? Model { get; set; }
private AccountModel Model { get; set; } = new();
private bool _sending;
private string? _errorMessage;
private string? _successMessage;
9 changes: 1 addition & 8 deletions BTCPayApp.UI/Pages/Settings/PasswordPage.razor
Original file line number Diff line number Diff line change
@@ -47,18 +47,11 @@
</section>

@code {
private PasswordModel? Model { get; set; }
private PasswordModel Model { get; set; } = new ();
private bool _sending;
private string? _errorMessage;
private string? _successMessage;

protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();

Model = new PasswordModel();
}

public async Task HandleValidSubmit()
{
_errorMessage = _successMessage = null;
2 changes: 1 addition & 1 deletion BTCPayApp.UI/Pages/Settings/PosPage.razor
Original file line number Diff line number Diff line change
@@ -186,7 +186,7 @@
_successMessage = null;

var app = AppData!;
var tipPercentages = string.IsNullOrEmpty(Model.CustomTipPercentages) ? null : AppItemParser.SplitStringListToInts(ListSeparator, Model.CustomTipPercentages);
var tipPercentages = string.IsNullOrEmpty(Model!.CustomTipPercentages) ? null : AppItemParser.SplitStringListToInts(ListSeparator, Model.CustomTipPercentages);
Dispatcher.Dispatch(new StoreState.UpdatePointOfSale(AppId!, new PointOfSaleAppRequest
{
Title = Model!.Title,
Loading

0 comments on commit 5ff026d

Please sign in to comment.