15 Commits
Author SHA1 Message Date
davide 0d541d0fe3 chore(release): bump version to 1.1.0
Fills in the CHANGELOG.md entry for the watch-only address-only import
mode, progressive Merkle verification, transaction size-limit fix, and
Android sync-reconnect fixes since 1.0.0, and bumps <Version>/versionCode
across the App and Android head csproj files ahead of the tag.
2026-07-19 17:59:56 +02:00
davide 7057905d94 fix(ui): hide Donate tab in Help until a wallet is open
The tab requires an open wallet to send from, so showing it before
one is loaded led to a dead end. Gate it behind IsWalletOpen, same as
the other wallet-only UI.
2026-07-19 17:46:34 +02:00
davide 51f1af8786 fix(ui): stop wizard/overlay TextBoxes from resizing on focus
Width-capped containers (wizard steps, private-key prompt, wallet info
overlay) used HorizontalAlignment="Center" with MaxWidth, which sizes
the panel from its content's DesiredSize. Since PlaceholderText only
contributes to that measurement while a TextBox is empty and
unfocused, clicking into an empty field shrank the whole panel.

Switch to HorizontalAlignment="Stretch": Avalonia's ArrangeCore sizes
Stretch from the available arrange rect (clamped by MaxWidth) instead
of DesiredSize, and centers the result exactly like Center alignment
does when MaxWidth caps it — so the box stays a fixed width regardless
of focus/placeholder state, on both desktop and Android.
2026-07-19 17:44:01 +02:00
davide 4cd5fab736 fix(sync): bound keep-alive ping and resume a sync stuck on lock/unlock
Three issues surfaced by testing the previous lock/unlock reconnect fix
on Android with a large wallet:

- The keep-alive ping had no timeout, so a "half-open" TCP connection
  (remote end gone with no FIN/RST ever delivered, the common outcome
  of Doze/mobile-radio suspend after a longer lock) left it awaiting a
  response that never arrives — the failure path that tears the dead
  client down was never reached. Bound the ping to 8s and added a
  re-entrancy guard so overlapping 20s ticks can't pile up concurrent
  reconnect attempts while one is stuck.

- CheckConnectionOnResumeAsync bailed out whenever a sync was already
  in progress, so a lock/unlock during an active sync (which has no
  per-request timeout of its own) left it hung indefinitely instead of
  recovering. It now cancels the stuck sync and tears down the dead
  client, marking the interruption as self-inflicted (_resumeRecovering)
  so the UI shows "reconnecting" and restarts immediately instead of a
  transient error message.

- WalletSynchronizer.ExportCaches persisted raw transaction bytes only
  for already-verified transactions, discarding anything downloaded but
  not yet through Merkle-proof verification when a sync was interrupted
  mid-way — forcing a full re-download of a large wallet's transactions
  on every resume instead of resuming straight into proof verification.
  Track confirmed txids at download time (_confirmedTxids), independent
  of verification status, and export/preload against that instead.

Also unified the three sync progress messages onto one template
reporting against the sync's total transaction/proof counts rather than
this session's download count, so a resumed sync immediately shows
"transactions n/n" instead of a misleading "0/0" before jumping into
proof verification.
2026-07-19 17:43:31 +02:00
davide 94a474fe41 fix(sync): recover connection after Android screen lock/unlock
TcpClient.Connected only reflects the last known socket state, so a
connection killed silently while the phone was locked (Doze, mobile
radio suspend, NAT timeout) still reported IsConnected == true. The
keep-alive ping's failure was swallowed by an empty catch, so the
stale "connected" state never cleared and sync kept retrying on a
dead socket instead of reconnecting.

Treat a failed keep-alive ping as a disconnect (tear down the client
and reconnect), and add OnPause/OnResume to the Android activity to
force an immediate health check on resume instead of waiting for the
20s timer, which may itself be suspended during Doze.
2026-07-19 16:01:18 +02:00
davide bbed21e820 docs: reconcile README/SECURITY with current repo state
README.md was out of date after several recent features: it listed 6
UI languages (missing Chinese Simplified), described watch-only as
xpub-only (address-only import also exists), overclaimed multisig as a
working PSBT flow (derivation for it actually throws — not
implemented), and its CLI quick-reference omitted restore-address and
servers. Also links the new USERGUIDE.md, previously unreferenced from
README.

SECURITY.md's "known limitations" list didn't mention multisig is
unsupported, worth stating explicitly since it's fund-safety adjacent.
2026-07-19 12:59:15 +02:00
davide 06f512e2f7 docs(userguide): document first-sync timing and warn against mining payouts
Explains why initial sync scales with transaction count rather than
wallet age (one Merkle-proof round trip per confirmed transaction, no
batching in the Electrum-style protocol) and why it's slower on mobile,
plus why later syncs are fast (cache persists proofs/headers/anchoring
state). Advises against using this wallet as a mining payout address:
the many small transactions typical of payouts make sync noticeably
slower (observed ~2 minutes past 5,000 transactions).
2026-07-19 12:59:02 +02:00
davide 5bb94c071f Merge branch 'watch-only'
Adds a pure address-only watch-only wallet mode (Core + CLI + App wizard
+ Send UI), on top of the existing xpub/xprv/WIF import flows which are
unchanged. TransactionFactory already refuses to sign for any IsWatchOnly
account, so the new address-only accounts inherit that guarantee for free.
2026-07-19 12:44:51 +02:00
davide 11b6a9a9ab docs(security): document address-only watch-only wallets
Keeps the key-management section of the threat model accurate for the
new restore-address / pure address import path (SECURITY.md must stay
in sync with any change to key/seed handling per project convention).
2026-07-19 12:39:52 +02:00
davide 9b00002e39 feat(app): label watch-only send flow and export unsigned PSBT
Send already refused to enable Confirm for watch-only accounts (Signed
false), but the App had no way to get the resulting PSBT out to sign
elsewhere — only the CLI printed it. Adds a base64 PSBT box + copy button
in the Send summary card, and a visible warning banner explaining the
wallet cannot sign, on both desktop and mobile layouts.
2026-07-19 12:39:28 +02:00
davide f0fb5bfcc6 feat(app): add watch-address import step to setup wizard
New wizard flow mirroring the existing xpub/WIF import steps: paste one
or more plain addresses (no key material at all) and go straight to the
password step, since there is no derivation and no script-type ambiguity
to resolve for a fixed address list.
2026-07-19 12:38:58 +02:00
davide 9fa5440ae5 feat(cli): add restore-address command for pure address watch-only
Parallels restore-xpub but for one or more plain addresses with no
extended key and no private key — output is explicitly labelled
"cannot sign" since the resulting wallet can never produce a signed tx.
2026-07-19 12:38:11 +02:00
davide 214abd2892 feat(core): support pure watch-only address import
Adds a WalletDocument.WatchAddresses field and WalletLoader.NewFromAddresses
to build an ImportedKeyAccount with no private key at all (unlike xpub/WIF
imports, which can still derive/hold key material). ScriptKind is inferred
from the address itself via a new DerivationPaths.KindFor helper. Signing
already refuses to run for any IsWatchOnly account (TransactionFactory), so
this only had to wire up construction/reload of the new account shape.
2026-07-19 12:37:31 +02:00
davide 6d05a88073 perf(net): make ElectrumClient's in-flight request cap configurable
MaxInFlight was a hardcoded constant (32); different indexing servers
tolerate different levels of request concurrency before throttling, so
expose it as an optional ConnectAsync parameter instead of requiring a
recompile to tune initial-sync throughput against a given server.
2026-07-19 12:16:18 +02:00
davide d9dd05aa52 perf(spv): persist checkpoint-anchoring state across sync sessions
_anchoredUpTo tracked which heights were already proven to hash-chain
back to a checkpoint, but only in memory: every app restart re-walked
and re-verified the whole header chain from the checkpoint even when
the header bytes themselves were already cached on disk, dominating
reconnect time on large wallets. Round-trip it through SyncCache like
the other sync caches (RawTxHex/VerifiedAt/BlockHeaders).
2026-07-19 12:16:00 +02:00
25 changed files with 817 additions and 68 deletions

No files matched your search

+116
View File
@@ -5,6 +5,122 @@ Technical changelog for PalladiumWallet. Format loosely follows
by subsystem rather than strictly by date, since `0.9.0` is the first by subsystem rather than strictly by date, since `0.9.0` is the first
release and covers the full history from the initial commit. release and covers the full history from the initial commit.
## [1.1.0] — 2026-07-19
Adds a pure address-only watch-only mode (Core + CLI + App wizard + Send
PSBT export), makes SPV sync render balance/history progressively instead
of blocking on full Merkle verification, and fixes several Android
sync-reconnect bugs found by testing the previous fix on a large wallet.
### Added
- Pure watch-only wallets from one or more plain addresses, no extended
key or private key material at all (unlike existing xpub/WIF imports,
which can still derive/hold key material): `WalletDocument.WatchAddresses`
+ `WalletLoader.NewFromAddresses`, `ScriptKind` inferred from the address
via `DerivationPaths.KindFor`, CLI `restore-address` command, and a
matching setup-wizard step. `TransactionFactory` already refused to sign
for any `IsWatchOnly` account, so the new address-only accounts inherit
that guarantee for free.
- Send flow: base64 PSBT export box + copy button and a visible warning
banner for watch-only accounts, so the unsigned PSBT built from a
watch-only wallet can actually be taken elsewhere to sign (previously
only the CLI printed it).
- Chinese (Simplified) as a 7th UI language (`Loc.Strings`/`Languages`);
the Settings language picker is a hand-written `RadioButton` list, not
generated from `Loc.Languages`, so `IsLangZh` was added to
`MainWindowViewModel.Settings.cs` and `MainView.axaml` too.
- New mainnet checkpoint at height 475124 (`ChainProfiles`).
### Changed
- SPV sync now renders balance/history as soon as transaction downloads
finish instead of blocking on every historical Merkle proof — critical
on mobile, where proof-checking can take much longer than the download.
Proofs keep verifying in the background and each transaction's
`Verified` flag catches up progressively; header ranges are fetched in
batches (`blockchain.block.headers`) instead of one call per header.
Coin selection (`UtxoSpendability.IsSpendable`) still refuses to spend a
UTXO until its Merkle proof is actually checked, regardless of
confirmation count — a server fabricating a confirmed balance can get it
displayed early but never spent before the forgery is caught. The disk
cache only ever persists the fully-verified end state. UI surfaces the
new `PendingVerificationSats`/`SpendableSats` split with a
"verifying..." badge.
- `ElectrumClient`'s in-flight request cap (`MaxInFlight`, previously a
hardcoded 32) is now an optional `ConnectAsync` parameter, since
different indexing servers tolerate different concurrency before
throttling.
### Performance
- Checkpoint-anchoring state (`_anchoredUpTo`) is now persisted across
sync sessions via `SyncCache` instead of being re-walked and
re-verified from scratch on every app restart, even when the header
bytes were already cached on disk — this dominated reconnect time on
large wallets.
### Fixed
- `TransactionFactory.Build`: sending a large amount from a wallet with
many small UTXOs could produce a transaction over the standard 100 KvB
relay limit, previously surfaced only as a cryptic
`Transaction's size is too high` error after everything else had
already succeeded. UTXOs are now ordered largest-first with a binary
search for the smallest spendable prefix, naturally preferring big
coins over dust; NBitcoin's own oversized-selection case is now
recognized and translated into a clear, actionable error instead of
being read as "insufficient funds".
- Android: a connection killed silently while the phone was locked (Doze,
radio suspend, NAT timeout) still reported `IsConnected == true`
because `TcpClient.Connected` only reflects the last known socket
state, and the keep-alive ping's failure was swallowed by an empty
catch — sync kept retrying on a dead socket instead of reconnecting.
Fixed across two passes:
- A failed keep-alive ping now tears down the client and reconnects;
`OnPause`/`OnResume` on the Android activity force an immediate
health check on resume instead of waiting for the 20s timer (itself
liable to be suspended during Doze).
- The keep-alive ping had no timeout, so a half-open TCP connection
(the common outcome of a longer Doze suspend) left it awaiting a
response that never arrives, so the teardown path was never reached
— bounded to 8s, plus a re-entrancy guard against overlapping ticks.
- Resume checking bailed out whenever a sync was already in progress,
leaving a lock/unlock during an active sync hung indefinitely; it now
cancels the stuck sync and tears down the dead client instead.
- `WalletSynchronizer.ExportCaches` persisted raw transaction bytes only
for already-verified transactions, discarding anything downloaded but
not yet proof-verified when a sync was interrupted — forcing a full
re-download on every resume of a large wallet. Confirmed txids are
now tracked at download time, independent of verification status.
- Wizard/overlay `TextBox`es (wizard steps, private-key prompt, wallet
info overlay) shrank the whole panel when clicked into empty: their
`HorizontalAlignment="Center"` + `MaxWidth` containers sized from
content `DesiredSize`, and `PlaceholderText` only contributes to that
measurement while empty and unfocused. Switched to
`HorizontalAlignment="Stretch"`, which sizes from the available arrange
rect (clamped by `MaxWidth`) regardless of focus/placeholder state.
- Help overlay's Donate tab is now gated behind `IsWalletOpen`, like the
rest of the wallet-only UI — it requires an open wallet to send from,
so showing it earlier was a dead end.
### Documentation
- `USERGUIDE.md`: documents why initial sync scales with transaction
count rather than wallet age (one Merkle-proof round trip per confirmed
transaction, no batching in the Electrum-style protocol), why later
syncs are fast (cache persists proofs/headers/anchoring state), and
warns against using this wallet as a mining payout address (many small
transactions measurably slow sync).
- `SECURITY.md`: documents address-only watch-only wallets, and adds
multisig to the explicit "known limitations" list (unsupported —
derivation for it throws, not just unimplemented UI).
- `README.md` reconciled with current repo state: 7 UI languages (was
6, missing Chinese Simplified), watch-only described as xpub *and*
address-only (was xpub-only), multisig no longer overclaimed as a
working PSBT flow, CLI quick-reference includes `restore-address` and
`servers`, links the new `USERGUIDE.md`.
## [1.0.0] — 2026-07-09 ## [1.0.0] — 2026-07-09
First stable release. Closes the last open security gap from 0.9.x (header First stable release. Closes the last open security gap from 0.9.x (header
+14 -6
View File
@@ -8,11 +8,11 @@ Unlike generic wallets adapted to many coins, Palladium Wallet is designed aroun
- **Lightweight SPV**: syncs against an indexing server (ElectrumX-like protocol) without downloading the full chain. - **Lightweight SPV**: syncs against an indexing server (ElectrumX-like protocol) without downloading the full chain.
- **Security**: seed and private keys encrypted on disk (AES-GCM, PBKDF2-SHA512), never in plaintext in logs or on the wire; every server response is validated with Merkle proofs + checkpoints. - **Security**: seed and private keys encrypted on disk (AES-GCM, PBKDF2-SHA512), never in plaintext in logs or on the wire; every server response is validated with Merkle proofs + checkpoints.
- **HD wallet** (BIP39/BIP32), SegWit/wrapped/legacy addresses, watch-only from xpub. - **HD wallet** (BIP39/BIP32), SegWit/wrapped/legacy addresses, watch-only from xpub or from plain addresses (no key material at all).
- **PSBT-centric**: signing flows go through PSBT (offline / air-gapped / multisig). - **PSBT-centric**: signing flows go through PSBT (offline / air-gapped); watch-only wallets export an unsigned PSBT for offline signing. Multisig script kinds are defined in the network profile but not yet implemented (planned, see `Core/Crypto/DerivationPaths.cs`).
- **Multi-network**: mainnet, testnet, regtest. - **Multi-network**: mainnet, testnet, regtest.
- **Cross-platform**: desktop (Windows/Linux) and Android share one Avalonia UI; a **CLI** runs on the same core. - **Cross-platform**: desktop (Windows/Linux) and Android share one Avalonia UI; a **CLI** runs on the same core.
- **Multilingual**: Italian, English, Spanish, French, Portuguese, German. - **Multilingual**: Italian, English, Spanish, French, Portuguese, German, Chinese (Simplified).
## Architecture ## Architecture
@@ -331,6 +331,9 @@ existing AVD, so create one first (step 3). Point it at the emulator binary:
## User guide (quick) ## User guide (quick)
A condensed overview follows; for the complete, exhaustive walkthrough (every screen, every
validation rule, troubleshooting) see [USERGUIDE.md](USERGUIDE.md).
### First launch ### First launch
1. On first launch (desktop), choose **where to store data** (wallet, configuration, certificates) — the default path or a folder of your choice. On Android this step is skipped: data lives in the app's private sandbox. 1. On first launch (desktop), choose **where to store data** (wallet, configuration, certificates) — the default path or a folder of your choice. On Android this step is skipped: data lives in the app's private sandbox.
2. Create a new wallet, restore from seed, or open one of the wallets already in your data folder. 2. Create a new wallet, restore from seed, or open one of the wallets already in your data folder.
@@ -360,15 +363,20 @@ existing AVD, so create one first (step 3). Point it at the emulator binary:
### CLI in brief ### CLI in brief
```bash ```bash
# Wallet # Wallet
dotnet run --project src/Cli -- create [--words 12|24] [--kind segwit|wrapped|legacy] [--net mainnet|testnet|regtest] [--password P] dotnet run --project src/Cli -- create [--words 12|24] [--kind segwit|wrapped|legacy] [--net mainnet|testnet|regtest] [--password P]
dotnet run --project src/Cli -- restore "<mnemonic>" [...] dotnet run --project src/Cli -- restore "<mnemonic>" [...]
dotnet run --project src/Cli -- info [--net ...] [--password P] dotnet run --project src/Cli -- restore-xpub <slip132-key> [--net ...] [--password P]
dotnet run --project src/Cli -- restore-address <addr1,addr2,...> [--net ...] [--password P]
dotnet run --project src/Cli -- info [--net ...] [--password P]
# Network # Network
dotnet run --project src/Cli -- sync [--server host[:port]] [--ssl] dotnet run --project src/Cli -- sync [--server host[:port]] [--ssl]
dotnet run --project src/Cli -- send --to ADDRESS (--amount X | --all) [--feerate sat/vB] [--broadcast] dotnet run --project src/Cli -- send --to ADDRESS (--amount X | --all) [--feerate sat/vB] [--broadcast]
dotnet run --project src/Cli -- servers [--discover]
``` ```
The default wallet file is `~/.palladium-wallet/<network>/wallets/default.wallet.json` (override with `--file`). The default wallet file is `~/.palladium-wallet/<network>/wallets/default.wallet.json` (override with `--file`).
Run without arguments for the full command list (also covers `newseed`, `addresses`, `reset-certs`);
see [USERGUIDE.md §17](USERGUIDE.md#17-command-line-interface-cli) for complete flag reference.
--- ---
+5 -2
View File
@@ -62,7 +62,7 @@ a sync, never a partial one, so no unverified data survives a restart.
- The BIP39 mnemonic and derived private keys exist only in process memory after unlock - 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 - 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 - 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 - Watch-only wallets (`restore-xpub`, or `restore-address` for pure address imports) hold no private keys and cannot sign transactions; `TransactionFactory` only calls `AddKeys`/signs when the account reports a private key, so an address-only import can never produce a signed transaction, only an exportable unsigned PSBT
--- ---
@@ -84,7 +84,7 @@ Connections to the indexing server use TOFU (Trust On First Use): the server's T
## Backup ## 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. 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 or from a plain address), the private keys must be kept in a separate cold storage device.
--- ---
@@ -108,3 +108,6 @@ This is a complement to, not a substitute for, independent human or third-party
- No coin control (automatic UTXO selection only) - 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 RBF/CPFP UI (RBF flag is set on all transactions, but fee bumping is not exposed)
- No Lightning Network support - No Lightning Network support
- No multisig (M-of-N) wallets: the network profile defines multisig SLIP-132 header
variants, but derivation for them is not implemented — attempting to use one throws
rather than silently producing an insecure/incorrect wallet
+24 -1
View File
@@ -578,6 +578,29 @@ If the server is overloaded (busy responses), the wallet retries automatically u
times with increasing back-off — a large wallet's first sync may take a little while, but it times with increasing back-off — a large wallet's first sync may take a little while, but it
resumes from the cache instead of restarting. resumes from the cache instead of restarting.
**First sync can take noticeably longer than later ones — this is expected.** Each confirmed
transaction requires its own Merkle-proof round trip to the indexing server
(`blockchain.transaction.get_merkle`, one request per transaction — the Electrum-style
protocol has no batched form of this call), plus, on mainnet, chaining the covering block
header back to the nearest hardcoded checkpoint. Sync time therefore scales with the number
of confirmed transactions in the wallet's history, not with wall-clock time since creation.
On **Android**, the first sync is typically slower still than on desktop for the same
wallet: mobile networks add higher round-trip latency and lower sustained throughput than a
desktop's wired/Wi-Fi connection, and every proof round trip pays that latency individually.
Every subsequent sync is fast: verified proofs, raw transaction bytes, downloaded block
headers, and the checkpoint hash-chain anchoring state are all persisted into the wallet
file's cache, so a resumed or later sync only fetches and verifies what changed since the
last one — even across an app restart.
**Do not use this wallet as a mining payout address.** Pool or solo mining payouts typically
arrive as many small, frequent transactions, and — because of the per-transaction Merkle
proof cost described above — sync time grows with transaction count, not balance. A wallet
whose history has accumulated **over 5,000 transactions** has been observed taking on the
order of a couple of minutes to fully synchronize even on a stable connection, with slower
networks (see the Android note above) pushing that further. If you mine, pay out to a wallet
purpose-built for high transaction volume (or one that lets you consolidate UTXOs
aggressively), and only move funds into Palladium Wallet in batches.
--- ---
## 13. Settings ## 13. Settings
@@ -818,7 +841,7 @@ Reset SSL certificates* — see
| Payment sent to me doesn't appear | Not yet synced/connected, or sender hasn't broadcast. | Check the connection indicator; mempool entries appear within seconds of broadcast when connected. | | Payment sent to me doesn't appear | Not yet synced/connected, or sender hasn't broadcast. | Check the connection indicator; mempool entries appear within seconds of broadcast when connected. |
| Update prompt at startup (*"Update available"*) | A newer GitHub release exists (checked once at startup, silently skipped offline). | *Download* opens the release page; *Dismiss* continues. Never enter your seed into anything but the wallet itself. | | Update prompt at startup (*"Update available"*) | A newer GitHub release exists (checked once at startup, silently skipped offline). | *Download* opens the release page; *Dismiss* continues. Never enter your seed into anything but the wallet itself. |
| Android: update apk refuses to install | Signature mismatch between builds. | Back up the seed **before** uninstalling; see [3.2](#32-android). | | Android: update apk refuses to install | Signature mismatch between builds. | Back up the seed **before** uninstalling; see [3.2](#32-android). |
| First sync is slow / server busy errors | Server throttling; the wallet retries automatically (up to 8 attempts, growing back-off). | Wait; progress is cached, so restarting resumes rather than repeats. | | First sync is slow / server busy errors | Server throttling (automatic retry, up to 8 attempts) and/or a large transaction history — sync time scales with transaction count, not balance, worse on mobile. | Wait; progress is cached, so restarting resumes rather than repeats. See [12.3](#123-what-synchronization-actually-does). Do not use this wallet for mining payouts (many small transactions). |
--- ---
+22
View File
@@ -4,6 +4,7 @@ using Android.Content;
using Android.Content.PM; using Android.Content.PM;
using Android.OS; using Android.OS;
using Avalonia.Android; using Avalonia.Android;
using AvaloniaApp = PalladiumWallet.App.App;
namespace PalladiumWallet.Mobile; namespace PalladiumWallet.Mobile;
@@ -17,6 +18,7 @@ public class MainActivity : AvaloniaMainActivity
internal const int ScanRequestCode = 9001; internal const int ScanRequestCode = 9001;
internal static TaskCompletionSource<string?>? ScanTcs; internal static TaskCompletionSource<string?>? ScanTcs;
internal static MainActivity? Current; internal static MainActivity? Current;
private bool _wasPaused;
protected override void OnCreate(Bundle? savedInstanceState) protected override void OnCreate(Bundle? savedInstanceState)
{ {
@@ -24,6 +26,26 @@ public class MainActivity : AvaloniaMainActivity
Current = this; Current = this;
} }
protected override void OnPause()
{
base.OnPause();
_wasPaused = true;
}
protected override void OnResume()
{
base.OnResume();
if (!_wasPaused) return;
_wasPaused = false;
// The TCP socket can die silently while the screen was off/locked (Doze,
// mobile radio suspend, NAT timeout) without the app ever observing the
// failure. Force an immediate health check instead of waiting for the next
// 20s keep-alive tick, which may itself have been suspended for longer than
// the lock.
if (AvaloniaApp.MainViewModel is { } vm)
_ = vm.CheckConnectionOnResumeAsync();
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent? data) protected override void OnActivityResult(int requestCode, Result resultCode, Intent? data)
{ {
base.OnActivityResult(requestCode, resultCode, data); base.OnActivityResult(requestCode, resultCode, data);
@@ -8,8 +8,8 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ApplicationId>io.github.davide3011.palladiumwallet</ApplicationId> <ApplicationId>io.github.davide3011.palladiumwallet</ApplicationId>
<!-- ApplicationVersion = versionCode (intero), ApplicationDisplayVersion = versionName --> <!-- ApplicationVersion = versionCode (intero), ApplicationDisplayVersion = versionName -->
<ApplicationVersion>3</ApplicationVersion> <ApplicationVersion>4</ApplicationVersion>
<ApplicationDisplayVersion>1.0.0</ApplicationDisplayVersion> <ApplicationDisplayVersion>1.1.0</ApplicationDisplayVersion>
<AndroidPackageFormat>apk</AndroidPackageFormat> <AndroidPackageFormat>apk</AndroidPackageFormat>
<!-- Includi le assembly .NET DENTRO l'apk: senza, in Debug si usa il Fast <!-- Includi le assembly .NET DENTRO l'apk: senza, in Debug si usa il Fast
Deployment (assembly spinte via adb da `dotnet run`) e un apk installato Deployment (assembly spinte via adb da `dotnet run`) e un apk installato
+5
View File
@@ -8,6 +8,10 @@ namespace PalladiumWallet.App;
public partial class App : Application public partial class App : Application
{ {
/// <summary>Set once the single ViewModel is created; lets platform heads (e.g. the
/// Android activity) reach it for lifecycle events without a second instance.</summary>
public static MainWindowViewModel? MainViewModel { get; private set; }
public override void Initialize() public override void Initialize()
{ {
AvaloniaXamlLoader.Load(this); AvaloniaXamlLoader.Load(this);
@@ -16,6 +20,7 @@ public partial class App : Application
public override void OnFrameworkInitializationCompleted() public override void OnFrameworkInitializationCompleted()
{ {
var vm = new MainWindowViewModel(); var vm = new MainWindowViewModel();
MainViewModel = vm;
// Desktop (Windows/Linux): classic window. Mobile (Android): single // Desktop (Windows/Linux): classic window. Mobile (Android): single
// view. Same shared UI (MainView) and same ViewModel. // view. Same shared UI (MainView) and same ViewModel.
+17
View File
@@ -102,6 +102,7 @@ public sealed class Loc
["wiz.restore.btn"] = ["Ripristina da seed", "Restore from seed", "Restaurar desde semilla", "Restaurer depuis la graine", "Restaurar da semente", "Aus Seed wiederherstellen", "从种子恢复"], ["wiz.restore.btn"] = ["Ripristina da seed", "Restore from seed", "Restaurar desde semilla", "Restaurer depuis la graine", "Restaurar da semente", "Aus Seed wiederherstellen", "从种子恢复"],
["wiz.importxkey.btn"] = ["Importa xpub / xprv", "Import xpub / xprv", "Importar xpub / xprv", "Importer xpub / xprv", "Importar xpub / xprv", "xpub / xprv importieren", "导入 xpub / xprv"], ["wiz.importxkey.btn"] = ["Importa xpub / xprv", "Import xpub / xprv", "Importar xpub / xprv", "Importer xpub / xprv", "Importar xpub / xprv", "xpub / xprv importieren", "导入 xpub / xprv"],
["wiz.importwif.btn"] = ["Importa chiave WIF", "Import WIF key", "Importar clave WIF", "Importer clé WIF", "Importar chave WIF", "WIF-Schlüssel importieren", "导入 WIF 密钥"], ["wiz.importwif.btn"] = ["Importa chiave WIF", "Import WIF key", "Importar clave WIF", "Importer clé WIF", "Importar chave WIF", "WIF-Schlüssel importieren", "导入 WIF 密钥"],
["wiz.importaddress.btn"] = ["Importa indirizzo (sola lettura)", "Import address (watch-only)", "Importar dirección (solo lectura)", "Importer une adresse (lecture seule)", "Importar endereço (somente leitura)", "Adresse importieren (nur lesend)", "导入地址(仅观察)"],
["wiz.open.title"] = ["Apri il wallet", "Open the wallet", "Abrir el wallet", "Ouvrir le wallet", "Abrir a carteira", "Wallet öffnen", "打开钱包"], ["wiz.open.title"] = ["Apri il wallet", "Open the wallet", "Abrir el wallet", "Ouvrir le wallet", "Abrir a carteira", "Wallet öffnen", "打开钱包"],
["wiz.open.placeholder"] = ["Password del file (vuoto se non impostata)", "File password (empty if not set)", "Contraseña del archivo (vacío si no establecida)", "Mot de passe du fichier (vide si non défini)", "Senha do arquivo (vazio se não definida)", "Dateipasswort (leer lassen, wenn nicht gesetzt)", "文件密码(未设置则留空)"], ["wiz.open.placeholder"] = ["Password del file (vuoto se non impostata)", "File password (empty if not set)", "Contraseña del archivo (vacío si no establecida)", "Mot de passe du fichier (vide si non défini)", "Senha do arquivo (vazio se não definida)", "Dateipasswort (leer lassen, wenn nicht gesetzt)", "文件密码(未设置则留空)"],
["wiz.open.ok"] = ["Apri", "Open", "Abrir", "Ouvrir", "Abrir", "Öffnen", "打开"], ["wiz.open.ok"] = ["Apri", "Open", "Abrir", "Ouvrir", "Abrir", "Öffnen", "打开"],
@@ -172,12 +173,24 @@ public sealed class Loc
"Fügen Sie einen oder mehrere WIF-Schlüssel ein (einer pro Zeile). Sie können mehrere Schlüssel importieren, um mehrere Adressen mit demselben Wallet zu verwalten.", "Fügen Sie einen oder mehrere WIF-Schlüssel ein (einer pro Zeile). Sie können mehrere Schlüssel importieren, um mehrere Adressen mit demselben Wallet zu verwalten.",
"粘贴一个或多个 WIF 密钥(每行一个)。您可以导入多个密钥,用同一个钱包控制多个地址。"], "粘贴一个或多个 WIF 密钥(每行一个)。您可以导入多个密钥,用同一个钱包控制多个地址。"],
["wiz.importwif.placeholder"] = ["K… / L… / 5… (una chiave per riga)", "K… / L… / 5… (one key per line)", "K… / L… / 5… (una clave por línea)", "K… / L… / 5… (une clé par ligne)", "K… / L… / 5… (uma chave por linha)", "K… / L… / 5… (ein Schlüssel pro Zeile)", "K… / L… / 5…(每行一个密钥)"], ["wiz.importwif.placeholder"] = ["K… / L… / 5… (una chiave per riga)", "K… / L… / 5… (one key per line)", "K… / L… / 5… (una clave por línea)", "K… / L… / 5… (une clé par ligne)", "K… / L… / 5… (uma chave por linha)", "K… / L… / 5… (ein Schlüssel pro Zeile)", "K… / L… / 5…(每行一个密钥)"],
["wiz.importaddress.title"] = ["Importa indirizzi in sola lettura", "Import watch-only addresses", "Importar direcciones de solo lectura", "Importer des adresses en lecture seule", "Importar endereços somente leitura", "Nur-Lese-Adressen importieren", "导入仅观察地址"],
["wiz.importaddress.hint"] = [
"Incolla uno o più indirizzi (uno per riga). Nessuna chiave privata è coinvolta: potrai vedere saldo e cronologia ma non potrai mai firmare o inviare transazioni da questo wallet.",
"Paste one or more addresses (one per line). No private key is involved: you'll be able to see the balance and history but you can never sign or send transactions from this wallet.",
"Pega una o más direcciones (una por línea). No hay ninguna clave privada involucrada: podrás ver el saldo y el historial, pero nunca podrás firmar ni enviar transacciones desde este wallet.",
"Collez une ou plusieurs adresses (une par ligne). Aucune clé privée n'est impliquée : vous pourrez voir le solde et l'historique, mais vous ne pourrez jamais signer ni envoyer de transactions depuis ce wallet.",
"Cole um ou mais endereços (um por linha). Nenhuma chave privada está envolvida: você poderá ver o saldo e o histórico, mas nunca poderá assinar ou enviar transações a partir desta carteira.",
"Fügen Sie eine oder mehrere Adressen ein (eine pro Zeile). Es ist kein privater Schlüssel beteiligt: Sie können den Kontostand und den Verlauf sehen, aber nie Transaktionen aus diesem Wallet signieren oder senden.",
"粘贴一个或多个地址(每行一个)。不涉及任何私钥:您可以查看余额和历史记录,但永远无法从此钱包签名或发送交易。"],
["wiz.importaddress.placeholder"] = ["Indirizzo… (uno per riga)", "Address… (one per line)", "Dirección… (una por línea)", "Adresse… (une par ligne)", "Endereço… (um por linha)", "Adresse… (eine pro Zeile)", "地址…(每行一个)"],
// Import error messages // Import error messages
["msg.xkey.required"] = ["Incolla una chiave estesa (xpub/xprv o variante).", "Paste an extended key (xpub/xprv or variant).", "Pega una clave extendida (xpub/xprv o variante).", "Collez une clé étendue (xpub/xprv ou variante).", "Cole uma chave estendida (xpub/xprv ou variante).", "Fügen Sie einen erweiterten Schlüssel ein (xpub/xprv oder Variante).", "请粘贴扩展密钥(xpub/xprv 或其变体)。"], ["msg.xkey.required"] = ["Incolla una chiave estesa (xpub/xprv o variante).", "Paste an extended key (xpub/xprv or variant).", "Pega una clave extendida (xpub/xprv o variante).", "Collez une clé étendue (xpub/xprv ou variante).", "Cole uma chave estendida (xpub/xprv ou variante).", "Fügen Sie einen erweiterten Schlüssel ein (xpub/xprv oder Variante).", "请粘贴扩展密钥(xpub/xprv 或其变体)。"],
["msg.xkey.invalid"] = ["Chiave estesa non riconosciuta per questa rete.", "Extended key not recognised for this network.", "Clave extendida no reconocida para esta red.", "Clé étendue non reconnue pour ce réseau.", "Chave estendida não reconhecida para esta rede.", "Erweiterter Schlüssel für dieses Netzwerk nicht erkannt.", "此网络无法识别该扩展密钥。"], ["msg.xkey.invalid"] = ["Chiave estesa non riconosciuta per questa rete.", "Extended key not recognised for this network.", "Clave extendida no reconocida para esta red.", "Clé étendue non reconnue pour ce réseau.", "Chave estendida não reconhecida para esta rede.", "Erweiterter Schlüssel für dieses Netzwerk nicht erkannt.", "此网络无法识别该扩展密钥。"],
["msg.wif.required"] = ["Incolla almeno una chiave WIF.", "Paste at least one WIF key.", "Pega al menos una clave WIF.", "Collez au moins une clé WIF.", "Cole pelo menos uma chave WIF.", "Fügen Sie mindestens einen WIF-Schlüssel ein.", "请至少粘贴一个 WIF 密钥。"], ["msg.wif.required"] = ["Incolla almeno una chiave WIF.", "Paste at least one WIF key.", "Pega al menos una clave WIF.", "Collez au moins une clé WIF.", "Cole pelo menos uma chave WIF.", "Fügen Sie mindestens einen WIF-Schlüssel ein.", "请至少粘贴一个 WIF 密钥。"],
["msg.wif.invalid"] = ["Chiave WIF non valida per questa rete.", "WIF key not valid for this network.", "Clave WIF no válida para esta red.", "Clé WIF invalide pour ce réseau.", "Chave WIF inválida para esta rede.", "WIF-Schlüssel für dieses Netzwerk ungültig.", "该 WIF 密钥对此网络无效。"], ["msg.wif.invalid"] = ["Chiave WIF non valida per questa rete.", "WIF key not valid for this network.", "Clave WIF no válida para esta red.", "Clé WIF invalide pour ce réseau.", "Chave WIF inválida para esta rede.", "WIF-Schlüssel für dieses Netzwerk ungültig.", "该 WIF 密钥对此网络无效。"],
["msg.address.required"] = ["Incolla almeno un indirizzo.", "Paste at least one address.", "Pega al menos una dirección.", "Collez au moins une adresse.", "Cole pelo menos um endereço.", "Fügen Sie mindestens eine Adresse ein.", "请至少粘贴一个地址。"],
["msg.address.invalid"] = ["Indirizzo non valido per questa rete.", "Address not valid for this network.", "Dirección no válida para esta red.", "Adresse invalide pour ce réseau.", "Endereço inválido para esta rede.", "Adresse für dieses Netzwerk ungültig.", "该地址对此网络无效。"],
// Wallet panel // Wallet panel
["wallet.close"] = ["Chiudi wallet", "Close wallet", "Cerrar wallet", "Fermer le wallet", "Fechar carteira", "Wallet schließen", "关闭钱包"], ["wallet.close"] = ["Chiudi wallet", "Close wallet", "Cerrar wallet", "Fermer le wallet", "Fechar carteira", "Wallet schließen", "关闭钱包"],
@@ -262,6 +275,10 @@ public sealed class Loc
["send.sect.recipient"] = ["Destinatario", "Recipient", "Destinatario", "Destinataire", "Destinatário", "Empfänger", "收款人"], ["send.sect.recipient"] = ["Destinatario", "Recipient", "Destinatario", "Destinataire", "Destinatário", "Empfänger", "收款人"],
["send.sect.amount"] = ["Importo e commissione", "Amount & fee", "Importe y comisión", "Montant et frais", "Valor e taxa", "Betrag & Gebühr", "金额与手续费"], ["send.sect.amount"] = ["Importo e commissione", "Amount & fee", "Importe y comisión", "Montant et frais", "Valor e taxa", "Betrag & Gebühr", "金额与手续费"],
["send.summary"] = ["Riepilogo", "Summary", "Resumen", "Résumé", "Resumo", "Zusammenfassung", "摘要"], ["send.summary"] = ["Riepilogo", "Summary", "Resumen", "Résumé", "Resumo", "Zusammenfassung", "摘要"],
["send.psbt.label"] = ["PSBT non firmata (base64) — da firmare altrove", "Unsigned PSBT (base64) — sign it elsewhere", "PSBT sin firmar (base64) — fírmala en otro lugar", "PSBT non signée (base64) — à signer ailleurs", "PSBT não assinada (base64) — assine em outro lugar", "Unsignierte PSBT (base64) — anderswo signieren", "未签名 PSBT(base64)— 请在别处签名"],
["send.psbt.copy"] = ["Copia PSBT", "Copy PSBT", "Copiar PSBT", "Copier la PSBT", "Copiar PSBT", "PSBT kopieren", "复制 PSBT"],
["send.watchonly.hint"] = ["Wallet in sola lettura: non può firmare. Esporta la PSBT e firmala con un wallet che possiede le chiavi.", "Watch-only wallet: it cannot sign. Export the PSBT and sign it with a wallet that holds the keys.", "Wallet de solo lectura: no puede firmar. Exporta la PSBT y fírmala con un wallet que tenga las claves.", "Wallet en lecture seule : il ne peut pas signer. Exportez la PSBT et signez-la avec un wallet possédant les clés.", "Carteira somente leitura: não pode assinar. Exporte a PSBT e assine-a com uma carteira que tenha as chaves.", "Nur-Lese-Wallet: kann nicht signieren. Exportieren Sie die PSBT und signieren Sie sie mit einem Wallet, das die Schlüssel besitzt.", "仅观察钱包:无法签名。请导出 PSBT 并用持有密钥的钱包签名。"],
["psbt.copied"] = ["PSBT copiata negli appunti", "PSBT copied to clipboard", "PSBT copiada al portapapeles", "PSBT copiée dans le presse-papiers", "PSBT copiada para a área de transferência", "PSBT in die Zwischenablage kopiert", "PSBT 已复制到剪贴板"],
["receive.your.address"] = ["Il tuo indirizzo", "Your address", "Tu dirección", "Votre adresse", "Seu endereço", "Deine Adresse", "您的地址"], ["receive.your.address"] = ["Il tuo indirizzo", "Your address", "Tu dirección", "Votre adresse", "Seu endereço", "Deine Adresse", "您的地址"],
// Wallet info overlay // Wallet info overlay
+1 -1
View File
@@ -6,7 +6,7 @@
<TargetFramework>net10.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<!-- Versione dell'applicazione: unico punto da modificare. Compare nel <!-- Versione dell'applicazione: unico punto da modificare. Compare nel
titolo della finestra ed è incisa nei binari pubblicati. --> titolo della finestra ed è incisa nei binari pubblicati. -->
<Version>1.0.0</Version> <Version>1.1.0</Version>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault> <AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
</PropertyGroup> </PropertyGroup>
@@ -31,6 +31,14 @@ public partial class MainWindowViewModel
[ObservableProperty] [ObservableProperty]
private bool hasPendingSend; private bool hasPendingSend;
[ObservableProperty]
private string pendingPsbtBase64 = "";
/// <summary>True when the open account cannot sign — Send only prepares an unsigned PSBT to export.</summary>
public bool IsWatchOnlyAccount => _account?.IsWatchOnly ?? false;
public void NotifyPsbtCopied() => StatusMessage = Loc.Tr("psbt.copied");
[RelayCommand] [RelayCommand]
private async Task ScanQr() private async Task ScanQr()
{ {
@@ -81,11 +89,13 @@ public partial class MainWindowViewModel
$"({_pendingSend.Transaction.GetVirtualSize()} vB)" + $"({_pendingSend.Transaction.GetVirtualSize()} vB)" +
(_pendingSend.Signed ? "" : Loc.Tr("msg.unsigned.watchonly")); (_pendingSend.Signed ? "" : Loc.Tr("msg.unsigned.watchonly"));
HasPendingSend = _pendingSend.Signed; HasPendingSend = _pendingSend.Signed;
PendingPsbtBase64 = _pendingSend.Signed ? "" : _pendingSend.Psbt.ToBase64();
} }
catch (Exception ex) catch (Exception ex)
{ {
_pendingSend = null; _pendingSend = null;
HasPendingSend = false; HasPendingSend = false;
PendingPsbtBase64 = "";
SendPreview = $"{Loc.Tr("msg.error")}: {DescribeError(ex)}"; SendPreview = $"{Loc.Tr("msg.error")}: {DescribeError(ex)}";
} }
await Task.CompletedTask; await Task.CompletedTask;
@@ -103,6 +113,7 @@ public partial class MainWindowViewModel
SendTo = SendAmount = ""; SendTo = SendAmount = "";
_pendingSend = null; _pendingSend = null;
HasPendingSend = false; HasPendingSend = false;
PendingPsbtBase64 = "";
await ConnectAndSync(); await ConnectAndSync();
} }
catch (Exception ex) catch (Exception ex)
+33 -11
View File
@@ -271,7 +271,8 @@ public partial class MainWindowViewModel
_doc.Cache?.BlockHeaders, _doc.Cache?.BlockHeaders,
_doc.Cache?.NextReceiveIndex ?? 0, _doc.Cache?.NextReceiveIndex ?? 0,
_doc.Cache?.NextChangeIndex ?? 0, _doc.Cache?.NextChangeIndex ?? 0,
net); net,
_doc.Cache?.AnchoredUpTo);
_synchronizer.Progress += msg => Dispatcher.UIThread.Post(() => StatusMessage = msg); _synchronizer.Progress += msg => Dispatcher.UIThread.Post(() => StatusMessage = msg);
// Progressive verification (§7.4): the wallet becomes usable as soon as // Progressive verification (§7.4): the wallet becomes usable as soon as
// transaction downloads finish, without waiting for every historical Merkle // transaction downloads finish, without waiting for every historical Merkle
@@ -289,15 +290,19 @@ public partial class MainWindowViewModel
// Off the UI thread: sync does heavy CPU work (LINQ over thousands of // Off the UI thread: sync does heavy CPU work (LINQ over thousands of
// cached txs/UTXOs) and blocking JSON/disk I/O between awaits, negligible // cached txs/UTXOs) and blocking JSON/disk I/O between awaits, negligible
// on desktop but enough to freeze the UI (ANR) on slower mobile hardware. // on desktop but enough to freeze the UI (ANR) on slower mobile hardware.
var (result, rawHex, verifiedAt, blockHeaders) = await Task.Run(async () => var (result, rawHex, verifiedAt, blockHeaders, anchoredUpTo) = await Task.Run(async () =>
{ {
var r = await _synchronizer.SyncOnceAsync(ct); var r = await _synchronizer.SyncOnceAsync(ct);
var caches = _synchronizer.ExportCaches(PalladiumNetworks.For(_account.Profile.Kind)); var caches = _synchronizer.ExportCaches(PalladiumNetworks.For(_account.Profile.Kind));
return (r, caches.RawTxHex, caches.VerifiedAt, caches.BlockHeaders); return (r, caches.RawTxHex, caches.VerifiedAt, caches.BlockHeaders, caches.AnchoredUpTo);
}, ct); }, ct);
_lastTransactions = result.Transactions; _lastTransactions = result.Transactions;
var cache = new SyncCache { RawTxHex = rawHex, VerifiedAt = verifiedAt, BlockHeaders = blockHeaders }; var cache = new SyncCache
{
RawTxHex = rawHex, VerifiedAt = verifiedAt, BlockHeaders = blockHeaders,
AnchoredUpTo = anchoredUpTo,
};
FillDisplayFields(cache, result); FillDisplayFields(cache, result);
_doc.Cache = cache; _doc.Cache = cache;
await WalletStore.SaveAsync(_doc, _walletPath!, _password); await WalletStore.SaveAsync(_doc, _walletPath!, _password);
@@ -309,11 +314,13 @@ public partial class MainWindowViewModel
} }
catch (OperationCanceledException) catch (OperationCanceledException)
{ {
// Intentional cancellation due to server change request — not an error. // Intentional cancellation: a server change request, or CheckConnectionOnResumeAsync
// recovering a sync stuck on a socket that died while the app was suspended
// (_resumeRecovering) — neither is an error the user needs to see as one.
cancelled = true; cancelled = true;
IsConnected = false; IsConnected = false;
ConnectionStatus = Loc.Tr("conn.none"); ConnectionStatus = _resumeRecovering ? Loc.Tr("conn.reconnecting") : Loc.Tr("conn.none");
ConnectionStatusShort = Loc.Tr("conn.none"); ConnectionStatusShort = _resumeRecovering ? Loc.Tr("conn.reconnecting") : Loc.Tr("conn.none");
StatusMessage = ""; StatusMessage = "";
} }
catch (CertificatePinMismatchException ex) catch (CertificatePinMismatchException ex)
@@ -326,9 +333,22 @@ public partial class MainWindowViewModel
catch (Exception ex) catch (Exception ex)
{ {
IsConnected = _client?.IsConnected == true; IsConnected = _client?.IsConnected == true;
ConnectionStatus = IsConnected ? ConnectionStatus : Loc.Tr("conn.none"); if (_resumeRecovering && !IsConnected)
ConnectionStatusShort = IsConnected ? Loc.Tr("conn.connectedto") : Loc.Tr("conn.none"); {
StatusMessage = $"{Loc.Tr("msg.error")}: {DescribeError(ex)}"; // We tore the connection down ourselves (see CheckConnectionOnResumeAsync);
// whether that surfaces here as a cancellation or as a transport exception
// is a race, not a real failure — show "reconnecting" and restart right away
// instead of a scary error message and a wait for the next keep-alive tick.
cancelled = true;
ConnectionStatus = Loc.Tr("conn.reconnecting");
ConnectionStatusShort = Loc.Tr("conn.reconnecting");
}
else
{
ConnectionStatus = IsConnected ? ConnectionStatus : Loc.Tr("conn.none");
ConnectionStatusShort = IsConnected ? Loc.Tr("conn.connectedto") : Loc.Tr("conn.none");
StatusMessage = $"{Loc.Tr("msg.error")}: {DescribeError(ex)}";
}
if (_account is not null) if (_account is not null)
{ {
_syncFailed = true; _syncFailed = true;
@@ -340,6 +360,7 @@ public partial class MainWindowViewModel
finally finally
{ {
IsSyncing = false; IsSyncing = false;
_resumeRecovering = false;
} }
// If cancelled due to a server change, restart immediately with the new server. // If cancelled due to a server change, restart immediately with the new server.
@@ -493,12 +514,13 @@ public partial class MainWindowViewModel
try try
{ {
var net = PalladiumNetworks.For(_account.Profile.Kind); var net = PalladiumNetworks.For(_account.Profile.Kind);
var (rawHex, verifiedAt, blockHeaders) = _synchronizer.ExportCaches(net); var (rawHex, verifiedAt, blockHeaders, anchoredUpTo) = _synchronizer.ExportCaches(net);
if (rawHex.Count == 0 && verifiedAt.Count == 0) if (rawHex.Count == 0 && verifiedAt.Count == 0)
return; return;
(_doc.Cache ??= new SyncCache()).RawTxHex = rawHex; (_doc.Cache ??= new SyncCache()).RawTxHex = rawHex;
_doc.Cache.VerifiedAt = verifiedAt; _doc.Cache.VerifiedAt = verifiedAt;
_doc.Cache.BlockHeaders = blockHeaders; _doc.Cache.BlockHeaders = blockHeaders;
_doc.Cache.AnchoredUpTo = anchoredUpTo;
WalletStore.Save(_doc, _walletPath, _password); WalletStore.Save(_doc, _walletPath, _password);
} }
catch { /* non-fatal: the next full save will recover */ } catch { /* non-fatal: the next full save will recover */ }
@@ -27,9 +27,10 @@ public partial class MainWindowViewModel
public const string StepScriptType = "script-type"; public const string StepScriptType = "script-type";
public const string StepImportXkey = "import-xkey"; public const string StepImportXkey = "import-xkey";
public const string StepImportWif = "import-wif"; public const string StepImportWif = "import-wif";
public const string StepImportAddress = "import-address";
public const string StepPassword = "password"; public const string StepPassword = "password";
private enum WizardFlowKind { New, Restore, ImportXkey, ImportWif } private enum WizardFlowKind { New, Restore, ImportXkey, ImportWif, ImportAddress }
private WizardFlowKind _wizardFlow; private WizardFlowKind _wizardFlow;
[ObservableProperty] [ObservableProperty]
@@ -44,6 +45,7 @@ public partial class MainWindowViewModel
[NotifyPropertyChangedFor(nameof(IsStepScriptType))] [NotifyPropertyChangedFor(nameof(IsStepScriptType))]
[NotifyPropertyChangedFor(nameof(IsStepImportXkey))] [NotifyPropertyChangedFor(nameof(IsStepImportXkey))]
[NotifyPropertyChangedFor(nameof(IsStepImportWif))] [NotifyPropertyChangedFor(nameof(IsStepImportWif))]
[NotifyPropertyChangedFor(nameof(IsStepImportAddress))]
[NotifyPropertyChangedFor(nameof(IsStepPassword))] [NotifyPropertyChangedFor(nameof(IsStepPassword))]
private string setupStep = StepStart; private string setupStep = StepStart;
@@ -56,9 +58,10 @@ public partial class MainWindowViewModel
public bool IsStepWords => SetupStep == StepWords; public bool IsStepWords => SetupStep == StepWords;
public bool IsStepPassphrase => SetupStep == StepPassphrase; public bool IsStepPassphrase => SetupStep == StepPassphrase;
public bool IsStepScriptType => SetupStep == StepScriptType; public bool IsStepScriptType => SetupStep == StepScriptType;
public bool IsStepImportXkey => SetupStep == StepImportXkey; public bool IsStepImportXkey => SetupStep == StepImportXkey;
public bool IsStepImportWif => SetupStep == StepImportWif; public bool IsStepImportWif => SetupStep == StepImportWif;
public bool IsStepPassword => SetupStep == StepPassword; public bool IsStepImportAddress => SetupStep == StepImportAddress;
public bool IsStepPassword => SetupStep == StepPassword;
[ObservableProperty] [ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsLegacySelected))] [NotifyPropertyChangedFor(nameof(IsLegacySelected))]
@@ -85,6 +88,9 @@ public partial class MainWindowViewModel
[ObservableProperty] [ObservableProperty]
private string importWifInput = ""; private string importWifInput = "";
[ObservableProperty]
private string importAddressInput = "";
// Script type detected during xkey decoding (to display to the user) // Script type detected during xkey decoding (to display to the user)
[ObservableProperty] [ObservableProperty]
private string importXkeyDetectedKind = ""; private string importXkeyDetectedKind = "";
@@ -214,6 +220,15 @@ public partial class MainWindowViewModel
StatusMessage = ""; StatusMessage = "";
} }
[RelayCommand]
private void WizardStartImportAddress()
{
_wizardFlow = WizardFlowKind.ImportAddress;
ImportAddressInput = "";
SetupStep = StepImportAddress;
StatusMessage = "";
}
[RelayCommand] [RelayCommand]
private void WizardNextFromShowSeed() private void WizardNextFromShowSeed()
{ {
@@ -312,6 +327,35 @@ public partial class MainWindowViewModel
StatusMessage = ""; StatusMessage = "";
} }
[RelayCommand]
private void WizardNextFromImportAddress()
{
var addresses = ImportAddressInput.Split('\n',
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (addresses.Length == 0)
{
StatusMessage = Loc.Tr("msg.address.required");
return;
}
var network = PalladiumNetworks.For(Net);
foreach (var a in addresses)
{
try
{
_ = NBitcoin.BitcoinAddress.Create(a, network);
}
catch
{
StatusMessage = Loc.Tr("msg.address.invalid");
return;
}
}
PasswordInput = ConfirmPasswordInput = "";
EncryptWallet = true;
SetupStep = StepPassword;
StatusMessage = "";
}
[RelayCommand] [RelayCommand]
private void WizardNextFromScriptType() private void WizardNextFromScriptType()
{ {
@@ -327,11 +371,16 @@ public partial class MainWindowViewModel
SetupStep = SetupStep switch SetupStep = SetupStep switch
{ {
StepOpen => WalletList.Count > 1 ? StepChooseWallet : StepStart, StepOpen => WalletList.Count > 1 ? StepChooseWallet : StepStart,
StepChooseWallet or StepShowSeed or StepWords or StepImportXkey or StepImportWif => StepStart, StepChooseWallet or StepShowSeed or StepWords or StepImportXkey or StepImportWif or StepImportAddress => StepStart,
StepConfirmSeed => StepShowSeed, StepConfirmSeed => StepShowSeed,
StepPassphrase => _wizardFlow == WizardFlowKind.Restore ? StepWords : StepConfirmSeed, StepPassphrase => _wizardFlow == WizardFlowKind.Restore ? StepWords : StepConfirmSeed,
StepScriptType => _wizardFlow == WizardFlowKind.ImportWif ? StepImportWif : StepPassphrase, StepScriptType => _wizardFlow == WizardFlowKind.ImportWif ? StepImportWif : StepPassphrase,
StepPassword => _wizardFlow == WizardFlowKind.ImportXkey ? StepImportXkey : StepScriptType, StepPassword => _wizardFlow switch
{
WizardFlowKind.ImportXkey => StepImportXkey,
WizardFlowKind.ImportAddress => StepImportAddress,
_ => StepScriptType,
},
_ => StepStart, _ => StepStart,
}; };
if (SetupStep == StepStart) if (SetupStep == StepStart)
@@ -391,6 +440,14 @@ public partial class MainWindowViewModel
(doc, account) = (d, a); (doc, account) = (d, a);
break; break;
} }
case WizardFlowKind.ImportAddress:
{
var addressLines = ImportAddressInput.Split('\n',
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var (d, a) = WalletLoader.NewFromAddresses(addressLines, Profile);
(doc, account) = (d, a);
break;
}
default: default:
{ {
var (d, a) = WalletLoader.NewFromMnemonic( var (d, a) = WalletLoader.NewFromMnemonic(
@@ -497,13 +554,14 @@ public partial class MainWindowViewModel
_walletPath = path; _walletPath = path;
_password = password; _password = password;
MnemonicInput = ConfirmMnemonicInput = PassphraseInput = PasswordInput = ConfirmPasswordInput = WalletNameInput = ""; MnemonicInput = ConfirmMnemonicInput = PassphraseInput = PasswordInput = ConfirmPasswordInput = WalletNameInput = "";
ImportXkeyInput = ImportWifInput = ImportXkeyDetectedKind = ""; ImportXkeyInput = ImportWifInput = ImportAddressInput = ImportXkeyDetectedKind = "";
SetupStep = StepStart; SetupStep = StepStart;
OnPropertyChanged(nameof(IsWatchOnlyAccount));
var walletKindTag = account switch var walletKindTag = account switch
{ {
ImportedKeyAccount => " · imported",
{ IsWatchOnly: true } => " · watch-only", { IsWatchOnly: true } => " · watch-only",
ImportedKeyAccount => " · imported",
_ => "" _ => ""
}; };
var pathTag = !string.IsNullOrEmpty(doc.AccountPath) ? $" · m/{doc.AccountPath}" : ""; var pathTag = !string.IsNullOrEmpty(doc.AccountPath) ? $" · m/{doc.AccountPath}" : "";
+87 -10
View File
@@ -77,6 +77,7 @@ public partial class MainWindowViewModel : ViewModelBase
// ---- keep-alive ---- // ---- keep-alive ----
private bool _autoReconnect; private bool _autoReconnect;
private bool _syncFailed; private bool _syncFailed;
private bool _resumeRecovering;
private readonly DispatcherTimer _keepAliveTimer; private readonly DispatcherTimer _keepAliveTimer;
// ---- server UI sync ---- // ---- server UI sync ----
@@ -161,28 +162,102 @@ public partial class MainWindowViewModel : ViewModelBase
_ = CheckForUpdatesAsync(); _ = CheckForUpdatesAsync();
} }
private bool _keepAliveRunning;
private async System.Threading.Tasks.Task KeepAliveTickAsync() private async System.Threading.Tasks.Task KeepAliveTickAsync()
{ {
if (IsSyncing) // Re-entrancy guard: without it, a ping stuck on a half-open socket (see
// below) would let every subsequent 20s tick pile up another concurrent
// ping/reconnect attempt on top of it.
if (IsSyncing || _keepAliveRunning)
return; return;
if (_client is { IsConnected: true }) _keepAliveRunning = true;
try
{ {
// If the wallet is open and the last sync failed, retry automatically. if (_client is { IsConnected: true } client)
if (_syncFailed && _account is not null)
{ {
// If the wallet is open and the last sync failed, retry automatically.
if (_syncFailed && _account is not null)
{
await ConnectAndSync();
return;
}
try
{
// A "half-open" TCP connection (remote end gone with no FIN/RST
// ever delivered — the common outcome of Android Doze/mobile-radio
// suspend killing the route silently) never fails the write, so
// PingAsync would otherwise await a response that never arrives.
// Bound it explicitly instead of relying on it to throw.
using var timeoutCts = new System.Threading.CancellationTokenSource(System.TimeSpan.FromSeconds(8));
await client.PingAsync(timeoutCts.Token);
}
catch
{
// TcpClient.Connected only reflects the last known socket state, so a
// connection killed silently while the app was suspended still reports
// IsConnected == true. A failed/timed-out ping is the only reliable
// signal here: tear the dead client down so the next tick reconnects
// instead of retrying forever on a dead socket.
await DisconnectAsync();
if (_autoReconnect)
{
ConnectionStatus = Loc.Tr("conn.reconnecting");
await ConnectAndSync();
}
}
}
else if (_autoReconnect)
{
ConnectionStatus = Loc.Tr("conn.reconnecting");
await ConnectAndSync(); await ConnectAndSync();
return;
} }
try { await _client.PingAsync(); }
catch { }
} }
else if (_autoReconnect) finally
{ {
ConnectionStatus = Loc.Tr("conn.reconnecting"); _keepAliveRunning = false;
await ConnectAndSync();
} }
} }
/// <summary>Forces an immediate connection health check, bypassing the 20s timer.
/// Called when the app resumes from background/lock screen, since the socket may
/// have died silently while suspended and the UI would otherwise show a stale
/// "connected" state until the next scheduled tick (or forever, if it never fires
/// during Doze).</summary>
public async System.Threading.Tasks.Task CheckConnectionOnResumeAsync()
{
if (IsSyncing)
{
// A sync in progress when the phone locked may be stuck awaiting a
// response on a socket that died silently while suspended (same
// half-open-TCP scenario as the keep-alive ping, but sync requests have
// no timeout of their own). Cancel it and tear the client down instead
// of leaving it hung forever. _resumeRecovering tells ConnectAndSync's
// error handling that this interruption is self-inflicted and expected,
// so it shows "reconnecting" and restarts immediately instead of
// flashing a scary error message and waiting for the next keep-alive tick.
_resumeRecovering = true;
ConnectionStatus = Loc.Tr("conn.reconnecting");
ConnectionStatusShort = Loc.Tr("conn.reconnecting");
_syncCts.Cancel();
// Deliberately not DisconnectAsync() here: it also nulls _synchronizer,
// which still holds whatever this sync already downloaded/verified (e.g.
// thousands of Merkle proofs on a large wallet). Nulling it before the
// cancelled ConnectAndSync unwinds would discard that progress, forcing a
// full restart instead of a resume. Only tear down the dead socket here;
// ConnectAndSync's own cancellation handling persists the partial cache
// (PersistPartialTxCache) before it recreates the synchronizer — same
// sequencing already used for the "server changed mid-sync" case.
if (_client is { } deadClient)
{
_client = null;
try { await deadClient.DisposeAsync(); } catch { }
}
return;
}
await KeepAliveTickAsync();
}
// ---- wallet lifecycle ---- // ---- wallet lifecycle ----
[RelayCommand] [RelayCommand]
@@ -201,6 +276,8 @@ public partial class MainWindowViewModel : ViewModelBase
_lastTransactions = null; _lastTransactions = null;
_pendingSend = null; _pendingSend = null;
HasPendingSend = false; HasPendingSend = false;
PendingPsbtBase64 = "";
OnPropertyChanged(nameof(IsWatchOnlyAccount));
History.Clear(); History.Clear();
Contacts.Clear(); Contacts.Clear();
SelectedContactInList = null; SelectedContactInList = null;
+59 -7
View File
@@ -60,7 +60,7 @@
<!-- ============ SETUP WIZARD (§15): one step at a time ============ --> <!-- ============ SETUP WIZARD (§15): one step at a time ============ -->
<ScrollViewer Grid.Row="1" IsVisible="{Binding IsSetupVisible}"> <ScrollViewer Grid.Row="1" IsVisible="{Binding IsSetupVisible}">
<StackPanel MaxWidth="560" Margin="24,40" Spacing="18" <StackPanel MaxWidth="560" Margin="24,40" Spacing="18"
HorizontalAlignment="Center"> HorizontalAlignment="Stretch">
<TextBlock Text="Palladium Wallet" FontSize="28" FontWeight="Bold" <TextBlock Text="Palladium Wallet" FontSize="28" FontWeight="Bold"
HorizontalAlignment="Center"/> HorizontalAlignment="Center"/>
@@ -99,6 +99,9 @@
<Button Content="{Binding Loc[wiz.importwif.btn]}" FontSize="16" <Button Content="{Binding Loc[wiz.importwif.btn]}" FontSize="16"
HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center"
Command="{Binding WizardStartImportWifCommand}"/> Command="{Binding WizardStartImportWifCommand}"/>
<Button Content="{Binding Loc[wiz.importaddress.btn]}" FontSize="16"
HorizontalAlignment="Stretch" HorizontalContentAlignment="Center"
Command="{Binding WizardStartImportAddressCommand}"/>
</StackPanel> </StackPanel>
<!-- Step: choose wallet (multiple files present) --> <!-- Step: choose wallet (multiple files present) -->
@@ -212,6 +215,19 @@
</StackPanel> </StackPanel>
</StackPanel> </StackPanel>
<!-- Step: import watch-only addresses (no key at all) -->
<StackPanel IsVisible="{Binding IsStepImportAddress}" Spacing="12">
<TextBlock Text="{Binding Loc[wiz.importaddress.title]}" FontSize="18" FontWeight="Bold"/>
<TextBlock Text="{Binding Loc[wiz.importaddress.hint]}" TextWrapping="Wrap" Foreground="{DynamicResource TextSecondaryBrush}"/>
<TextBox PlaceholderText="{Binding Loc[wiz.importaddress.placeholder]}"
Text="{Binding ImportAddressInput}" AcceptsReturn="True" Height="80"/>
<StackPanel Orientation="Horizontal" Spacing="10">
<Button Content="{Binding Loc[wiz.back]}" Command="{Binding WizardBackCommand}"/>
<Button Content="{Binding Loc[wiz.next]}" Classes="accent"
Command="{Binding WizardNextFromImportAddressCommand}"/>
</StackPanel>
</StackPanel>
<!-- Step: choose script/address type --> <!-- Step: choose script/address type -->
<StackPanel IsVisible="{Binding IsStepScriptType}" Spacing="12"> <StackPanel IsVisible="{Binding IsStepScriptType}" Spacing="12">
<TextBlock Text="{Binding Loc[wiz.scripttype.title]}" FontSize="18" FontWeight="Bold"/> <TextBlock Text="{Binding Loc[wiz.scripttype.title]}" FontSize="18" FontWeight="Bold"/>
@@ -429,7 +445,7 @@
<!-- ── DESKTOP: Recipient | Amount side-by-side ── --> <!-- ── DESKTOP: Recipient | Amount side-by-side ── -->
<Grid IsVisible="{Binding IsDesktop}" <Grid IsVisible="{Binding IsDesktop}"
RowDefinitions="Auto,Auto,Auto" RowSpacing="14"> RowDefinitions="Auto,Auto,Auto,Auto" RowSpacing="14">
<Grid Grid.Row="0" ColumnDefinitions="*,*" ColumnSpacing="14"> <Grid Grid.Row="0" ColumnDefinitions="*,*" ColumnSpacing="14">
<!-- Recipient card --> <!-- Recipient card -->
@@ -500,11 +516,29 @@
<SelectableTextBlock Text="{Binding SendPreview}" <SelectableTextBlock Text="{Binding SendPreview}"
TextWrapping="Wrap" FontSize="13" Classes="mono" TextWrapping="Wrap" FontSize="13" Classes="mono"
Foreground="{DynamicResource TextSecondaryBrush}"/> Foreground="{DynamicResource TextSecondaryBrush}"/>
<StackPanel Spacing="6"
IsVisible="{Binding PendingPsbtBase64, Converter={x:Static StringConverters.IsNotNullOrEmpty}}">
<TextBlock Text="{Binding Loc[send.psbt.label]}" Classes="label"/>
<Grid ColumnDefinitions="*,Auto">
<TextBox Grid.Column="0" Text="{Binding PendingPsbtBase64}" IsReadOnly="True"
FontFamily="monospace" FontSize="11" TextWrapping="Wrap"
AcceptsReturn="True" Height="90"/>
<Button Grid.Column="1" Margin="8,0,0,0"
Content="{Binding Loc[send.psbt.copy]}"
Click="OnCopyPsbtClick"/>
</Grid>
</StackPanel>
</StackPanel> </StackPanel>
</Border> </Border>
<!-- Watch-only notice -->
<TextBlock Grid.Row="2" Text="{Binding Loc[send.watchonly.hint]}"
IsVisible="{Binding IsWatchOnlyAccount}"
TextWrapping="Wrap" FontSize="12"
Foreground="{DynamicResource WarningBrush}"/>
<!-- Action buttons --> <!-- Action buttons -->
<Grid Grid.Row="2" ColumnDefinitions="*,*" ColumnSpacing="14"> <Grid Grid.Row="3" ColumnDefinitions="*,*" ColumnSpacing="14">
<Button Grid.Column="0" Content="{Binding Loc[send.prepare]}" <Button Grid.Column="0" Content="{Binding Loc[send.prepare]}"
Command="{Binding PrepareSendCommand}" Command="{Binding PrepareSendCommand}"
HorizontalAlignment="Stretch" HorizontalContentAlignment="Center"/> HorizontalAlignment="Stretch" HorizontalContentAlignment="Center"/>
@@ -604,9 +638,26 @@
<SelectableTextBlock Text="{Binding SendPreview}" <SelectableTextBlock Text="{Binding SendPreview}"
TextWrapping="Wrap" FontSize="13" Classes="mono" TextWrapping="Wrap" FontSize="13" Classes="mono"
Foreground="{DynamicResource TextSecondaryBrush}"/> Foreground="{DynamicResource TextSecondaryBrush}"/>
<StackPanel Spacing="6"
IsVisible="{Binding PendingPsbtBase64, Converter={x:Static StringConverters.IsNotNullOrEmpty}}">
<TextBlock Text="{Binding Loc[send.psbt.label]}" Classes="label"/>
<TextBox Text="{Binding PendingPsbtBase64}" IsReadOnly="True"
FontFamily="monospace" FontSize="11" TextWrapping="Wrap"
AcceptsReturn="True" Height="90"/>
<Button Content="{Binding Loc[send.psbt.copy]}"
Click="OnCopyPsbtClick"
MinHeight="44"
HorizontalAlignment="Stretch" HorizontalContentAlignment="Center"/>
</StackPanel>
</StackPanel> </StackPanel>
</Border> </Border>
<!-- Watch-only notice -->
<TextBlock Text="{Binding Loc[send.watchonly.hint]}"
IsVisible="{Binding IsWatchOnlyAccount}"
TextWrapping="Wrap" FontSize="12"
Foreground="{DynamicResource WarningBrush}"/>
<!-- Action buttons: primary (Confirm) prominent, secondary below --> <!-- Action buttons: primary (Confirm) prominent, secondary below -->
<Button Content="{Binding Loc[send.confirm]}" Classes="accent" <Button Content="{Binding Loc[send.confirm]}" Classes="accent"
Command="{Binding ConfirmSendCommand}" Command="{Binding ConfirmSendCommand}"
@@ -993,7 +1044,7 @@
<Border Background="{DynamicResource OverlayCardBrush}" <Border Background="{DynamicResource OverlayCardBrush}"
BorderBrush="{DynamicResource BorderSubtleBrush}" BorderThickness="1" CornerRadius="8" BorderBrush="{DynamicResource BorderSubtleBrush}" BorderThickness="1" CornerRadius="8"
MaxWidth="360" Margin="16" MaxWidth="360" Margin="16"
HorizontalAlignment="Center" VerticalAlignment="Center"> HorizontalAlignment="Stretch" VerticalAlignment="Center">
<StackPanel Margin="24" Spacing="14"> <StackPanel Margin="24" Spacing="14">
<TextBlock Text="{Binding Loc[addr.privkey.prompt.title]}" <TextBlock Text="{Binding Loc[addr.privkey.prompt.title]}"
FontSize="16" FontWeight="Bold"/> FontSize="16" FontWeight="Bold"/>
@@ -1334,7 +1385,7 @@
<Border Background="{DynamicResource OverlayCardBrush}" <Border Background="{DynamicResource OverlayCardBrush}"
BorderBrush="{DynamicResource BorderSubtleBrush}" BorderThickness="1" CornerRadius="8" BorderBrush="{DynamicResource BorderSubtleBrush}" BorderThickness="1" CornerRadius="8"
MaxWidth="500" Margin="16" MaxWidth="500" Margin="16"
HorizontalAlignment="Center" VerticalAlignment="Center"> HorizontalAlignment="Stretch" VerticalAlignment="Center">
<ScrollViewer MaxHeight="620"> <ScrollViewer MaxHeight="620">
<StackPanel Margin="24" Spacing="14"> <StackPanel Margin="24" Spacing="14">
<TextBlock Text="{Binding Loc[walletinfo.title]}" <TextBlock Text="{Binding Loc[walletinfo.title]}"
@@ -1597,8 +1648,9 @@
</ScrollViewer> </ScrollViewer>
</TabItem> </TabItem>
<!-- Tab: Donate --> <!-- Tab: Donate (needs an open wallet to send from) -->
<TabItem Header="{Binding Loc[help.tab.donate]}"> <TabItem Header="{Binding Loc[help.tab.donate]}"
IsVisible="{Binding IsWalletOpen}">
<ScrollViewer VerticalScrollBarVisibility="Auto"> <ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel Spacing="12" Margin="0,12,0,0"> <StackPanel Spacing="12" Margin="0,12,0,0">
<TextBlock Text="{Binding Loc[donate.desc]}" TextWrapping="Wrap" <TextBlock Text="{Binding Loc[donate.desc]}" TextWrapping="Wrap"
+11
View File
@@ -102,6 +102,17 @@ public partial class MainView : UserControl
} }
} }
private async void OnCopyPsbtClick(object? sender, RoutedEventArgs e)
{
if (DataContext is not MainWindowViewModel vm || string.IsNullOrEmpty(vm.PendingPsbtBase64))
return;
if (TopLevel.GetTopLevel(this)?.Clipboard is { } clipboard)
{
await clipboard.SetTextAsync(vm.PendingPsbtBase64);
vm.NotifyPsbtCopied();
}
}
private void OnConnectionStatusTapped(object? sender, TappedEventArgs e) private void OnConnectionStatusTapped(object? sender, TappedEventArgs e)
{ {
if (DataContext is MainWindowViewModel vm) if (DataContext is MainWindowViewModel vm)
+31 -2
View File
@@ -18,6 +18,7 @@ try
["create", .. var rest] => Create(rest), ["create", .. var rest] => Create(rest),
["restore", var words, .. var rest] => Restore(words, rest), ["restore", var words, .. var rest] => Restore(words, rest),
["restore-xpub", var xpub, .. var rest] => RestoreXpub(xpub, rest), ["restore-xpub", var xpub, .. var rest] => RestoreXpub(xpub, rest),
["restore-address", var addrs, .. var rest] => RestoreAddress(addrs, rest),
["info", .. var rest] => Info(rest), ["info", .. var rest] => Info(rest),
["sync", .. var rest] => await Sync(rest), ["sync", .. var rest] => await Sync(rest),
["send", .. var rest] => await Send(rest), ["send", .. var rest] => await Send(rest),
@@ -95,6 +96,31 @@ static int RestoreXpub(string xpubText, string[] o)
return 0; return 0;
} }
static int RestoreAddress(string addrsText, string[] o)
{
var profile = Profile(o);
var addresses = addrsText.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (addresses.Length == 0)
{
Console.Error.WriteLine("At least one address is required.");
return 1;
}
WalletDocument doc;
try
{
(doc, _) = WalletLoader.NewFromAddresses(addresses, profile);
}
catch (InvalidDataException ex)
{
Console.Error.WriteLine(ex.Message);
return 1;
}
var path = WalletPath(o, profile);
WalletStore.Save(doc, path, Opt(o, "--password"));
Console.WriteLine($"Watch-only wallet saved to {path} ({addresses.Length} address(es), cannot sign)");
return 0;
}
static int Info(string[] o) static int Info(string[] o)
{ {
var (doc, account, path) = OpenWallet(o); var (doc, account, path) = OpenWallet(o);
@@ -140,10 +166,11 @@ static async Task<int> Sync(string[] o)
doc.Cache?.BlockHeaders, doc.Cache?.BlockHeaders,
doc.Cache?.NextReceiveIndex ?? 0, doc.Cache?.NextReceiveIndex ?? 0,
doc.Cache?.NextChangeIndex ?? 0, doc.Cache?.NextChangeIndex ?? 0,
net); net,
doc.Cache?.AnchoredUpTo);
var result = await sync.SyncOnceAsync(); var result = await sync.SyncOnceAsync();
var (rawHex, verifiedAt, blockHeaders) = sync.ExportCaches(net); var (rawHex, verifiedAt, blockHeaders, anchoredUpTo) = sync.ExportCaches(net);
doc.Cache = new SyncCache doc.Cache = new SyncCache
{ {
TipHeight = result.TipHeight, TipHeight = result.TipHeight,
@@ -160,6 +187,7 @@ static async Task<int> Sync(string[] o)
RawTxHex = rawHex, RawTxHex = rawHex,
VerifiedAt = verifiedAt, VerifiedAt = verifiedAt,
BlockHeaders = blockHeaders, BlockHeaders = blockHeaders,
AnchoredUpTo = anchoredUpTo,
}; };
WalletStore.Save(doc, path, Opt(o, "--password")); WalletStore.Save(doc, path, Opt(o, "--password"));
@@ -352,6 +380,7 @@ static int Usage()
[--passphrase W] [--password P] [--file PATH] [--passphrase W] [--password P] [--file PATH]
restore "<mnemonic>" [same options as create] [--path m/...] restore "<mnemonic>" [same options as create] [--path m/...]
restore-xpub <slip132 xpub> [--net ...] [--password P] [--file PATH] (watch-only) restore-xpub <slip132 xpub> [--net ...] [--password P] [--file PATH] (watch-only)
restore-address <addr1,addr2,...> [--net ...] [--password P] [--file PATH] (watch-only, no keys)
info [--net ...] [--password P] [--file PATH] info [--net ...] [--password P] [--file PATH]
Network (indexing server; without --server the first known server is used): Network (indexing server; without --server the first known server is used):
+13
View File
@@ -52,6 +52,19 @@ public static class DerivationPaths
_ => throw new ArgumentOutOfRangeException(nameof(kind)), _ => throw new ArgumentOutOfRangeException(nameof(kind)),
}; };
/// <summary>
/// Best-effort reverse mapping from an already-known address to a ScriptKind, used to
/// label pure address imports (no derivation involved, so this is informational only).
/// </summary>
public static ScriptKind KindFor(BitcoinAddress address) => address switch
{
BitcoinWitPubKeyAddress => ScriptKind.NativeSegwit,
TaprootAddress => ScriptKind.Taproot,
BitcoinWitScriptAddress => ScriptKind.NativeSegwitMultisig,
BitcoinScriptAddress => ScriptKind.WrappedSegwit,
_ => ScriptKind.Legacy,
};
/// <summary> /// <summary>
/// Account path relative to the root: purpose'/coin'/account' (§4.2). /// Account path relative to the root: purpose'/coin'/account' (§4.2).
/// coin_type is taken from the profile (746 mainnet, 1 testnet). /// coin_type is taken from the profile (746 mainnet, 1 testnet).
+12 -5
View File
@@ -36,8 +36,12 @@ public sealed class ElectrumClient : IAsyncDisposable
// single segment; this gate avoids flooding the server with thousands of // single segment; this gate avoids flooding the server with thousands of
// simultaneous requests on large wallets → no bursts of -101/-102 nor // simultaneous requests on large wallets → no bursts of -101/-102 nor
// connection drops. Writes still stay pipelined up to this degree. // connection drops. Writes still stay pipelined up to this degree.
private const int MaxInFlight = 32; // Configurable per connection (see ConnectAsync): the right value trades off
private readonly SemaphoreSlim _inFlight = new(MaxInFlight, MaxInFlight); // initial-sync throughput against how aggressively a given server tolerates
// concurrent requests before throttling — no single constant is right for
// every server, so callers may raise/lower it instead of recompiling.
public const int DefaultMaxInFlight = 32;
private readonly SemaphoreSlim _inFlight;
private long _nextId; private long _nextId;
@@ -49,19 +53,22 @@ public sealed class ElectrumClient : IAsyncDisposable
public event Action<string, JsonElement>? NotificationReceived; public event Action<string, JsonElement>? NotificationReceived;
public event Action<Exception?>? Disconnected; public event Action<Exception?>? Disconnected;
private ElectrumClient(TcpClient tcp, Stream stream, string host, int port, bool useSsl) private ElectrumClient(TcpClient tcp, Stream stream, string host, int port, bool useSsl,
int maxInFlight)
{ {
_tcp = tcp; _tcp = tcp;
_stream = stream; _stream = stream;
Host = host; Host = host;
Port = port; Port = port;
UseSsl = useSsl; UseSsl = useSsl;
_inFlight = new SemaphoreSlim(maxInFlight, maxInFlight);
_readLoop = Task.Run(ReadLoopAsync); _readLoop = Task.Run(ReadLoopAsync);
_writeLoop = Task.Run(WriteLoopAsync); _writeLoop = Task.Run(WriteLoopAsync);
} }
public static async Task<ElectrumClient> ConnectAsync(string host, int port, bool useSsl, public static async Task<ElectrumClient> ConnectAsync(string host, int port, bool useSsl,
CertificatePinStore? pins = null, CancellationToken ct = default) CertificatePinStore? pins = null, CancellationToken ct = default,
int maxInFlight = DefaultMaxInFlight)
{ {
var tcp = new TcpClient { NoDelay = true }; var tcp = new TcpClient { NoDelay = true };
try try
@@ -90,7 +97,7 @@ public sealed class ElectrumClient : IAsyncDisposable
stream = ssl; stream = ssl;
} }
var client = new ElectrumClient(tcp, stream, host, port, useSsl); var client = new ElectrumClient(tcp, stream, host, port, useSsl, maxInFlight);
await client.RequestAsync("server.version", ct, ClientName, ProtocolVersion); await client.RequestAsync("server.version", ct, ClientName, ProtocolVersion);
return client; return client;
} }
+49 -9
View File
@@ -75,13 +75,23 @@ public sealed class WalletSynchronizer(IWalletAccount account, ElectrumClient cl
private readonly ConcurrentDictionary<string, Transaction> _txCache = new(); private readonly ConcurrentDictionary<string, Transaction> _txCache = new();
// txids known confirmed (height > 0) as of download time, independent of whether their
// Merkle proof has been verified yet — lets ExportCaches persist raw tx bytes for a
// confirmed transaction interrupted before verification, instead of forcing a
// re-download on the next sync just because _verifiedAtHeight hasn't caught up. Every
// entry here has txHeights[txid] > 0 at the time it was recorded, i.e. server-confirmed;
// unconfirmed (mempool/RBF-able) transactions are deliberately never added.
private readonly ConcurrentDictionary<string, byte> _confirmedTxids = new();
// Concurrent: written incrementally by individual merkle-verification tasks as they // Concurrent: written incrementally by individual merkle-verification tasks as they
// complete (§7.4 progressive verification), not just once after they all finish. // complete (§7.4 progressive verification), not just once after they all finish.
private readonly ConcurrentDictionary<string, int> _verifiedAtHeight = new(); private readonly ConcurrentDictionary<string, int> _verifiedAtHeight = new();
private readonly ConcurrentDictionary<int, Task<string>> _headerFetches = new(); private readonly ConcurrentDictionary<int, Task<string>> _headerFetches = new();
// checkpoint height -> highest height already proven to hash-chain back to it // checkpoint height -> highest height already proven to hash-chain back to it.
// (in-memory only: cheap to recompute from _headerFetches, no need to persist). // Persisted across sessions (see ExportCaches/PreloadCaches): without it, every restart
// re-walks and re-verifies the whole header chain from the checkpoint even though the
// header bytes themselves are cached, which dominates reconnect time on large wallets.
private readonly ConcurrentDictionary<int, int> _anchoredUpTo = new(); private readonly ConcurrentDictionary<int, int> _anchoredUpTo = new();
// Serializes header-range downloads: concurrent AnchorToCheckpointAsync calls (one per tx // Serializes header-range downloads: concurrent AnchorToCheckpointAsync calls (one per tx
@@ -110,16 +120,31 @@ public sealed class WalletSynchronizer(IWalletAccount account, ElectrumClient cl
Dictionary<int, string>? blockHeaders, Dictionary<int, string>? blockHeaders,
int knownReceiveIndex, int knownReceiveIndex,
int knownChangeIndex, int knownChangeIndex,
Network network) Network network,
Dictionary<int, int>? anchoredUpTo = null)
{ {
foreach (var (txid, hex) in rawTxHex) foreach (var (txid, hex) in rawTxHex)
{
_txCache.TryAdd(txid, Transaction.Parse(hex, network)); _txCache.TryAdd(txid, Transaction.Parse(hex, network));
// ExportCaches only ever wrote confirmed transactions here (see its own
// filter), so every preloaded entry is safe to mark confirmed too.
_confirmedTxids.TryAdd(txid, 0);
}
foreach (var (txid, height) in verifiedAt) foreach (var (txid, height) in verifiedAt)
if (!_verifiedAtHeight.ContainsKey(txid)) if (!_verifiedAtHeight.ContainsKey(txid))
_verifiedAtHeight[txid] = height; _verifiedAtHeight[txid] = height;
if (blockHeaders is not null) if (blockHeaders is not null)
foreach (var (height, hex) in blockHeaders) foreach (var (height, hex) in blockHeaders)
_headerFetches.TryAdd(height, Task.FromResult(hex)); _headerFetches.TryAdd(height, Task.FromResult(hex));
// Only trust a preloaded anchor up to a height whose header is also cached: if the
// header cache was cleared/corrupted independently, re-deriving the chain-of-hashes
// check on next use (AnchorToCheckpointAsync re-fetches what's missing) is safer than
// trusting a stale "already validated" claim against headers that may no longer match.
if (anchoredUpTo is not null)
foreach (var (checkpointHeight, upToHeight) in anchoredUpTo)
if (_headerFetches.ContainsKey(upToHeight))
_anchoredUpTo.AddOrUpdate(checkpointHeight, upToHeight,
(_, existing) => Math.Max(existing, upToHeight));
_knownReceiveIndex = knownReceiveIndex; _knownReceiveIndex = knownReceiveIndex;
_knownChangeIndex = knownChangeIndex; _knownChangeIndex = knownChangeIndex;
} }
@@ -131,10 +156,11 @@ public sealed class WalletSynchronizer(IWalletAccount account, ElectrumClient cl
/// </summary> /// </summary>
public (Dictionary<string, string> RawTxHex, public (Dictionary<string, string> RawTxHex,
Dictionary<string, int> VerifiedAt, Dictionary<string, int> VerifiedAt,
Dictionary<int, string> BlockHeaders) Dictionary<int, string> BlockHeaders,
Dictionary<int, int> AnchoredUpTo)
ExportCaches(Network network) ExportCaches(Network network)
{ {
var rawHex = _verifiedAtHeight.Keys var rawHex = _confirmedTxids.Keys
.Where(_txCache.ContainsKey) .Where(_txCache.ContainsKey)
.ToDictionary(txid => txid, txid => _txCache[txid].ToHex()); .ToDictionary(txid => txid, txid => _txCache[txid].ToHex());
@@ -145,7 +171,8 @@ public sealed class WalletSynchronizer(IWalletAccount account, ElectrumClient cl
if (task.IsCompletedSuccessfully) if (task.IsCompletedSuccessfully)
headers[height] = task.Result; headers[height] = task.Result;
return (rawHex, new Dictionary<string, int>(_verifiedAtHeight), headers); return (rawHex, new Dictionary<string, int>(_verifiedAtHeight), headers,
new Dictionary<int, int>(_anchoredUpTo));
} }
public async Task<SyncResult> SyncOnceAsync(CancellationToken ct = default) public async Task<SyncResult> SyncOnceAsync(CancellationToken ct = default)
@@ -218,17 +245,30 @@ public sealed class WalletSynchronizer(IWalletAccount account, ElectrumClient cl
&& (!_verifiedAtHeight.TryGetValue(kv.Key, out var h) || h != kv.Value)) && (!_verifiedAtHeight.TryGetValue(kv.Key, out var h) || h != kv.Value))
.ToList(); .ToList();
// Total/already-cached counts (not just this session's downloads): on a sync resumed
// after an interruption, `missing` is often empty because everything was already
// fetched last time (see _confirmedTxids/PreloadCaches) — reporting against the total
// shows "n/n transactions" immediately instead of a misleading "0/0" before jumping
// straight to proof verification.
var totalTx = txHeights.Count;
var alreadyCached = totalTx - missing.Count;
string DownloadVerifyStatus(int downloaded, int verified) =>
$"transactions {downloaded}/{totalTx}, proofs {verified}/{toVerify.Count}…";
if (missing.Count > 0 || toVerify.Count > 0) if (missing.Count > 0 || toVerify.Count > 0)
Progress?.Invoke($"downloading {missing.Count} txs, verifying {toVerify.Count} proofs…"); Progress?.Invoke(DownloadVerifyStatus(alreadyCached, 0));
var dlDone = 0; var dlDone = 0;
await Task.WhenAll(missing.Select(txid => RetryOnBusyAsync(async () => await Task.WhenAll(missing.Select(txid => RetryOnBusyAsync(async () =>
{ {
var raw = await client.GetTransactionAsync(txid, ct); var raw = await client.GetTransactionAsync(txid, ct);
_txCache[txid] = Transaction.Parse(raw, network); _txCache[txid] = Transaction.Parse(raw, network);
if (txHeights[txid] > 0)
_confirmedTxids.TryAdd(txid, 0);
var n = Interlocked.Increment(ref dlDone); var n = Interlocked.Increment(ref dlDone);
if (n % 50 == 0 || n == missing.Count) if (n % 50 == 0 || n == missing.Count)
Progress?.Invoke($"tx {n}/{missing.Count}, proofs 0/{toVerify.Count}…"); Progress?.Invoke(DownloadVerifyStatus(alreadyCached + n, 0));
}, ct))); }, ct)));
SyncResult BuildSnapshot() => SyncResult BuildSnapshot() =>
@@ -259,7 +299,7 @@ public sealed class WalletSynchronizer(IWalletAccount account, ElectrumClient cl
_verifiedAtHeight[txid] = height; _verifiedAtHeight[txid] = height;
var n = Interlocked.Increment(ref merkDone); var n = Interlocked.Increment(ref merkDone);
if (n % 50 == 0 || n == toVerify.Count) if (n % 50 == 0 || n == toVerify.Count)
Progress?.Invoke($"tx {missing.Count}/{missing.Count}, proofs {n}/{toVerify.Count}…"); Progress?.Invoke(DownloadVerifyStatus(totalTx, n));
if (n % PartialResultBatchSize == 0) if (n % PartialResultBatchSize == 0)
PartialResult?.Invoke(BuildSnapshot()); PartialResult?.Invoke(BuildSnapshot());
}, ct)).ToList(); }, ct)).ToList();
+11
View File
@@ -40,6 +40,9 @@ public sealed class WalletDocument
/// <summary>Imported WIF keys (in plaintext in the document — must be encrypted!).</summary> /// <summary>Imported WIF keys (in plaintext in the document — must be encrypted!).</summary>
public List<string>? WifKeys { get; set; } public List<string>? WifKeys { get; set; }
/// <summary>Watch-only addresses with no associated private key (pure address import).</summary>
public List<string>? WatchAddresses { get; set; }
/// <summary>Gap limit for address scanning (§5), configurable.</summary> /// <summary>Gap limit for address scanning (§5), configurable.</summary>
public int GapLimit { get; set; } = 20; public int GapLimit { get; set; } = 20;
@@ -134,6 +137,14 @@ public sealed class SyncCache
/// subsequent syncs. /// subsequent syncs.
/// </summary> /// </summary>
public Dictionary<int, string>? BlockHeaders { get; set; } public Dictionary<int, string>? BlockHeaders { get; set; }
/// <summary>
/// Checkpoint height → highest height already proven to hash-chain back to it (§7.3).
/// Avoids re-walking and re-verifying the whole header chain from the checkpoint on
/// every launch: the chain-of-hashes check already done for a height doesn't need
/// redoing once headers themselves are cached.
/// </summary>
public Dictionary<int, int>? AnchoredUpTo { get; set; }
} }
/// <summary>Scanned address with its own balance and transaction count (address view).</summary> /// <summary>Scanned address with its own balance and transaction count (address view).</summary>
+52 -1
View File
@@ -51,7 +51,15 @@ public static class WalletLoader
return new ImportedKeyAccount(entries, kind, profile); return new ImportedKeyAccount(entries, kind, profile);
} }
// 4. Watch-only from xpub // 4. Watch-only imported addresses (no keys, no HD derivation)
if (doc.WatchAddresses is { Count: > 0 } watchAddresses)
{
var entries = watchAddresses.Select(a =>
(BitcoinAddress.Create(a.Trim(), network), (Key?)null)).ToList();
return new ImportedKeyAccount(entries, kind, profile);
}
// 5. Watch-only from xpub
if (doc.AccountXpub is null) if (doc.AccountXpub is null)
throw new InvalidDataException("Wallet file has no xpub and no seed."); throw new InvalidDataException("Wallet file has no xpub and no seed.");
if (!Slip132.TryDecodePublic(doc.AccountXpub, profile, out var xpub, out _)) if (!Slip132.TryDecodePublic(doc.AccountXpub, profile, out var xpub, out _))
@@ -170,4 +178,47 @@ public static class WalletLoader
}; };
return (doc, account); return (doc, account);
} }
/// <summary>
/// Creates the document from one or more plain addresses, with no private key at all
/// (pure watch-only import — the account can never sign, unlike xpub- or WIF-based accounts
/// which can be upgraded later by supplying the matching key). ScriptKind is informational
/// only here (no derivation happens from a fixed address list) and is auto-detected from the
/// first address unless <paramref name="kindOverride"/> is given.
/// </summary>
public static (WalletDocument Doc, ImportedKeyAccount Account) NewFromAddresses(
IReadOnlyList<string> addresses, ChainProfile profile, ScriptKind? kindOverride = null)
{
if (addresses.Count == 0)
throw new InvalidDataException("At least one address is required.");
var network = PalladiumNetworks.For(profile.Kind);
var entries = new List<(BitcoinAddress, Key?)>();
var addressStrings = new List<string>();
foreach (var raw in addresses)
{
BitcoinAddress addr;
try
{
addr = BitcoinAddress.Create(raw.Trim(), network);
}
catch (Exception ex)
{
throw new InvalidDataException($"Invalid address: {ex.Message}");
}
entries.Add((addr, null));
addressStrings.Add(raw.Trim());
}
var kind = kindOverride ?? DerivationPaths.KindFor(entries[0].Item1);
var account = new ImportedKeyAccount(entries, kind, profile);
var doc = new WalletDocument
{
Network = profile.NetName,
ScriptKind = kind.ToString(),
WatchAddresses = addressStrings,
};
return (doc, account);
}
} }
@@ -595,7 +595,7 @@ public class WalletSynchronizerTests
var first = new WalletSynchronizer(account, client); var first = new WalletSynchronizer(account, client);
var result1 = await first.SyncOnceAsync(); var result1 = await first.SyncOnceAsync();
var (rawTx, verifiedAt, headers) = first.ExportCaches(Net); var (rawTx, verifiedAt, headers, anchoredUpTo) = first.ExportCaches(Net);
Assert.Single(rawTx); // the confirmed tx is exported Assert.Single(rawTx); // the confirmed tx is exported
Assert.Single(verifiedAt); // with its verified height Assert.Single(verifiedAt); // with its verified height
@@ -605,7 +605,7 @@ public class WalletSynchronizerTests
server.ResetCallCounts(); server.ResetCallCounts();
var second = new WalletSynchronizer(account, client); var second = new WalletSynchronizer(account, client);
second.PreloadCaches(rawTx, verifiedAt, headers, second.PreloadCaches(rawTx, verifiedAt, headers,
result1.NextReceiveIndex, result1.NextChangeIndex, Net); result1.NextReceiveIndex, result1.NextChangeIndex, Net, anchoredUpTo);
var result2 = await second.SyncOnceAsync(); var result2 = await second.SyncOnceAsync();
Assert.Equal(result1.ConfirmedSats, result2.ConfirmedSats); Assert.Equal(result1.ConfirmedSats, result2.ConfirmedSats);
@@ -614,6 +614,55 @@ public class WalletSynchronizerTests
Assert.Equal(0, server.CallCount("blockchain.block.header")); Assert.Equal(0, server.CallCount("blockchain.block.header"));
} }
[Fact]
public async Task Lo_stato_di_anchoring_precaricato_da_disco_evita_di_ricamminare_la_catena_al_riavvio()
{
// Same scenario as "Un_range_gia_ancorato_non_viene_ricamminato_al_sync_successivo", but
// across two separate WalletSynchronizer instances (simulating an app restart) with
// AnchoredUpTo round-tripped through ExportCaches/PreloadCaches like a real save/reload —
// the in-memory-only memoization that test covers wouldn't survive that on its own.
var account = Account();
var scenario = new Scenario();
var funding = scenario.Pay(account.GetReceiveAddress(0), 1_000_000, height: 105);
var tx2 = Net.CreateTransaction();
tx2.Inputs.Add(new TxIn(new OutPoint(uint256.One, 1)));
tx2.Outputs.Add(Money.Satoshis(500_000), account.GetReceiveAddress(1));
var chain = ChainedHeaders(100, 105, funding.GetHash(),
roots: new() { [103] = tx2.GetHash() });
foreach (var (h, hex) in chain) scenario.Headers[h] = hex;
var checkpointProfile = Profile with
{
Checkpoints = [new Checkpoint(100, BlockHeaderInfo.Parse(chain[100]).Hash.ToString(), 0x1d00ffff)],
};
var checkpointAccount = Account(checkpointProfile);
var (server, client) = await StartAsync(scenario);
await using var _ = server; await using var __ = client;
var first = new WalletSynchronizer(checkpointAccount, client);
var result1 = await first.SyncOnceAsync(); // walks and memoizes the anchor up to 105
var (rawTx, verifiedAt, headers, anchoredUpTo) = first.ExportCaches(Net);
Assert.NotEmpty(anchoredUpTo);
// Fresh synchroniser (new launch) preloaded from the exported caches, then a new tx at
// height 103 — within the already-anchored range — is announced.
scenario.Register(tx2, 103, checkpointAccount.GetReceiveAddress(1));
server.ResetCallCounts();
var second = new WalletSynchronizer(checkpointAccount, client);
second.PreloadCaches(rawTx, verifiedAt, headers,
result1.NextReceiveIndex, result1.NextChangeIndex, Net, anchoredUpTo);
var result2 = await second.SyncOnceAsync();
// 103 <= the persisted anchor of 105: no header-range re-walk despite this being a
// brand-new synchroniser instance that never anchored anything itself.
Assert.Equal(1_500_000, result2.ConfirmedSats);
Assert.Equal(0, server.CallCount("blockchain.block.header"));
Assert.Equal(0, server.CallCount("blockchain.block.headers"));
}
[Fact] [Fact]
public async Task Le_tx_non_confermate_non_vengono_esportate_nella_cache() public async Task Le_tx_non_confermate_non_vengono_esportate_nella_cache()
{ {
@@ -625,7 +674,7 @@ public class WalletSynchronizerTests
var sync = new WalletSynchronizer(account, client); var sync = new WalletSynchronizer(account, client);
await sync.SyncOnceAsync(); await sync.SyncOnceAsync();
var (rawTx, verifiedAt, _) = sync.ExportCaches(Net); var (rawTx, verifiedAt, _, _) = sync.ExportCaches(Net);
// Unconfirmed txs can change (RBF): they must always be re-downloaded. // Unconfirmed txs can change (RBF): they must always be re-downloaded.
Assert.Empty(rawTx); Assert.Empty(rawTx);
@@ -148,6 +148,21 @@ public class StorageTests
Assert.True(WalletDocument.FromJson(doc.ToJson()).IsWatchOnly); Assert.True(WalletDocument.FromJson(doc.ToJson()).IsWatchOnly);
} }
[Fact]
public void WatchAddresses_fa_roundtrip_json_ed_e_watch_only()
{
var doc = new WalletDocument
{
Network = "mainnet",
ScriptKind = "NativeSegwit",
WatchAddresses = ["bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"],
};
var restored = WalletDocument.FromJson(doc.ToJson());
Assert.Equal(doc.WatchAddresses, restored.WatchAddresses);
Assert.True(restored.IsWatchOnly);
}
[Fact] [Fact]
public void Json_corrotto_lancia_eccezione() public void Json_corrotto_lancia_eccezione()
{ {
@@ -250,6 +250,33 @@ public class TransactionFactoryTests
Assert.Contains(tx.Outputs, o => o.Value.Satoshi == 400_000); Assert.Contains(tx.Outputs, o => o.Value.Satoshi == 400_000);
} }
[Fact]
public void Un_account_di_soli_indirizzi_watch_only_produce_una_psbt_non_firmata()
{
var full = Account();
var (utxos, txs) = Fund(full, 1_000_000);
// Pure address import: no private key at all (unlike xpub watch-only, which
// can still derive public keys/scriptPubKeys — this account can't upgrade
// to spendable without the user separately importing the matching key).
var watchOnly = new ImportedKeyAccount(
[(full.GetReceiveAddress(0), (Key?)null)], ScriptKind.NativeSegwit, Profile);
var built = new TransactionFactory(watchOnly).Build(
utxos, txs, full.GetReceiveAddress(5), amountSats: 400_000,
feeRateSatPerVByte: 2, changeIndex: 0, tipHeight: 100);
Assert.False(built.Signed);
Assert.True(watchOnly.IsWatchOnly);
Assert.Null(watchOnly.GetPrivateKey(false, 0));
var psbt = built.Psbt;
psbt.SignWithKeys(full.GetExtPrivateKey(false, 0));
psbt.Finalize();
var tx = psbt.ExtractTransaction();
Assert.Contains(tx.Outputs, o => o.Value.Satoshi == 400_000);
}
[Theory] [Theory]
[InlineData("0.00000001", 1L)] [InlineData("0.00000001", 1L)]
[InlineData("1", 100_000_000L)] [InlineData("1", 100_000_000L)]
@@ -1,4 +1,5 @@
using System; using System;
using System.Linq;
using PalladiumWallet.Core.Chain; using PalladiumWallet.Core.Chain;
using PalladiumWallet.Core.Crypto; using PalladiumWallet.Core.Crypto;
using PalladiumWallet.Core.Storage; using PalladiumWallet.Core.Storage;
@@ -249,4 +250,85 @@ public class WalletLoaderTests
Assert.Throws<InvalidDataException>( Assert.Throws<InvalidDataException>(
() => WalletLoader.NewFromWif([], ScriptKind.NativeSegwit, ChainProfiles.Mainnet)); () => WalletLoader.NewFromWif([], ScriptKind.NativeSegwit, ChainProfiles.Mainnet));
} }
// ---- NewFromAddresses (pure watch-only, no key at all) ----
private static string SampleAddress(ScriptKind kind = ScriptKind.NativeSegwit) =>
WalletLoader.NewFromMnemonic(ValidMnemonic, null, kind, ChainProfiles.Mainnet)
.Account.GetReceiveAddress(0).ToString();
[Fact]
public void NewFromAddresses_crea_documento_watch_only_senza_chiavi()
{
var address = SampleAddress();
var (doc, account) = WalletLoader.NewFromAddresses([address], ChainProfiles.Mainnet);
Assert.Equal("mainnet", doc.Network);
Assert.Null(doc.Mnemonic);
Assert.Null(doc.AccountXprv);
Assert.Null(doc.AccountXpub);
Assert.Null(doc.WifKeys);
Assert.Equal([address], doc.WatchAddresses);
Assert.True(doc.IsWatchOnly);
Assert.True(account.IsWatchOnly);
Assert.Null(account.GetPrivateKey(false, 0));
Assert.Equal(address, account.GetReceiveAddress(0).ToString());
}
[Fact]
public void NewFromAddresses_rileva_lo_scriptkind_dallindirizzo()
{
var legacyAddr = SampleAddress(ScriptKind.Legacy);
var (doc, _) = WalletLoader.NewFromAddresses([legacyAddr], ChainProfiles.Mainnet);
Assert.Equal("Legacy", doc.ScriptKind);
}
[Fact]
public void NewFromAddresses_piu_indirizzi_sono_tutti_scansionabili()
{
var addr1 = SampleAddress();
var addr2 = WalletLoader.NewFromMnemonic(ValidMnemonic24, null, ScriptKind.NativeSegwit, ChainProfiles.Mainnet)
.Account.GetReceiveAddress(0).ToString();
var (_, account) = WalletLoader.NewFromAddresses([addr1, addr2], ChainProfiles.Mainnet);
Assert.NotNull(account.FixedAddresses);
Assert.Equal(2, account.FixedAddresses!.Count);
Assert.True(account.FixedAddresses!.All(e => account.GetPrivateKey(e.IsChange, e.Index) is null));
}
[Fact]
public void NewFromAddresses_lista_vuota_lancia_eccezione()
{
Assert.Throws<InvalidDataException>(
() => WalletLoader.NewFromAddresses([], ChainProfiles.Mainnet));
}
[Fact]
public void NewFromAddresses_indirizzo_invalido_lancia_eccezione()
{
Assert.Throws<InvalidDataException>(
() => WalletLoader.NewFromAddresses(["not-an-address"], ChainProfiles.Mainnet));
}
[Fact]
public void NewFromAddresses_indirizzo_di_rete_sbagliata_lancia_eccezione()
{
var testnetAddr = WalletLoader.NewFromMnemonic(ValidMnemonic, null, ScriptKind.NativeSegwit, ChainProfiles.Testnet)
.Account.GetReceiveAddress(0).ToString();
Assert.Throws<InvalidDataException>(
() => WalletLoader.NewFromAddresses([testnetAddr], ChainProfiles.Mainnet));
}
[Fact]
public void ToAccount_da_watch_addresses_ricostruisce_lo_stesso_account()
{
var address = SampleAddress();
var (doc, _) = WalletLoader.NewFromAddresses([address], ChainProfiles.Mainnet);
var account = WalletLoader.ToAccount(doc);
Assert.True(account.IsWatchOnly);
Assert.Equal(address, account.GetReceiveAddress(0).ToString());
Assert.Null(account.GetPrivateKey(false, 0));
}
} }