6 Commits

Author SHA1 Message Date
davide bb9819ec96 docs: document CsCheck property-based tests in README and CLAUDE.md 2026-06-13 22:09:52 +02:00
davide 8cdbd70966 test: add property-based tests with CsCheck (218 total)
9 property tests covering:
- CoinAmount: TryParseIn/TryParseCoins never throw on arbitrary strings;
  FormatIn→TryParseIn roundtrip holds for any sats in [0, MaxSupply];
  parsed results always ≥ 0
- EncryptedFile: Encrypt→Decrypt roundtrip for any plaintext/password;
  wrong password always raises WrongPasswordException (never other exceptions);
  IsEncrypted never throws
- MerkleProof: every leaf in a randomly generated tree verifies against its root
  (1–16 leaves, covers odd/even/single at every position); foreign txid never
  verifies and never crashes
2026-06-13 22:09:02 +02:00
davide ee0b73dd52 test: expand coverage to 209 tests across all core modules
Added tests for CoinAmount (all units, comma decimal, sub-satoshi rejection,
overflow, unknown unit ArgumentException, roundtrip), Storage (nonce/salt
uniqueness per encrypt, atomic write, WalletLock acquire/release/stale-file),
WalletLoader (NewFromMnemonic, passphrase isolation, watch-only, invalid
inputs, ProfileOf), SPV/Merkle (single tx, odd/even counts, altered proof,
empty list), and Chain (unknown NetKind, distinct profiles, port constants).
2026-06-13 21:59:51 +02:00
davide a8d48bedad docs: add SECURITY.md with threat model and SPV trust assumptions
Covers: what the wallet protects against (AES-GCM at rest, Merkle SPV
verification, TLS TOFU pinning) and what it does not (compromised OS,
eclipse attacks, traffic analysis). Documents key/seed management,
encryption parameters, TLS pinning behaviour, backup guidance, and
known v1 limitations (no Tor, no coin control, no hardware wallet).
2026-06-13 21:15:41 +02:00
davide 5d061c6f21 docs(storage): document plaintext save caveat on WalletStore.Save
The password parameter accepts null, which saves the wallet in plaintext.
The XML doc comment now makes explicit that this is only acceptable when
the user has explicitly opted out of encryption with a UI warning shown.
2026-06-13 21:15:28 +02:00
davide 2ddc0f920c refactor(app): split MainWindowViewModel into partial files by area
1300-line monolith → 7 focused files (max 359 lines each):
  MainWindowViewModel.cs         core fields, constructor, lifecycle
  MainWindowViewModel.Wizard.cs  setup wizard and wallet open/close flows
  MainWindowViewModel.Settings.cs language, unit, overlay flags
  MainWindowViewModel.Sync.cs    server config, connection, sync loop
  MainWindowViewModel.Send.cs    send panel
  MainWindowViewModel.Contacts.cs contact management
  MainWindowViewModel.Receive.cs balance display, QR, addresses, tx details

No behaviour change, no XAML change, 127/127 tests pass.
2026-06-13 21:15:07 +02:00
18 changed files with 2058 additions and 1208 deletions
+1 -1
View File
@@ -40,7 +40,7 @@ by `MainWindow` on desktop and as the single-view root on Android.
`export PATH="$HOME/.dotnet10:$PATH" DOTNET_ROOT="$HOME/.dotnet10"`. `export PATH="$HOME/.dotnet10:$PATH" DOTNET_ROOT="$HOME/.dotnet10"`.
- Build: `dotnet build` - Build: `dotnet build`
- Tests (headless, the primary verification layer): `dotnet test` — single: `dotnet test --filter "FullyQualifiedName~TestName"` - Tests (headless, the primary verification layer): `dotnet test` — single: `dotnet test --filter "FullyQualifiedName~TestName"`; property-based tests (CsCheck, `PropertyTests.cs`) run in the same command and take ~30 s
- GUI hot reload: `dotnet watch --project src/App.Desktop` (on WSL2/WSLg the window shows on the Windows desktop, no graphics dependencies to install) - GUI hot reload: `dotnet watch --project src/App.Desktop` (on WSL2/WSLg the window shows on the Windows desktop, no graphics dependencies to install)
- CLI: `dotnet run --project src/Cli -- <command>` (no args → usage) - CLI: `dotnet run --project src/Cli -- <command>` (no args → usage)
- Windows publish: `dotnet publish src/App.Desktop -r win-x64 -p:PublishSingleFile=true --self-contained` - Windows publish: `dotnet publish src/App.Desktop -r win-x64 -p:PublishSingleFile=true --self-contained`
+2
View File
@@ -141,6 +141,8 @@ dotnet test tests/PalladiumWallet.Tests
> Cross-implementation tests compare addresses, txids and PSBTs against reference golden vectors: a different address or txid is a blocking bug. > Cross-implementation tests compare addresses, txids and PSBTs against reference golden vectors: a different address or txid is a blocking bug.
The suite includes **property-based tests** ([CsCheck](https://github.com/AnthonyLloyd/CsCheck)) in `tests/PalladiumWallet.Tests/PropertyTests.cs`. These generate hundreds of random inputs per test and verify invariants that must hold universally — no crash on arbitrary strings, encrypt/decrypt roundtrip for any plaintext and password, every leaf in a randomly-built Merkle tree verifies against its root. They run automatically with `dotnet test` and take ~30 s.
--- ---
## Building ## Building
+83
View File
@@ -0,0 +1,83 @@
# Security
## Threat model
Palladium Wallet is a self-custody SPV wallet. It is designed to protect funds against:
- Theft of the wallet file at rest (AES-256-GCM encryption with PBKDF2-HMAC-SHA512)
- Memory snooping of private keys after unlock (keys are held only in process memory, never written to disk in plaintext unless the user explicitly disables encryption)
- Fraudulent transaction injection by a malicious server (every confirmed transaction is verified with a Merkle proof against SPV-validated block headers anchored to hardcoded checkpoints)
It does **not** protect against:
- A fully compromised operating system or process (malware with memory access can extract keys from RAM)
- An attacker who obtains the wallet file **and** the password
- Denial of service or eclipse attacks against the indexing server
- Network-level traffic analysis (no Tor/proxy support in the first release)
---
## SPV trust model
This wallet is an SPV client, not a full node. It validates:
- Block headers (proof of work checked up to the last checkpoint; `SkipPowValidation` is enabled because LWMA difficulty cannot be recomputed client-side — trust is anchored to hardcoded checkpoints in `Core/Chain/ChainProfiles.cs`)
- Transaction inclusion in a confirmed block (Merkle branch proof, mandatory for every confirmed transaction — see `Core/Spv/MerkleVerifier.cs`)
It does **not** validate:
- Script execution (P2WPKH scripts are assumed valid if the server returns a confirmed transaction with a valid Merkle proof)
- Double-spend detection beyond what the server reports (an eclipse attack on the indexing server could hide a conflicting transaction)
- Full block validity (coinbase, consensus rules beyond the header)
The indexing server (ElectrumX-compatible, port 50001/50002) is a **semi-trusted** component. It can:
- Lie about unconfirmed (mempool) transactions — the wallet shows mempool transactions as unconfirmed and non-spendable
- Refuse to relay a broadcast transaction
- Delay reporting of new blocks
It cannot (given correct Merkle verification):
- Fabricate a confirmed transaction with a valid Merkle proof
- Forge a payment to a wrong address
---
## Key and seed management
- The BIP39 mnemonic and derived private keys exist only in process memory after unlock
- Private keys are never written to disk, logged, or sent over the network
- The wallet file stores the encrypted seed (with password) or the encrypted/plaintext `WalletDocument` — the document contains the account xpub and sync cache, not the raw seed when watch-only
- Watch-only wallets (`restore-xpub`) hold no private keys and cannot sign transactions
---
## Encryption at rest
- Algorithm: AES-256-GCM
- Key derivation: PBKDF2-HMAC-SHA512, 100 000 iterations, 32-byte random salt
- Authentication: GCM tag (16 bytes) — any tampering is detected before decryption
- The user can explicitly opt out of encryption (UI shows a warning); the `WalletStore.Save` API accepts `null` password only when the caller has confirmed user intent
---
## TLS certificate pinning
Connections to the indexing server use TOFU (Trust On First Use): the server's TLS certificate is pinned on first connection and stored in `server-certs.json`. A certificate change triggers a hard error (`CertificatePinMismatchException`) requiring explicit reset by the user. This prevents silent MITM substitution after first connection.
---
## Backup
The wallet file is the only thing that needs to be backed up. For encrypted wallets, the password is also required. If both the file and the password are lost, funds are unrecoverable (no server-side backup). For watch-only wallets restored from xpub, the private keys must be kept in a separate cold storage device.
---
## Known limitations and out-of-scope for v1
- No Tor/proxy support (network traffic reveals which addresses are being queried)
- No multi-server pooling (single point of failure for the indexing server)
- No hardware wallet integration
- No coin control (automatic UTXO selection only)
- No RBF/CPFP UI (RBF flag is set on all transactions, but fee bumping is not exposed)
- No Lightning Network support
@@ -0,0 +1,70 @@
using System.Collections.ObjectModel;
using System.Linq;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using PalladiumWallet.Core.Storage;
namespace PalladiumWallet.App.ViewModels;
public partial class MainWindowViewModel
{
public ObservableCollection<ContactEntry> Contacts { get; } = [];
[ObservableProperty]
private ContactEntry? selectedContactInList;
/// <summary>Contatto selezionato nella ComboBox del pannello Invia: riempie SendTo.</summary>
[ObservableProperty]
private ContactEntry? sendToContact;
partial void OnSendToContactChanged(ContactEntry? value)
{
if (value is not null)
SendTo = value.Address;
}
[ObservableProperty]
private string newContactName = "";
[ObservableProperty]
private string newContactAddress = "";
[RelayCommand]
private void AddContact()
{
var name = NewContactName.Trim();
var addr = NewContactAddress.Trim();
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(addr)) return;
Contacts.Add(new ContactEntry(name, addr));
NewContactName = NewContactAddress = "";
PersistContacts();
}
[RelayCommand]
private void RemoveSelectedContact()
{
if (SelectedContactInList is { } c)
{
Contacts.Remove(c);
SelectedContactInList = null;
PersistContacts();
}
}
private void PersistContacts()
{
if (_doc is null || _walletPath is null) return;
_doc.Contacts = Contacts
.Select(c => new StoredContact { Name = c.Name, Address = c.Address })
.ToList();
WalletStore.Save(_doc, _walletPath, _password);
}
private void LoadContacts()
{
Contacts.Clear();
if (_doc is null) return;
foreach (var c in _doc.Contacts)
Contacts.Add(new ContactEntry(c.Name, c.Address));
}
}
@@ -0,0 +1,221 @@
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Media.Imaging;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using PalladiumWallet.App.Localization;
using PalladiumWallet.Core.Chain;
using PalladiumWallet.Core.Spv;
using PalladiumWallet.Core.Storage;
using PalladiumWallet.Core.Wallet;
using QRCoder;
namespace PalladiumWallet.App.ViewModels;
public partial class MainWindowViewModel
{
// ---- saldo e info wallet ----
[ObservableProperty]
private string balanceText = "—";
[ObservableProperty]
private string unconfirmedText = "";
[ObservableProperty]
private string networkInfo = "";
// ---- indirizzo di ricezione e QR ----
[ObservableProperty]
private string receiveAddress = "";
[ObservableProperty]
private Bitmap? receiveQr;
partial void OnReceiveAddressChanged(string value)
{
var previous = ReceiveQr;
ReceiveQr = string.IsNullOrEmpty(value) ? null : GenerateQr(value);
previous?.Dispose();
}
public void NotifyAddressCopied() => StatusMessage = Loc.Tr("addr.copied");
private static Bitmap? GenerateQr(string text)
{
try
{
using var generator = new QRCodeGenerator();
using var data = generator.CreateQrCode(text, QRCodeGenerator.ECCLevel.M);
var png = new PngByteQRCode(data).GetGraphic(8);
return new Bitmap(new MemoryStream(png));
}
catch
{
return null;
}
}
// ---- tab indirizzi ----
[ObservableProperty]
private AddressRow? selectedAddressRow;
[ObservableProperty]
private AddressInfo? addressInfo;
public void ShowAddressInfo(AddressRow row) =>
AddressInfo = new AddressInfo(Loc, row.Indirizzo, row.DerivPath, row.PubKey, row.PrivKey);
[RelayCommand]
private void CloseAddressInfo() => AddressInfo = null;
// ---- overlay dettaglio transazione ----
[ObservableProperty]
private bool isTxDetailsOpen;
[ObservableProperty]
private bool isTxDetailsLoading;
[ObservableProperty]
private TransactionDetailsViewModel? txDetails;
public async Task ShowTransactionDetailsAsync(string txid)
{
if (_client is null || !_client.IsConnected)
{
StatusMessage = Loc.Tr("tx.needconnection");
return;
}
_txDetailsCts?.Cancel();
_txDetailsCts = new CancellationTokenSource();
var ct = _txDetailsCts.Token;
TxDetails = null;
IsTxDetailsLoading = true;
IsTxDetailsOpen = true;
var details = await BuildTransactionDetailsAsync(txid, ct);
if (ct.IsCancellationRequested || !IsTxDetailsOpen)
return;
if (details is null)
{
IsTxDetailsOpen = false;
IsTxDetailsLoading = false;
return;
}
TxDetails = details;
IsTxDetailsLoading = false;
}
[RelayCommand]
private void CloseTransactionDetails()
{
_txDetailsCts?.Cancel();
IsTxDetailsOpen = false;
IsTxDetailsLoading = false;
TxDetails = null;
}
public async Task<TransactionDetailsViewModel?> BuildTransactionDetailsAsync(
string txid, CancellationToken ct = default)
{
if (_client is null || !_client.IsConnected)
{
StatusMessage = Loc.Tr("tx.needconnection");
return null;
}
if (_doc?.Cache is not { } cache)
return null;
var client = _client;
var network = PalladiumNetworks.For(Net);
var row = cache.History.FirstOrDefault(t => t.Txid == txid);
var owned = cache.Addresses.Select(a => a.Address).ToHashSet();
var tipHeight = cache.TipHeight;
var height = row?.Height ?? 0;
var delta = row?.DeltaSats ?? 0;
var verified = row?.Verified ?? false;
var transactions = _lastTransactions;
var loc = _loc;
var unit = _config.Unit;
try
{
return await Task.Run(async () =>
{
var details = await TransactionInspector.FetchAsync(
client, network, txid, tipHeight, height, owned, delta, verified, transactions, ct);
return new TransactionDetailsViewModel(details, loc, unit);
}, ct);
}
catch (OperationCanceledException)
{
return null;
}
catch (Exception ex)
{
StatusMessage = $"{Loc.Tr("msg.error")}: {ex.Message}";
return null;
}
}
// ---- aggiorna display dal risultato della sync ----
private void ApplyCache(SyncCache? cache)
{
if (_account is null)
return;
if (cache is null)
{
BalanceText = $"0.00000000 {Profile.CoinUnit}";
UnconfirmedText = "";
ReceiveAddress = _account.GetReceiveAddress(0).ToString();
History.Clear();
Addresses.Clear();
for (var i = 0; i < 10; i++)
Addresses.Add(new AddressRow(_loc["addr.receive"], i,
_account.GetReceiveAddress(i).ToString(), "—", "—",
false,
_account.GetPublicKey(false, i).ToHex(),
KeyWif(false, i),
$"m/{_doc!.AccountPath}/0/{i}"));
return;
}
BalanceText = Fmt(cache.ConfirmedSats);
var pending = cache.History.Where(t => t.Height <= 0).Sum(t => t.DeltaSats);
UnconfirmedText = pending != 0
? $"{Loc.Tr("msg.pending")}: {(pending > 0 ? "+" : "")}{Fmt(pending)} — {Loc.Tr("msg.notspendable")}"
: "";
ReceiveAddress = _account.GetReceiveAddress(cache.NextReceiveIndex).ToString();
History.Clear();
foreach (var tx in cache.History)
History.Add(new HistoryRow(
tx.Height > 0 ? tx.Height.ToString() : "mempool",
(tx.DeltaSats >= 0 ? "+" : "") + Fmt(tx.DeltaSats, withLabel: false),
tx.Txid,
tx.Verified ? "✓ SPV" : "—"));
Addresses.Clear();
foreach (var a in cache.Addresses)
Addresses.Add(new AddressRow(
a.IsChange ? _loc["addr.change"] : _loc["addr.receive"],
a.Index,
a.Address,
a.BalanceSats > 0 ? Fmt(a.BalanceSats, withLabel: false) : (a.TxCount > 0 ? "0" : "—"),
a.TxCount > 0 ? a.TxCount.ToString() : "—",
a.IsChange,
_account.GetPublicKey(a.IsChange, a.Index).ToHex(),
KeyWif(a.IsChange, a.Index),
$"m/{_doc!.AccountPath}/{(a.IsChange ? 1 : 0)}/{a.Index}"));
}
}
@@ -0,0 +1,99 @@
using System;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using NBitcoin;
using PalladiumWallet.Core.Chain;
using PalladiumWallet.Core.Net;
using PalladiumWallet.Core.Wallet;
namespace PalladiumWallet.App.ViewModels;
public partial class MainWindowViewModel
{
[ObservableProperty]
private string sendTo = "";
[ObservableProperty]
private string sendAmount = "";
[ObservableProperty]
private string sendFeeRate = "1";
[ObservableProperty]
private bool sendAll;
[ObservableProperty]
private string sendPreview = "";
[ObservableProperty]
private bool hasPendingSend;
[RelayCommand]
private async Task PrepareSend()
{
if (_account is null || _doc?.Cache is null)
{
SendPreview = "Sincronizza prima di inviare.";
return;
}
try
{
if (_lastTransactions is null)
{
SendPreview = "Connettiti al server e sincronizza prima di inviare.";
return;
}
var destination = BitcoinAddress.Create(SendTo.Trim(), PalladiumNetworks.For(Net));
long amount = 0;
if (!SendAll && !CoinAmount.TryParseIn(SendAmount, _config.Unit, out amount))
{
SendPreview = "Importo non valido.";
return;
}
if (!decimal.TryParse(SendFeeRate, out var feeRate) || feeRate <= 0)
{
SendPreview = "Fee rate non valido.";
return;
}
_pendingSend = new TransactionFactory(_account).Build(
_doc.Cache.Utxos, _lastTransactions, destination, amount, feeRate,
_doc.Cache.NextChangeIndex, SendAll);
SendPreview = $"txid {_pendingSend.Txid[..16]}… · " +
$"fee {Fmt(_pendingSend.Fee.Satoshi)} " +
$"({_pendingSend.Transaction.GetVirtualSize()} vB)" +
(_pendingSend.Signed ? "" : " · NON firmata (watch-only)");
HasPendingSend = _pendingSend.Signed;
}
catch (Exception ex)
{
_pendingSend = null;
HasPendingSend = false;
SendPreview = $"Errore: {ex.Message}";
}
await Task.CompletedTask;
}
[RelayCommand]
private async Task ConfirmSend()
{
if (_pendingSend is null || _client is null)
return;
try
{
var txid = await _client.BroadcastAsync(_pendingSend.ToHex());
SendPreview = $"Trasmessa: {txid}";
SendTo = SendAmount = "";
_pendingSend = null;
HasPendingSend = false;
await ConnectAndSync();
}
catch (Exception ex)
{
SendPreview = $"Errore broadcast: {ex.Message}";
}
}
}
@@ -0,0 +1,74 @@
using CommunityToolkit.Mvvm.Input;
namespace PalladiumWallet.App.ViewModels;
public partial class MainWindowViewModel
{
// ---- spunte del menu Impostazioni (ToggleType Radio) ----
public bool IsLangIt => _config.Language == "it";
public bool IsLangEn => _config.Language == "en";
public bool IsLangEs => _config.Language == "es";
public bool IsLangFr => _config.Language == "fr";
public bool IsLangPt => _config.Language == "pt";
public bool IsLangDe => _config.Language == "de";
public bool IsUnitPlm => _config.Unit == "PLM";
public bool IsUnitMilli => _config.Unit == "mPLM";
public bool IsUnitMicro => _config.Unit == "µPLM";
public bool IsUnitSat => _config.Unit == "sat";
[RelayCommand]
private void SetLanguage(string language)
{
_config.Language = language;
ApplySettings(_config);
}
[RelayCommand]
private void SetUnit(string unit)
{
_config.Unit = unit;
ApplySettings(_config);
}
public void ApplySettings(PalladiumWallet.Core.Storage.AppConfig config)
{
_config = config;
_config.Save();
_loc = Localization.Loc.SwitchTo(config.Language);
OnPropertyChanged(nameof(Loc));
OnPropertyChanged(nameof(UnitLabel));
OnPropertyChanged(nameof(IsLangIt));
OnPropertyChanged(nameof(IsLangEn));
OnPropertyChanged(nameof(IsLangEs));
OnPropertyChanged(nameof(IsLangFr));
OnPropertyChanged(nameof(IsLangPt));
OnPropertyChanged(nameof(IsLangDe));
OnPropertyChanged(nameof(IsUnitPlm));
OnPropertyChanged(nameof(IsUnitMilli));
OnPropertyChanged(nameof(IsUnitMicro));
OnPropertyChanged(nameof(IsUnitSat));
ApplyCache(_doc?.Cache);
StatusMessage = Localization.Loc.Tr("msg.settings.saved");
}
// ---- overlay impostazioni, server, help ----
[CommunityToolkit.Mvvm.ComponentModel.ObservableProperty]
private bool isSettingsOpen;
[RelayCommand]
private void OpenSettings() => IsSettingsOpen = true;
[RelayCommand]
private void CloseSettings() => IsSettingsOpen = false;
[CommunityToolkit.Mvvm.ComponentModel.ObservableProperty]
private bool isHelpOpen;
[RelayCommand]
private void OpenHelp() => IsHelpOpen = true;
[RelayCommand]
private void CloseHelp() => IsHelpOpen = false;
}
@@ -0,0 +1,258 @@
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using PalladiumWallet.App.Localization;
using PalladiumWallet.Core.Net;
using PalladiumWallet.Core.Spv;
using PalladiumWallet.Core.Storage;
namespace PalladiumWallet.App.ViewModels;
public partial class MainWindowViewModel
{
// ---- server e connessione ----
[ObservableProperty]
private string serverHost = "";
[ObservableProperty]
private string serverPort = "";
[ObservableProperty]
private bool useSsl = true;
[ObservableProperty]
private bool isServerSettingsOpen;
[RelayCommand]
private void OpenServerSettings()
{
IsSettingsOpen = false;
IsServerSettingsOpen = true;
}
[RelayCommand]
private void CloseServerSettings() => IsServerSettingsOpen = false;
[ObservableProperty]
private string connectionStatus = Loc.Tr("conn.none");
[ObservableProperty]
private bool isConnected;
[ObservableProperty]
private bool isSyncing;
public ObservableCollection<KnownServer> KnownServers { get; } = [];
[ObservableProperty]
private KnownServer? selectedKnownServer;
partial void OnSelectedKnownServerChanged(KnownServer? value)
{
if (value is null)
return;
_syncingServerFields = true;
ServerHost = value.Host;
ServerPort = value.PortFor(UseSsl).ToString();
_syncingServerFields = false;
}
partial void OnUseSslChanged(bool value)
{
if (_syncingServerFields)
return;
_syncingServerFields = true;
ServerPort = SelectedKnownServer is { } server
? server.PortFor(value).ToString()
: (value ? Profile.DefaultSslPort : Profile.DefaultTcpPort).ToString();
_syncingServerFields = false;
}
partial void OnServerPortChanged(string value)
{
if (_syncingServerFields)
return;
if (!int.TryParse(value.Trim(), out var port))
return;
bool? wantSsl =
SelectedKnownServer is { } s && port == s.SslPort ? true :
SelectedKnownServer is { } t && port == t.TcpPort ? false :
port == Profile.DefaultSslPort ? true :
port == Profile.DefaultTcpPort ? false :
null;
if (wantSsl is bool b && b != UseSsl)
{
_syncingServerFields = true;
UseSsl = b;
_syncingServerFields = false;
}
}
private void RefreshServers()
{
KnownServers.Clear();
foreach (var server in Registry.All)
KnownServers.Add(server);
SelectedKnownServer = KnownServers.FirstOrDefault();
if (SelectedKnownServer is null)
{
ServerHost = "127.0.0.1";
ServerPort = (UseSsl ? Profile.DefaultSslPort : Profile.DefaultTcpPort).ToString();
}
}
private (string Host, int Port) ParseServer()
{
var host = ServerHost.Trim();
var port = int.TryParse(ServerPort.Trim(), out var p)
? p
: UseSsl ? Profile.DefaultSslPort : Profile.DefaultTcpPort;
return (host, port);
}
[RelayCommand]
private async Task ConnectAndSync()
{
if (IsSyncing)
{
_resyncRequested = true;
return;
}
IsSyncing = true;
StatusMessage = "";
try
{
var (host, port) = ParseServer();
if (_client is { } current &&
(current.Host != host || current.Port != port || current.UseSsl != UseSsl))
{
await DisconnectAsync();
}
if (_client is null || !_client.IsConnected)
{
ConnectionStatus = $"{Loc.Tr("conn.connectingto")} {host}:{port}…";
var pins = new CertificatePinStore(AppPaths.CertificatePinsPath(Net));
_client = await ElectrumClient.ConnectAsync(host, port, UseSsl, pins);
_client.NotificationReceived += OnServerNotification;
_client.Disconnected += _ => Dispatcher.UIThread.Post(() =>
{
IsConnected = false;
ConnectionStatus = Loc.Tr("conn.disconnected");
});
IsConnected = true;
_autoReconnect = true;
ConnectionStatus = $"{Loc.Tr("conn.connectedto")} {host}:{port}{(UseSsl ? " (TLS)" : "")}";
}
if (_account is null || _doc is null)
return;
if (_synchronizer is null)
{
_synchronizer = new WalletSynchronizer(_account, _client, _doc.GapLimit);
_synchronizer.Progress += msg => Dispatcher.UIThread.Post(() => StatusMessage = msg);
}
do
{
_resyncRequested = false;
var result = await _synchronizer.SyncOnceAsync();
_lastTransactions = result.Transactions;
_doc.Cache = new SyncCache
{
TipHeight = result.TipHeight,
ConfirmedSats = result.ConfirmedSats,
UnconfirmedSats = result.UnconfirmedSats,
NextReceiveIndex = result.NextReceiveIndex,
NextChangeIndex = result.NextChangeIndex,
History = [.. result.History],
Utxos = [.. result.Utxos],
Addresses = [.. result.AddressRows],
};
WalletStore.Save(_doc, _walletPath!, _password);
ApplyCache(_doc.Cache);
StatusMessage = $"{Loc.Tr("msg.synced")}: {Loc.Tr("msg.height")} {result.TipHeight}, " +
$"{result.History.Count} {Loc.Tr("msg.synced.detail")}";
} while (_resyncRequested);
}
catch (CertificatePinMismatchException ex)
{
IsConnected = false;
ConnectionStatus = Loc.Tr("conn.certchanged");
StatusMessage = ex.Message;
}
catch (Exception ex)
{
IsConnected = _client?.IsConnected == true;
ConnectionStatus = IsConnected ? ConnectionStatus : Loc.Tr("conn.error");
StatusMessage = $"Errore: {ex.Message}";
}
finally
{
IsSyncing = false;
}
}
[RelayCommand]
private async Task DiscoverServers()
{
if (_client is null || !_client.IsConnected)
{
StatusMessage = Loc.Tr("conn.none") + ".";
return;
}
try
{
var added = await Registry.DiscoverAsync(_client);
var selected = SelectedKnownServer;
RefreshServers();
SelectedKnownServer = KnownServers.FirstOrDefault(s => s.Host == selected?.Host)
?? KnownServers.FirstOrDefault();
StatusMessage = added > 0
? $"Trovati {added} nuovi server dai peer (totale {KnownServers.Count})."
: $"Nessun nuovo server annunciato (totale {KnownServers.Count}).";
}
catch (Exception ex)
{
StatusMessage = $"Errore nella scoperta peer: {ex.Message}";
}
}
private void OnServerNotification(string method, System.Text.Json.JsonElement payload)
{
if (method is "blockchain.scripthash.subscribe" or "blockchain.headers.subscribe")
Dispatcher.UIThread.Post(() =>
{
if (IsSyncing)
_resyncRequested = true;
else
_ = ConnectAndSync();
});
}
[RelayCommand]
private void ResetCertificates()
{
new CertificatePinStore(AppPaths.CertificatePinsPath(Net)).ResetAll();
StatusMessage = Loc.Tr("msg.certreset");
}
private async Task DisconnectAsync()
{
if (_client is { } client)
{
_client = null;
_synchronizer = null;
try { await client.DisposeAsync(); } catch { }
}
IsConnected = false;
}
}
@@ -0,0 +1,360 @@
using System;
using System.Collections.ObjectModel;
using System.IO;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using PalladiumWallet.App.Localization;
using PalladiumWallet.Core.Chain;
using PalladiumWallet.Core.Crypto;
using PalladiumWallet.Core.Storage;
using PalladiumWallet.Core.Wallet;
namespace PalladiumWallet.App.ViewModels;
public partial class MainWindowViewModel
{
// ---- wizard di setup
public const string StepDataLocation = "data-location";
public const string StepStart = "start";
public const string StepChooseWallet = "choose-wallet";
public const string StepOpen = "open";
public const string StepShowSeed = "show-seed";
public const string StepConfirmSeed = "confirm-seed";
public const string StepWords = "words";
public const string StepPassphrase = "passphrase";
public const string StepPassword = "password";
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsStepDataLocation))]
[NotifyPropertyChangedFor(nameof(IsStepStart))]
[NotifyPropertyChangedFor(nameof(IsStepChooseWallet))]
[NotifyPropertyChangedFor(nameof(IsStepOpen))]
[NotifyPropertyChangedFor(nameof(IsStepShowSeed))]
[NotifyPropertyChangedFor(nameof(IsStepConfirmSeed))]
[NotifyPropertyChangedFor(nameof(IsStepWords))]
[NotifyPropertyChangedFor(nameof(IsStepPassphrase))]
[NotifyPropertyChangedFor(nameof(IsStepPassword))]
private string setupStep = StepStart;
public bool IsStepDataLocation => SetupStep == StepDataLocation;
public bool IsStepStart => SetupStep == StepStart;
public bool IsStepChooseWallet => SetupStep == StepChooseWallet;
public bool IsStepOpen => SetupStep == StepOpen;
public bool IsStepShowSeed => SetupStep == StepShowSeed;
public bool IsStepConfirmSeed => SetupStep == StepConfirmSeed;
public bool IsStepWords => SetupStep == StepWords;
public bool IsStepPassphrase => SetupStep == StepPassphrase;
public bool IsStepPassword => SetupStep == StepPassword;
public string DefaultDataPath => AppPaths.DefaultDataRoot();
[ObservableProperty]
private string mnemonicInput = "";
[ObservableProperty]
private string confirmMnemonicInput = "";
[ObservableProperty]
private string passphraseInput = "";
[ObservableProperty]
private string passwordInput = "";
[ObservableProperty]
private string confirmPasswordInput = "";
[ObservableProperty]
private bool encryptWallet = true;
[ObservableProperty]
private bool walletFileExists;
public ObservableCollection<WalletFileEntry> WalletList { get; } = [];
[RelayCommand]
private void UseDefaultDataLocation() => ApplyDataLocation(AppPaths.DefaultDataRoot());
public void ApplyDataLocation(string root)
{
try
{
AppPaths.ConfigureDataLocation(root);
}
catch (Exception ex)
{
StatusMessage = $"{Loc.Tr("msg.error")}: {ex.Message}";
return;
}
_config = AppConfig.Load();
_loc = Loc.SwitchTo(_config.Language);
OnPropertyChanged(nameof(Loc));
OnPropertyChanged(nameof(UnitLabel));
RefreshSetupState();
}
private void RefreshSetupState()
{
SetupStep = StepStart;
MnemonicInput = ConfirmMnemonicInput = PassphraseInput = PasswordInput = ConfirmPasswordInput = "";
WalletFileExists = AppPaths.WalletFiles(Net).Count > 0;
StatusMessage = "";
RefreshServers();
_ = ConnectAndSync();
}
[RelayCommand]
private void WizardStartOpen()
{
var files = AppPaths.WalletFiles(Net);
if (files.Count > 1)
{
WalletList.Clear();
foreach (var path in files)
WalletList.Add(new WalletFileEntry(Path.GetFileName(path), path));
SetupStep = StepChooseWallet;
StatusMessage = "";
return;
}
_pendingOpenPath = files.Count == 1 ? files[0] : AppPaths.DefaultWalletPath(Net);
PasswordInput = "";
SetupStep = StepOpen;
StatusMessage = "";
}
[RelayCommand]
private void ChooseWallet(WalletFileEntry? entry)
{
if (entry is null)
return;
_pendingOpenPath = entry.Path;
PasswordInput = "";
SetupStep = StepOpen;
StatusMessage = "";
}
[RelayCommand]
private void WizardStartNew()
{
_isRestoreFlow = false;
MnemonicInput = Bip39.Generate(MnemonicLength.Twelve).ToString();
SetupStep = StepShowSeed;
StatusMessage = "";
}
[RelayCommand]
private void WizardStartRestore()
{
_isRestoreFlow = true;
MnemonicInput = "";
SetupStep = StepWords;
StatusMessage = "";
}
[RelayCommand]
private void WizardNextFromShowSeed()
{
ConfirmMnemonicInput = "";
SetupStep = StepConfirmSeed;
StatusMessage = "";
}
[RelayCommand]
private void WizardNextFromConfirmSeed()
{
var normalized = string.Join(' ',
ConfirmMnemonicInput.Split(' ', StringSplitOptions.RemoveEmptyEntries));
if (!string.Equals(normalized, MnemonicInput, StringComparison.OrdinalIgnoreCase))
{
StatusMessage = Loc.Tr("msg.seed.mismatch");
return;
}
GoToPassphraseStep();
}
[RelayCommand]
private void WizardNextFromWords()
{
if (!Bip39.TryParse(MnemonicInput, out _))
{
StatusMessage = Loc.Tr("msg.words.invalid");
return;
}
GoToPassphraseStep();
}
private void GoToPassphraseStep()
{
PassphraseInput = "";
SetupStep = StepPassphrase;
StatusMessage = "";
}
[RelayCommand]
private void WizardNextFromPassphrase()
{
PasswordInput = ConfirmPasswordInput = "";
EncryptWallet = true;
SetupStep = StepPassword;
StatusMessage = "";
}
[RelayCommand]
private void WizardBack()
{
SetupStep = SetupStep switch
{
StepOpen => WalletList.Count > 1 ? StepChooseWallet : StepStart,
StepChooseWallet or StepShowSeed or StepWords => StepStart,
StepConfirmSeed => StepShowSeed,
StepPassphrase => _isRestoreFlow ? StepWords : StepConfirmSeed,
StepPassword => StepPassphrase,
_ => StepStart,
};
if (SetupStep == StepStart)
RefreshSetupState();
}
[RelayCommand]
private void CreateOrRestore()
{
string? password;
if (EncryptWallet)
{
if (string.IsNullOrEmpty(PasswordInput))
{
StatusMessage = Loc.Tr("msg.password.required");
return;
}
if (PasswordInput != ConfirmPasswordInput)
{
StatusMessage = Loc.Tr("msg.password.mismatch");
return;
}
password = PasswordInput;
}
else
{
password = null;
}
try
{
var (doc, account) = WalletLoader.NewFromMnemonic(
MnemonicInput,
string.IsNullOrEmpty(PassphraseInput) ? null : PassphraseInput,
ScriptKind.NativeSegwit,
Profile);
var path = AppPaths.DefaultWalletPath(Net);
for (var n = 2; WalletStore.Exists(path); n++)
path = Path.Combine(AppPaths.WalletsDir(Net), $"wallet-{n}.wallet.json");
WalletStore.Save(doc, path, password);
var newLock = WalletLock.TryAcquire(path);
if (newLock is null) { StatusMessage = Loc.Tr("msg.wallet.locked"); return; }
OpenLoaded(doc, account, path, password, newLock);
}
catch (Exception ex)
{
StatusMessage = $"Errore: {ex.Message}";
}
}
[RelayCommand]
private void OpenExisting()
{
var path = _pendingOpenPath ?? AppPaths.DefaultWalletPath(Net);
var password = string.IsNullOrEmpty(PasswordInput) ? null : PasswordInput;
var newLock = WalletLock.TryAcquire(path);
if (newLock is null) { StatusMessage = Loc.Tr("msg.wallet.locked"); return; }
try
{
var doc = WalletStore.Load(path, password);
_pendingOpenPath = null;
OpenLoaded(doc, WalletLoader.ToAccount(doc), path, password, newLock);
}
catch (WrongPasswordException)
{
newLock.Dispose();
StatusMessage = Loc.Tr("msg.wrongpassword");
}
catch (UnauthorizedAccessException)
{
newLock.Dispose();
StatusMessage = Loc.Tr("msg.wallet.noaccess");
}
catch (Exception ex)
{
newLock.Dispose();
StatusMessage = $"Errore: {ex.Message}";
}
}
public void OpenFromPath(string path)
{
var newLock = WalletLock.TryAcquire(path);
if (newLock is null) { StatusMessage = Loc.Tr("msg.wallet.locked"); return; }
try
{
var doc = WalletStore.Load(path);
if (IsWalletOpen)
CloseWallet();
OpenLoaded(doc, WalletLoader.ToAccount(doc), path, password: null, newLock);
}
catch (WrongPasswordException)
{
newLock.Dispose();
if (IsWalletOpen)
CloseWallet();
_pendingOpenPath = path;
WalletFileExists = true;
PasswordInput = "";
SetupStep = StepOpen;
StatusMessage = "";
}
catch (UnauthorizedAccessException)
{
newLock.Dispose();
StatusMessage = Loc.Tr("msg.wallet.noaccess");
}
catch (Exception ex)
{
newLock.Dispose();
StatusMessage = $"Errore: {ex.Message}";
}
}
[RelayCommand]
private void NewWallet()
{
if (IsWalletOpen)
CloseWallet();
_pendingOpenPath = null;
StatusMessage = "";
}
private void OpenLoaded(
WalletDocument doc, HdAccount account, string path, string? password, WalletLock walletLock)
{
_walletLock?.Dispose();
_walletLock = walletLock;
SelectedNetwork = doc.Network;
_doc = doc;
_account = account;
_walletPath = path;
_password = password;
MnemonicInput = ConfirmMnemonicInput = PassphraseInput = PasswordInput = ConfirmPasswordInput = "";
SetupStep = StepStart;
NetworkInfo = $"{doc.Network} · {doc.ScriptKind} · m/{doc.AccountPath}"
+ (doc.IsWatchOnly ? " · watch-only" : "");
LoadContacts();
ApplyCache(doc.Cache);
IsWalletOpen = true;
StatusMessage = Loc.Tr("msg.opened");
_ = ConnectAndSync();
}
}
File diff suppressed because it is too large Load Diff
+2
View File
@@ -25,6 +25,8 @@ public static class WalletStore
return WalletDocument.FromJson(content); return WalletDocument.FromJson(content);
} }
/// <param name="password">Null saves in plaintext. Only omit when the user has
/// explicitly opted out of encryption (UI must show a clear warning).</param>
public static void Save(WalletDocument doc, string path, string? password = null) public static void Save(WalletDocument doc, string path, string? password = null)
{ {
var content = doc.ToJson(); var content = doc.ToJson();
@@ -69,6 +69,42 @@ public class ChainProfileTests
Assert.StartsWith("tpub", EncodeWithHeader(headers.Public)); Assert.StartsWith("tpub", EncodeWithHeader(headers.Public));
} }
[Fact]
public void Rete_sconosciuta_lancia_ArgumentException()
{
Assert.ThrowsAny<ArgumentException>(() => ChainProfiles.For((NetKind)99));
}
[Fact]
public void I_tre_profili_sono_istanze_distinte()
{
Assert.NotSame(ChainProfiles.Mainnet, ChainProfiles.Testnet);
Assert.NotSame(ChainProfiles.Mainnet, ChainProfiles.Regtest);
Assert.NotSame(ChainProfiles.Testnet, ChainProfiles.Regtest);
}
[Fact]
public void Tutti_i_profili_hanno_gli_stessi_porti_tcp_ssl()
{
foreach (var profile in new[] { ChainProfiles.Mainnet, ChainProfiles.Testnet, ChainProfiles.Regtest })
{
Assert.Equal(50001, profile.DefaultTcpPort);
Assert.Equal(50002, profile.DefaultSslPort);
}
}
[Fact]
public void Coin_type_mainnet_e_746()
{
Assert.Equal(746, ChainProfiles.Mainnet.Bip44CoinType);
}
[Fact]
public void Coin_type_testnet_e_1()
{
Assert.Equal(1, ChainProfiles.Testnet.Bip44CoinType);
}
// Serializza header (4 byte BE) + payload BIP32 di 74 byte e codifica Base58Check: // Serializza header (4 byte BE) + payload BIP32 di 74 byte e codifica Base58Check:
// il prefisso testuale risultante dipende solo dall'header. // il prefisso testuale risultante dipende solo dall'header.
private static string EncodeWithHeader(uint header) private static string EncodeWithHeader(uint header)
@@ -11,6 +11,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" /> <PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="CsCheck" Version="4.7.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.5.3" /> <PackageReference Include="xunit" Version="2.5.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
@@ -0,0 +1,205 @@
using System;
using System.Collections.Generic;
using CsCheck;
using NBitcoin;
using PalladiumWallet.Core.Spv;
using PalladiumWallet.Core.Storage;
using PalladiumWallet.Core.Wallet;
namespace PalladiumWallet.Tests;
/// <summary>
/// Property-based tests (CsCheck). Ogni test genera centinaia di input casuali e
/// verifica che le proprietà invarianti reggano — crash, eccezioni non attese, o
/// violazioni di roundtrip sono failures.
/// </summary>
public class PropertyTests
{
// ── generatori riutilizzabili ─────────────────────────────────────────────
private static readonly Gen<string> GenUnit = Gen.OneOf(
Gen.Const("PLM"), Gen.Const("mPLM"), Gen.Const("µPLM"), Gen.Const("sat"));
// uint256 casuale costruito da 4 ulong
private static readonly Gen<uint256> GenTxid =
Gen.Select(Gen.ULong, Gen.ULong, Gen.ULong, Gen.ULong, (a, b, c, d) =>
{
var bytes = new byte[32];
BitConverter.TryWriteBytes(bytes.AsSpan(0, 8), a);
BitConverter.TryWriteBytes(bytes.AsSpan(8, 8), b);
BitConverter.TryWriteBytes(bytes.AsSpan(16, 8), c);
BitConverter.TryWriteBytes(bytes.AsSpan(24, 8), d);
return new uint256(bytes);
});
// ── CoinAmount ──────────────────────────────────────────────────────────
/// TryParseIn non deve mai lanciare eccezioni su input arbitrario con unità valide.
[Fact]
public void CoinAmount_TryParseIn_non_lancia_mai_su_input_arbitrario()
{
Gen.Select(GenUnit, Gen.String).Sample((unit, text) =>
{
try
{
CoinAmount.TryParseIn(text, unit, out _);
}
catch (ArgumentException)
{
// unità sconosciuta: impossibile qui perché usiamo solo unità note
throw;
}
catch (Exception ex)
{
Assert.Fail($"TryParseIn ha lanciato {ex.GetType().Name} per unit={unit}");
}
});
}
/// FormatIn → TryParseIn: qualsiasi satoshi [0, MaxSupply] deve fare roundtrip esatto.
[Fact]
public void CoinAmount_roundtrip_FormatIn_TryParseIn_per_ogni_unita()
{
const long MaxSupply = 21_000_000L * 100_000_000L;
Gen.Select(Gen.Long[0, MaxSupply], GenUnit).Sample((sats, unit) =>
{
var formatted = CoinAmount.FormatIn(sats, unit, withLabel: false);
Assert.True(
CoinAmount.TryParseIn(formatted, unit, out var parsed),
$"FormatIn={formatted} unit={unit} non si riparsa");
Assert.Equal(sats, parsed);
});
}
/// TryParseCoins non deve mai lanciare su input arbitrario.
[Fact]
public void CoinAmount_TryParseCoins_non_lancia_mai_su_input_arbitrario()
{
Gen.String.Sample(text =>
{
try
{
CoinAmount.TryParseCoins(text, out _);
}
catch (Exception ex)
{
Assert.Fail($"TryParseCoins ha lanciato {ex.GetType().Name}");
}
});
}
/// Qualsiasi valore accettato da TryParseCoins deve essere ≥ 0.
[Fact]
public void CoinAmount_TryParseCoins_accetta_solo_valori_non_negativi()
{
Gen.String.Sample(text =>
{
if (CoinAmount.TryParseCoins(text, out var sats))
Assert.True(sats >= 0, $"TryParseCoins ha restituito {sats} per '{text}'");
});
}
// ── EncryptedFile ────────────────────────────────────────────────────────
/// Encrypt → Decrypt con la stessa password deve restituire il testo originale.
[Fact]
public void EncryptedFile_roundtrip_su_contenuto_e_password_arbitrari()
{
Gen.Select(Gen.String, Gen.String[1, 64]).Sample((plaintext, password) =>
{
var cipher = EncryptedFile.Encrypt(plaintext, password);
var recovered = EncryptedFile.Decrypt(cipher, password);
Assert.Equal(plaintext, recovered);
});
}
/// Decrypt con password sbagliata deve lanciare WrongPasswordException, mai altro.
[Fact]
public void EncryptedFile_password_sbagliata_lancia_solo_WrongPasswordException()
{
Gen.Select(Gen.String, Gen.String[1, 32], Gen.String[1, 32]).Sample((plaintext, pwd1, pwd2) =>
{
if (pwd1 == pwd2) return; // stessa password: roundtrip valido, salta
var cipher = EncryptedFile.Encrypt(plaintext, pwd1);
try
{
EncryptedFile.Decrypt(cipher, pwd2);
Assert.Fail("Decrypt con password sbagliata non ha lanciato");
}
catch (WrongPasswordException) { /* atteso */ }
catch (Exception ex)
{
Assert.Fail($"Decrypt ha lanciato {ex.GetType().Name} invece di WrongPasswordException");
}
});
}
/// IsEncrypted non deve mai lanciare su input arbitrario.
[Fact]
public void EncryptedFile_IsEncrypted_non_lancia_mai()
{
Gen.String.Sample(s =>
{
try { EncryptedFile.IsEncrypted(s); }
catch (Exception ex)
{
Assert.Fail($"IsEncrypted ha lanciato {ex.GetType().Name}");
}
});
}
// ── MerkleProof ──────────────────────────────────────────────────────────
/// Ogni foglia di un albero Merkle generato casualmente deve verificare contro la radice.
[Fact]
public void MerkleProof_ogni_foglia_verifica_contro_la_sua_radice()
{
GenTxid.Array[1, 16].Sample(txids =>
{
var root = MerkleProof.ComputeRootFromLeaves(txids);
for (var pos = 0; pos < txids.Length; pos++)
{
var branch = BuildBranch(txids, pos);
Assert.True(
MerkleProof.Verify(txids[pos], pos, branch, root),
$"Verify fallita per pos={pos} su {txids.Length} foglie");
}
});
}
/// Un txid non presente nelle foglie non deve verificare (e non deve crashare).
[Fact]
public void MerkleProof_txid_estraneo_non_verifica_e_non_crasha()
{
Gen.Select(GenTxid.Array[2, 8], GenTxid).Sample((txids, extra) =>
{
if (txids.Contains(extra)) return; // collisione casuale: salta
var root = MerkleProof.ComputeRootFromLeaves(txids);
var branch = BuildBranch(txids, 0);
Assert.False(MerkleProof.Verify(extra, 0, branch, root));
});
}
// helper: costruisce il branch per la posizione data
private static List<uint256> BuildBranch(IReadOnlyList<uint256> leaves, int position)
{
var branch = new List<uint256>();
var level = leaves.ToList();
while (level.Count > 1)
{
var sibling = (position ^ 1) < level.Count ? level[position ^ 1] : level[position];
branch.Add(sibling);
var next = new List<uint256>();
for (var i = 0; i < level.Count; i += 2)
{
var pair = new[] { level[i], i + 1 < level.Count ? level[i + 1] : level[i] };
next.Add(MerkleProof.ComputeRootFromLeaves(pair));
}
level = next;
position >>= 1;
}
return branch;
}
}
+120 -5
View File
@@ -1,3 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NBitcoin; using NBitcoin;
using PalladiumWallet.Core.Chain; using PalladiumWallet.Core.Chain;
using PalladiumWallet.Core.Spv; using PalladiumWallet.Core.Spv;
@@ -17,12 +20,26 @@ public class ScripthashTests
var script = Script.FromHex(scriptHex); var script = Script.FromHex(scriptHex);
Assert.Equal(expected, Scripthash.FromScript(script)); Assert.Equal(expected, Scripthash.FromScript(script));
} }
[Fact]
public void Script_identici_producono_scripthash_identico()
{
var script = Script.FromHex("76a9140102030405060708090a0b0c0d0e0f101112131488ac");
Assert.Equal(Scripthash.FromScript(script), Scripthash.FromScript(script));
}
[Fact]
public void Script_diversi_producono_scripthash_diversi()
{
var s1 = Script.FromHex("76a9140102030405060708090a0b0c0d0e0f101112131488ac");
var s2 = Script.FromHex("00140102030405060708090a0b0c0d0e0f1011121314");
Assert.NotEqual(Scripthash.FromScript(s1), Scripthash.FromScript(s2));
}
} }
public class MerkleProofTests public class MerkleProofTests
{ {
// Blocco Bitcoin 100000: 4 transazioni, merkle root nota — àncora esterna // Blocco Bitcoin 100000: 4 transazioni (pari), merkle root nota.
// per la convenzione di hashing/ordinamento.
private static readonly uint256[] Block100000Txids = private static readonly uint256[] Block100000Txids =
[ [
uint256.Parse("8c14f0db3df150123e6f3dbbf30f8b955a8249b62ac1d1ff16284aefa3d06d87"), uint256.Parse("8c14f0db3df150123e6f3dbbf30f8b955a8249b62ac1d1ff16284aefa3d06d87"),
@@ -34,6 +51,8 @@ public class MerkleProofTests
private static readonly uint256 Block100000Root = private static readonly uint256 Block100000Root =
uint256.Parse("f3e94742aca4b5ef85488dc37c06c3282295ffec960994b2c0d5ac2a25a95766"); uint256.Parse("f3e94742aca4b5ef85488dc37c06c3282295ffec960994b2c0d5ac2a25a95766");
// ---- numero pari di transazioni (4 tx) ----
[Fact] [Fact]
public void La_radice_calcolata_dalle_foglie_coincide_con_quella_del_blocco() public void La_radice_calcolata_dalle_foglie_coincide_con_quella_del_blocco()
{ {
@@ -51,6 +70,70 @@ public class MerkleProofTests
Assert.True(MerkleProof.Verify(Block100000Txids[position], position, branch, Block100000Root)); Assert.True(MerkleProof.Verify(Block100000Txids[position], position, branch, Block100000Root));
} }
// ---- singola transazione ----
[Fact]
public void Radice_con_singola_tx_e_la_tx_stessa()
{
var txid = uint256.Parse("8c14f0db3df150123e6f3dbbf30f8b955a8249b62ac1d1ff16284aefa3d06d87");
var root = MerkleProof.ComputeRootFromLeaves([txid]);
Assert.Equal(txid, root);
}
[Fact]
public void Verify_con_branch_vuoto_e_posizione_0_e_la_tx_stessa()
{
var txid = uint256.Parse("8c14f0db3df150123e6f3dbbf30f8b955a8249b62ac1d1ff16284aefa3d06d87");
var root = MerkleProof.ComputeRootFromLeaves([txid]);
Assert.True(MerkleProof.Verify(txid, 0, [], root));
}
// ---- numero dispari di transazioni (duplicazione dell'ultimo) ----
[Fact]
public void Tre_tx_dispari_la_terza_viene_duplicata()
{
// Con 3 tx: livello 1 = [SHA256d(tx0||tx1), SHA256d(tx2||tx2)]
// Verifica che la radice sia deterministica e corretta.
var txids = Block100000Txids.Take(3).ToArray();
var root = MerkleProof.ComputeRootFromLeaves(txids);
var branch2 = BuildBranch(txids, 2);
Assert.True(MerkleProof.Verify(txids[2], 2, branch2, root));
}
[Fact]
public void Cinque_tx_dispari_verifica_tutte_le_posizioni()
{
// 5 tx → livello pari (4) → livello pari (2) → radice
var txids = new uint256[5];
for (var i = 0; i < 5; i++)
txids[i] = new uint256(new byte[32].Select((_, j) => (byte)(i * 17 + j)).ToArray());
var root = MerkleProof.ComputeRootFromLeaves(txids);
for (var pos = 0; pos < 5; pos++)
{
var branch = BuildBranch(txids, pos);
Assert.True(MerkleProof.Verify(txids[pos], pos, branch, root),
$"posizione {pos} non verifica");
}
}
// ---- due transazioni (pari minimo) ----
[Fact]
public void Due_tx_verifica_entrambe_le_posizioni()
{
var txids = Block100000Txids.Take(2).ToArray();
var root = MerkleProof.ComputeRootFromLeaves(txids);
for (var pos = 0; pos < 2; pos++)
{
var branch = BuildBranch(txids, pos);
Assert.True(MerkleProof.Verify(txids[pos], pos, branch, root));
}
}
// ---- proof errate ----
[Fact] [Fact]
public void Una_prova_per_la_posizione_sbagliata_fallisce() public void Una_prova_per_la_posizione_sbagliata_fallisce()
{ {
@@ -65,6 +148,29 @@ public class MerkleProofTests
Assert.False(MerkleProof.Verify(uint256.One, 0, branch, Block100000Root)); Assert.False(MerkleProof.Verify(uint256.One, 0, branch, Block100000Root));
} }
[Fact]
public void Branch_alterato_non_verifica()
{
var branch = BuildBranch(Block100000Txids, 0);
branch[0] = uint256.One; // corrompe il primo elemento del branch
Assert.False(MerkleProof.Verify(Block100000Txids[0], 0, branch, Block100000Root));
}
[Fact]
public void Radice_alterata_non_verifica()
{
var branch = BuildBranch(Block100000Txids, 0);
Assert.False(MerkleProof.Verify(Block100000Txids[0], 0, branch, uint256.One));
}
// ---- lista vuota lancia eccezione ----
[Fact]
public void Lista_vuota_lancia_ArgumentException()
{
Assert.Throws<ArgumentException>(() => MerkleProof.ComputeRootFromLeaves([]));
}
/// <summary>Costruisce il branch per una foglia ricostruendo i livelli dell'albero.</summary> /// <summary>Costruisce il branch per una foglia ricostruendo i livelli dell'albero.</summary>
private static List<uint256> BuildBranch(IReadOnlyList<uint256> leaves, int position) private static List<uint256> BuildBranch(IReadOnlyList<uint256> leaves, int position)
{ {
@@ -89,7 +195,6 @@ public class MerkleProofTests
public class BlockHeaderInfoTests public class BlockHeaderInfoTests
{ {
// Header del blocco genesi di Bitcoin (riusato dalla mainnet PLM, §3).
private const string GenesisHeaderHex = private const string GenesisHeaderHex =
"0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c"; "0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c";
@@ -118,10 +223,20 @@ public class BlockHeaderInfoTests
[Fact] [Fact]
public void Con_skip_pow_la_validazione_non_controlla_il_target() public void Con_skip_pow_la_validazione_non_controlla_il_target()
{ {
// La genesi ha PoW valido, ma il punto è che con SkipPowValidation=true
// (LWMA, §3) il check si limita al collegamento.
var header = BlockHeaderInfo.Parse(GenesisHeaderHex); var header = BlockHeaderInfo.Parse(GenesisHeaderHex);
Assert.True(ChainProfiles.Mainnet.SkipPowValidation); Assert.True(ChainProfiles.Mainnet.SkipPowValidation);
Assert.True(header.IsValidChild(uint256.Zero, ChainProfiles.Mainnet)); Assert.True(header.IsValidChild(uint256.Zero, ChainProfiles.Mainnet));
} }
[Fact]
public void Header_troncato_lancia_eccezione()
{
Assert.ThrowsAny<Exception>(() => BlockHeaderInfo.Parse("0100000000"));
}
[Fact]
public void Header_hex_non_valido_lancia_eccezione()
{
Assert.ThrowsAny<Exception>(() => BlockHeaderInfo.Parse("ZZZ"));
}
} }
@@ -1,3 +1,6 @@
using System;
using System.IO;
using System.Text.Json.Nodes;
using PalladiumWallet.Core.Storage; using PalladiumWallet.Core.Storage;
namespace PalladiumWallet.Tests.Storage; namespace PalladiumWallet.Tests.Storage;
@@ -14,6 +17,11 @@ public class StorageTests
Labels = { ["txid123"] = "caffè" }, Labels = { ["txid123"] = "caffè" },
}; };
private static string TempPath() =>
Path.Combine(Path.GetTempPath(), $"plm-test-{Guid.NewGuid()}.wallet.json");
// ---- cifratura AES-GCM ----
[Fact] [Fact]
public void La_cifratura_fa_roundtrip_con_la_password_giusta() public void La_cifratura_fa_roundtrip_con_la_password_giusta()
{ {
@@ -34,14 +42,43 @@ public class StorageTests
public void Un_file_manomesso_viene_rifiutato() public void Un_file_manomesso_viene_rifiutato()
{ {
var cipher = EncryptedFile.Encrypt("contenuto", "pass"); var cipher = EncryptedFile.Encrypt("contenuto", "pass");
// Corrompe un byte del ciphertext mantenendo base64 e JSON validi. var node = JsonNode.Parse(cipher)!;
var node = System.Text.Json.Nodes.JsonNode.Parse(cipher)!;
var data = Convert.FromBase64String(node["Data"]!.GetValue<string>()); var data = Convert.FromBase64String(node["Data"]!.GetValue<string>());
data[0] ^= 0xff; data[0] ^= 0xff;
node["Data"] = Convert.ToBase64String(data); node["Data"] = Convert.ToBase64String(data);
Assert.Throws<WrongPasswordException>(() => EncryptedFile.Decrypt(node.ToJsonString(), "pass")); Assert.Throws<WrongPasswordException>(() => EncryptedFile.Decrypt(node.ToJsonString(), "pass"));
} }
[Fact]
public void Ogni_encrypt_produce_nonce_diverso()
{
var c1 = JsonNode.Parse(EncryptedFile.Encrypt("x", "p"))!["Nonce"]!.GetValue<string>();
var c2 = JsonNode.Parse(EncryptedFile.Encrypt("x", "p"))!["Nonce"]!.GetValue<string>();
Assert.NotEqual(c1, c2);
}
[Fact]
public void Ogni_encrypt_produce_salt_diverso()
{
var s1 = JsonNode.Parse(EncryptedFile.Encrypt("x", "p"))!["Salt"]!.GetValue<string>();
var s2 = JsonNode.Parse(EncryptedFile.Encrypt("x", "p"))!["Salt"]!.GetValue<string>();
Assert.NotEqual(s1, s2);
}
[Fact]
public void IsEncrypted_restituisce_false_per_json_non_cifrato()
{
Assert.False(EncryptedFile.IsEncrypted("{\"Version\": 1}"));
}
[Fact]
public void IsEncrypted_restituisce_false_per_testo_non_json()
{
Assert.False(EncryptedFile.IsEncrypted("non è json"));
}
// ---- WalletDocument JSON ----
[Fact] [Fact]
public void Il_documento_wallet_fa_roundtrip_json() public void Il_documento_wallet_fa_roundtrip_json()
{ {
@@ -58,15 +95,36 @@ public class StorageTests
[Fact] [Fact]
public void Una_versione_futura_del_file_viene_rifiutata() public void Una_versione_futura_del_file_viene_rifiutata()
{ {
var doc = SampleDoc(); var json = SampleDoc().ToJson().Replace("\"Version\": 1", "\"Version\": 99");
var json = doc.ToJson().Replace("\"Version\": 1", "\"Version\": 99");
Assert.Throws<InvalidDataException>(() => WalletDocument.FromJson(json)); Assert.Throws<InvalidDataException>(() => WalletDocument.FromJson(json));
} }
[Fact]
public void Il_documento_senza_mnemonica_e_watch_only()
{
var doc = SampleDoc();
doc.Mnemonic = null;
Assert.True(WalletDocument.FromJson(doc.ToJson()).IsWatchOnly);
}
[Fact]
public void Json_corrotto_lancia_eccezione()
{
Assert.ThrowsAny<Exception>(() => WalletDocument.FromJson("{non è json valido}"));
}
[Fact]
public void Json_con_campi_mancanti_lancia_eccezione()
{
Assert.ThrowsAny<Exception>(() => WalletDocument.FromJson("{}"));
}
// ---- WalletStore ----
[Fact] [Fact]
public void Il_wallet_store_salva_e_riapre_con_e_senza_password() public void Il_wallet_store_salva_e_riapre_con_e_senza_password()
{ {
var path = Path.Combine(Path.GetTempPath(), $"plm-test-{Guid.NewGuid()}.wallet.json"); var path = TempPath();
try try
{ {
WalletStore.Save(SampleDoc(), path); WalletStore.Save(SampleDoc(), path);
@@ -86,17 +144,59 @@ public class StorageTests
} }
[Fact] [Fact]
public void Il_documento_senza_mnemonica_e_watch_only() public void Scrittura_atomica_non_lascia_file_tmp()
{ {
var doc = SampleDoc(); var path = TempPath();
doc.Mnemonic = null; try
Assert.True(WalletDocument.FromJson(doc.ToJson()).IsWatchOnly); {
WalletStore.Save(SampleDoc(), path);
Assert.True(File.Exists(path));
Assert.False(File.Exists(path + ".tmp"));
} }
finally
{
File.Delete(path);
}
}
[Fact]
public void Load_da_path_inesistente_lancia_eccezione()
{
var path = Path.Combine(Path.GetTempPath(), $"plm-noexist-{Guid.NewGuid()}.wallet.json");
Assert.Throws<FileNotFoundException>(() => WalletStore.Load(path));
}
[Fact]
public void Exists_restituisce_false_per_path_inesistente()
{
var path = Path.Combine(Path.GetTempPath(), $"plm-noexist-{Guid.NewGuid()}.wallet.json");
Assert.False(WalletStore.Exists(path));
}
[Fact]
public void Due_save_successivi_producono_nonce_diversi()
{
var path = TempPath();
try
{
WalletStore.Save(SampleDoc(), path, "password");
var n1 = JsonNode.Parse(File.ReadAllText(path))!["Nonce"]!.GetValue<string>();
WalletStore.Save(SampleDoc(), path, "password");
var n2 = JsonNode.Parse(File.ReadAllText(path))!["Nonce"]!.GetValue<string>();
Assert.NotEqual(n1, n2);
}
finally
{
File.Delete(path);
}
}
// ---- WalletLock ----
[Fact] [Fact]
public void WalletLock_acquisisce_e_rilascia() public void WalletLock_acquisisce_e_rilascia()
{ {
var path = Path.Combine(Path.GetTempPath(), $"plm-lock-{Guid.NewGuid()}.wallet.json"); var path = TempPath();
try try
{ {
using var lock1 = WalletLock.TryAcquire(path); using var lock1 = WalletLock.TryAcquire(path);
@@ -104,7 +204,6 @@ public class StorageTests
} }
finally finally
{ {
File.Delete(path);
File.Delete(path + ".lock"); File.Delete(path + ".lock");
} }
} }
@@ -112,18 +211,15 @@ public class StorageTests
[Fact] [Fact]
public void WalletLock_seconda_istanza_restituisce_null() public void WalletLock_seconda_istanza_restituisce_null()
{ {
var path = Path.Combine(Path.GetTempPath(), $"plm-lock-{Guid.NewGuid()}.wallet.json"); var path = TempPath();
try try
{ {
using var lock1 = WalletLock.TryAcquire(path); using var lock1 = WalletLock.TryAcquire(path);
Assert.NotNull(lock1); Assert.NotNull(lock1);
Assert.Null(WalletLock.TryAcquire(path));
var lock2 = WalletLock.TryAcquire(path);
Assert.Null(lock2);
} }
finally finally
{ {
File.Delete(path);
File.Delete(path + ".lock"); File.Delete(path + ".lock");
} }
} }
@@ -131,7 +227,7 @@ public class StorageTests
[Fact] [Fact]
public void WalletLock_riacquisibile_dopo_rilascio() public void WalletLock_riacquisibile_dopo_rilascio()
{ {
var path = Path.Combine(Path.GetTempPath(), $"plm-lock-{Guid.NewGuid()}.wallet.json"); var path = TempPath();
try try
{ {
var lock1 = WalletLock.TryAcquire(path); var lock1 = WalletLock.TryAcquire(path);
@@ -143,8 +239,37 @@ public class StorageTests
} }
finally finally
{ {
File.Delete(path);
File.Delete(path + ".lock"); File.Delete(path + ".lock");
} }
} }
[Fact]
public void WalletLock_dispose_rimuove_il_file_lock()
{
var path = TempPath();
var lockPath = path + ".lock";
var lock1 = WalletLock.TryAcquire(path);
Assert.NotNull(lock1);
lock1!.Dispose();
Assert.False(File.Exists(lockPath));
}
[Fact]
public void WalletLock_file_lock_preesistente_ma_non_bloccato_viene_acquisito()
{
// Un .lock rimasto da un crash precedente (file esiste ma nessuno lo tiene)
// non deve bloccare l'apertura del wallet.
var path = TempPath();
var lockPath = path + ".lock";
try
{
File.WriteAllText(lockPath, "stale");
using var lock1 = WalletLock.TryAcquire(path);
Assert.NotNull(lock1);
}
finally
{
File.Delete(lockPath);
}
}
} }
@@ -1,39 +1,137 @@
using System;
using PalladiumWallet.Core.Wallet; using PalladiumWallet.Core.Wallet;
namespace PalladiumWallet.Tests.Wallet; namespace PalladiumWallet.Tests.Wallet;
public class CoinAmountTests public class CoinAmountTests
{ {
// --- importi validi --- // ---- importi validi: tutte le unità ----
[Theory] [Theory]
[InlineData("1", "sat", 1)] [InlineData("1", "sat", 1)]
[InlineData("0", "sat", 0)] [InlineData("0", "sat", 0)]
[InlineData("0", "PLM", 0)]
[InlineData("0", "mPLM", 0)]
[InlineData("0", "µPLM", 0)]
[InlineData("1.5", "PLM", 150_000_000)] [InlineData("1.5", "PLM", 150_000_000)]
[InlineData("0.00000001", "PLM", 1)] [InlineData("0.00000001", "PLM", 1)]
[InlineData("1", "PLM", 100_000_000)] [InlineData("1", "PLM", 100_000_000)]
[InlineData("1.00000", "mPLM", 100_000)] [InlineData("1.00000", "mPLM", 100_000)]
[InlineData("0.00001", "mPLM", 1)]
[InlineData("1.00", "µPLM", 100)] [InlineData("1.00", "µPLM", 100)]
[InlineData("0.01", "µPLM", 1)]
[InlineData("100000000", "sat", 100_000_000)]
public void Importo_valido_viene_accettato(string input, string unit, long expectedSats) public void Importo_valido_viene_accettato(string input, string unit, long expectedSats)
{ {
Assert.True(CoinAmount.TryParseIn(input, unit, out var sats)); Assert.True(CoinAmount.TryParseIn(input, unit, out var sats));
Assert.Equal(expectedSats, sats); Assert.Equal(expectedSats, sats);
} }
// --- importi con troppi decimali: devono essere rifiutati --- // ---- decimale con virgola (locale italiano) ----
[Theory] [Theory]
[InlineData("1.9", "sat")] // sat non è divisibile [InlineData("1,5", "PLM", 150_000_000)]
[InlineData("0.001", "µPLM")] // 0.001 × 100 = 0.1 sat [InlineData("1,00000", "mPLM", 100_000)]
[InlineData("1.500000001", "PLM")] // 9 decimali, uno di troppo [InlineData("0,00000001", "PLM", 1)]
[InlineData("0.000000001", "PLM")] // sotto al satoshi public void Virgola_italiana_viene_accettata(string input, string unit, long expectedSats)
{
Assert.True(CoinAmount.TryParseIn(input, unit, out var sats));
Assert.Equal(expectedSats, sats);
}
// ---- spazi iniziali/finali ----
[Theory]
[InlineData(" 1 ", "sat", 1)]
[InlineData(" 1.5 ", "PLM", 150_000_000)]
public void Spazi_iniziali_e_finali_vengono_ignorati(string input, string unit, long expectedSats)
{
Assert.True(CoinAmount.TryParseIn(input, unit, out var sats));
Assert.Equal(expectedSats, sats);
}
// ---- importi con troppi decimali ----
[Theory]
[InlineData("1.9", "sat")]
[InlineData("1.1", "sat")] [InlineData("1.1", "sat")]
[InlineData("0.001", "µPLM")]
[InlineData("1.500000001", "PLM")]
[InlineData("0.000000001", "PLM")]
[InlineData("0.000001", "mPLM")]
public void Importo_con_troppi_decimali_viene_rifiutato(string input, string unit) public void Importo_con_troppi_decimali_viene_rifiutato(string input, string unit)
{ {
Assert.False(CoinAmount.TryParseIn(input, unit, out _)); Assert.False(CoinAmount.TryParseIn(input, unit, out _));
} }
// --- TryParseCoins --- // ---- negativi ----
[Theory]
[InlineData("-1", "sat")]
[InlineData("-0.1", "PLM")]
[InlineData("-1", "PLM")]
public void Importo_negativo_viene_rifiutato(string input, string unit)
{
Assert.False(CoinAmount.TryParseIn(input, unit, out _));
}
// ---- stringa vuota e non numerica ----
[Theory]
[InlineData("")]
[InlineData("abc")]
[InlineData("1e5")]
[InlineData("∞")]
public void Stringa_non_numerica_viene_rifiutata(string input)
{
Assert.False(CoinAmount.TryParseIn(input, "PLM", out _));
}
// ---- overflow ----
[Fact]
public void Overflow_viene_rifiutato()
{
// 92233720368.54775807 PLM supera long.MaxValue in satoshi
Assert.False(CoinAmount.TryParseIn("99999999999", "PLM", out _));
}
// ---- unità sconosciuta lancia ArgumentException ----
[Theory]
[InlineData("banana")]
[InlineData("BTC")]
[InlineData("")]
[InlineData("plm")] // case-sensitive
public void Unita_sconosciuta_lancia_ArgumentException(string unit)
{
Assert.Throws<ArgumentException>(() => CoinAmount.TryParseIn("1", unit, out _));
}
[Fact]
public void FormatIn_unita_sconosciuta_lancia_ArgumentException()
{
Assert.Throws<ArgumentException>(() => CoinAmount.FormatIn(1, "banana"));
}
// ---- roundtrip FormatIn → TryParseIn ----
[Theory]
[InlineData(0, "PLM")]
[InlineData(1, "sat")]
[InlineData(1, "PLM")]
[InlineData(150_000_000, "PLM")]
[InlineData(100_000, "mPLM")]
[InlineData(100, "µPLM")]
[InlineData(99_999_999, "PLM")]
public void Roundtrip_format_parse_conserva_i_satoshi(long sats, string unit)
{
var formatted = CoinAmount.FormatIn(sats, unit, withLabel: false);
Assert.True(CoinAmount.TryParseIn(formatted, unit, out var parsed));
Assert.Equal(sats, parsed);
}
// ---- TryParseCoins ----
[Fact] [Fact]
public void TryParseCoins_accetta_precisione_massima() public void TryParseCoins_accetta_precisione_massima()
@@ -42,6 +140,13 @@ public class CoinAmountTests
Assert.Equal(1L, sats); Assert.Equal(1L, sats);
} }
[Fact]
public void TryParseCoins_virgola_italiana()
{
Assert.True(CoinAmount.TryParseCoins("1,5", out var sats));
Assert.Equal(150_000_000L, sats);
}
[Fact] [Fact]
public void TryParseCoins_rifiuta_sotto_al_satoshi() public void TryParseCoins_rifiuta_sotto_al_satoshi()
{ {
@@ -53,4 +158,21 @@ public class CoinAmountTests
{ {
Assert.False(CoinAmount.TryParseCoins("-1", out _)); Assert.False(CoinAmount.TryParseCoins("-1", out _));
} }
[Fact]
public void TryParseCoins_rifiuta_overflow()
{
Assert.False(CoinAmount.TryParseCoins("99999999999", out _));
}
// ---- Format (PLM con 8 decimali) ----
[Theory]
[InlineData(100_000_000, "1.00000000")]
[InlineData(1, "0.00000001")]
[InlineData(0, "0.00000000")]
public void Format_produce_stringa_con_8_decimali(long sats, string expected)
{
Assert.Equal(expected, CoinAmount.Format(sats));
}
} }
@@ -0,0 +1,188 @@
using System;
using PalladiumWallet.Core.Chain;
using PalladiumWallet.Core.Crypto;
using PalladiumWallet.Core.Storage;
using PalladiumWallet.Core.Wallet;
namespace PalladiumWallet.Tests.Wallet;
public class WalletLoaderTests
{
private const string ValidMnemonic =
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
private const string ValidMnemonic24 =
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon " +
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art";
// ---- NewFromMnemonic ----
[Fact]
public void NewFromMnemonic_crea_documento_con_rete_e_tipo_corretti()
{
var profile = ChainProfiles.Mainnet;
var (doc, account) = WalletLoader.NewFromMnemonic(
ValidMnemonic, passphrase: null, ScriptKind.NativeSegwit, profile);
Assert.Equal("mainnet", doc.Network);
Assert.Equal("NativeSegwit", doc.ScriptKind);
Assert.Equal(ValidMnemonic, doc.Mnemonic);
Assert.Null(doc.Passphrase);
Assert.NotEmpty(doc.AccountXpub);
Assert.NotEmpty(doc.MasterFingerprint);
Assert.False(doc.IsWatchOnly);
}
[Fact]
public void NewFromMnemonic_stessa_mnemonica_produce_stesso_xpub()
{
var profile = ChainProfiles.Mainnet;
var (doc1, _) = WalletLoader.NewFromMnemonic(ValidMnemonic, null, ScriptKind.NativeSegwit, profile);
var (doc2, _) = WalletLoader.NewFromMnemonic(ValidMnemonic, null, ScriptKind.NativeSegwit, profile);
Assert.Equal(doc1.AccountXpub, doc2.AccountXpub);
}
[Fact]
public void NewFromMnemonic_passphrase_diversa_produce_xpub_diverso()
{
var profile = ChainProfiles.Mainnet;
var (doc1, _) = WalletLoader.NewFromMnemonic(ValidMnemonic, null, ScriptKind.NativeSegwit, profile);
var (doc2, _) = WalletLoader.NewFromMnemonic(ValidMnemonic, "passphrase", ScriptKind.NativeSegwit, profile);
Assert.NotEqual(doc1.AccountXpub, doc2.AccountXpub);
}
[Fact]
public void NewFromMnemonic_mnemonica_invalida_lancia_eccezione()
{
Assert.Throws<InvalidDataException>(() =>
WalletLoader.NewFromMnemonic("parole non valide foo bar", null, ScriptKind.NativeSegwit, ChainProfiles.Mainnet));
}
[Fact]
public void NewFromMnemonic_mnemonica_24_parole_funziona()
{
var (doc, _) = WalletLoader.NewFromMnemonic(
ValidMnemonic24, null, ScriptKind.NativeSegwit, ChainProfiles.Mainnet);
Assert.Equal("mainnet", doc.Network);
Assert.NotEmpty(doc.AccountXpub);
}
[Fact]
public void NewFromMnemonic_tipi_script_producono_xpub_diversi()
{
var profile = ChainProfiles.Mainnet;
var (docNative, _) = WalletLoader.NewFromMnemonic(ValidMnemonic, null, ScriptKind.NativeSegwit, profile);
var (docWrapped, _) = WalletLoader.NewFromMnemonic(ValidMnemonic, null, ScriptKind.WrappedSegwit, profile);
var (docLegacy, _) = WalletLoader.NewFromMnemonic(ValidMnemonic, null, ScriptKind.Legacy, profile);
Assert.NotEqual(docNative.AccountXpub, docWrapped.AccountXpub);
Assert.NotEqual(docNative.AccountXpub, docLegacy.AccountXpub);
}
[Fact]
public void NewFromMnemonic_reti_diverse_producono_xpub_diverse()
{
var (docMain, _) = WalletLoader.NewFromMnemonic(ValidMnemonic, null, ScriptKind.NativeSegwit, ChainProfiles.Mainnet);
var (docTest, _) = WalletLoader.NewFromMnemonic(ValidMnemonic, null, ScriptKind.NativeSegwit, ChainProfiles.Testnet);
Assert.NotEqual(docMain.AccountXpub, docTest.AccountXpub);
}
// ---- ToAccount ----
[Fact]
public void ToAccount_da_mnemonica_deriva_gli_stessi_indirizzi_ad_ogni_caricamento()
{
var (doc, _) = WalletLoader.NewFromMnemonic(
ValidMnemonic, null, ScriptKind.NativeSegwit, ChainProfiles.Mainnet);
var account1 = WalletLoader.ToAccount(doc);
var account2 = WalletLoader.ToAccount(doc);
Assert.Equal(
account1.GetReceiveAddress(0).ToString(),
account2.GetReceiveAddress(0).ToString());
}
[Fact]
public void ToAccount_da_mnemonica_non_e_watch_only()
{
var (doc, _) = WalletLoader.NewFromMnemonic(
ValidMnemonic, null, ScriptKind.NativeSegwit, ChainProfiles.Mainnet);
var account = WalletLoader.ToAccount(doc);
Assert.False(account.IsWatchOnly);
}
[Fact]
public void ToAccount_da_xpub_e_watch_only_e_produce_stessi_indirizzi()
{
var (doc, accountSeed) = WalletLoader.NewFromMnemonic(
ValidMnemonic, null, ScriptKind.NativeSegwit, ChainProfiles.Mainnet);
// Crea documento watch-only rimuovendo la mnemonica
var docWo = new WalletDocument
{
Network = doc.Network,
ScriptKind = doc.ScriptKind,
AccountPath = doc.AccountPath,
AccountXpub = doc.AccountXpub,
};
var accountWo = WalletLoader.ToAccount(docWo);
Assert.True(accountWo.IsWatchOnly);
Assert.Equal(
accountSeed.GetReceiveAddress(0).ToString(),
accountWo.GetReceiveAddress(0).ToString());
Assert.Equal(
accountSeed.GetReceiveAddress(9).ToString(),
accountWo.GetReceiveAddress(9).ToString());
}
[Fact]
public void ToAccount_watch_only_non_espone_chiavi_private()
{
var (doc, _) = WalletLoader.NewFromMnemonic(
ValidMnemonic, null, ScriptKind.NativeSegwit, ChainProfiles.Mainnet);
var docWo = new WalletDocument
{
Network = doc.Network,
ScriptKind = doc.ScriptKind,
AccountPath = doc.AccountPath,
AccountXpub = doc.AccountXpub,
};
var account = WalletLoader.ToAccount(docWo);
Assert.Throws<InvalidOperationException>(() => account.GetExtPrivateKey(false, 0));
}
[Fact]
public void ToAccount_rete_sconosciuta_lancia_eccezione()
{
var (doc, _) = WalletLoader.NewFromMnemonic(
ValidMnemonic, null, ScriptKind.NativeSegwit, ChainProfiles.Mainnet);
var docBad = new WalletDocument
{
Network = "fantanet",
ScriptKind = doc.ScriptKind,
AccountPath = doc.AccountPath,
AccountXpub = doc.AccountXpub,
Mnemonic = doc.Mnemonic,
};
Assert.ThrowsAny<Exception>(() => WalletLoader.ToAccount(docBad));
}
// ---- ProfileOf ----
[Theory]
[InlineData("mainnet", NetKind.Mainnet)]
[InlineData("testnet", NetKind.Testnet)]
[InlineData("regtest", NetKind.Regtest)]
[InlineData("Mainnet", NetKind.Mainnet)]
public void ProfileOf_riconosce_le_reti_note(string network, NetKind expected)
{
var doc = new WalletDocument { Network = network, ScriptKind = "NativeSegwit",
AccountPath = "84'/0'/0'", AccountXpub = "xpub" };
Assert.Equal(expected, WalletLoader.ProfileOf(doc).Kind);
}
}