moonproof-wallet 0.2.2

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
# moonproof-wallet

Native Rust wallet for the Midnight blockchain. Port of the TypeScript [`@midnight-ntwrk/wallet-sdk`](https://github.com/midnightntwrk/midnight-wallet) stack built on the `midnight-ledger` crates — no WASM boundary, no JS runtime.

## Correctness posture

This crate is the wallet for anything built on moonproof. The bar is high: every primitive is tested against the canonical reference it's porting.

- **HD derivation** is verified against **BIP32 Test Vector 1** from the Bitcoin wiki — a derivation mismatch would make moonproof wallets incompatible with `@scure/bip32` (and every other BIP32 implementation). That test is red until the byte-for-byte match holds.
- **Balancer** — the exact algorithm (and every public test) from `@midnight-ntwrk/wallet-sdk-capabilities/balancer` is ported. Fee accounting (including the "face vs net" rule for fee-token change outputs) is a faithful 1:1 translation of the TS reference; any divergence would cause fund loss or rejected txs.
- **Address format** — round-trip tests exercise mainnet and non-mainnet networks, custom networks, each address type, and the SCALE compact encoding for dust across its four length modes (1, 2, 4, big-integer bytes).
- **Segment validation** — rejects non-allowed characters per the TS reference's regex.

An extensive unit test suite covers these paths. `cargo test -p moonproof-wallet` must stay green on every change.

## What it covers

- [`hd`]: BIP32/BIP44 derivation with Midnight's role scheme.
- [`balancer`]: greedy + counter-offer coin selection, pluggable selector.
- [`address`]: Bech32m shielded, unshielded and dust addresses.
- [`abstractions`] and [`types`]: network ids, protocol versions, sync progress, token types, amounts, cost model.
- [`unshielded`], [`shielded`] and [`dust`]: the three sub-wallets, each with state, sync and transaction building.
- [`facade`]: transfers, swaps, dust registration, fee balancing against the synced block's ledger parameters, submission, and releasing what rejected or partially successful transactions booked.
- [`session`], [`runtime`], [`pending_tx`], [`tx_history`] and [`snapshot`]: the long-running wallet: indexer sync, submission tracking, history and persisted state.
- [`signing`]: `signData` with the dApp connector's Schnorr and ECDSA schemes.

## Shipped pieces, in detail

### `hd` — BIP32 + BIP44 derivation

Exactly matches `@midnight-ntwrk/wallet-sdk-hd`. Path: `m / 44' / 2400' / account' / role / index`.

```rust
use moonproof_wallet::{HDWallet, Role};

let wallet = HDWallet::from_mnemonic(
    "abandon abandon abandon abandon abandon abandon abandon \
     abandon abandon abandon abandon about",
    "",
)?;

// Single role:
let signing_key = wallet
    .account(0)
    .role(Role::NightExternal)
    .derive(0)?;

// Composite derivation across all roles at an index — re-uses the
// m/44'/2400'/account' prefix once:
let keys = wallet.account(0).roles(&Role::ALL).derive(0)?;
```

`SecretKey` is `ZeroizeOnDrop`; its `Debug` impl is redacted.

Role values are portable with the TS reference:

| Role | u32 |
|------|-----|
| `NightExternal` | 0 |
| `NightInternal` | 1 |
| `Dust` | 2 |
| `Zswap` | 3 |
| `Metadata` | 4 |

**Interop check.** `hd::tests::bip32_test_vector_1_interop` derives at `m/0'/1/2'/2/1000000000` from the BIP32 standard seed and asserts the published private key. A breakage here would be a wallet-compatibility regression — the test is load-bearing.

### `balancer` — greedy + counter-offer algorithm

1:1 port of `@midnight-ntwrk/wallet-sdk-capabilities/balancer`:

1. Seed a `CounterOffer` with initial imbalances.
2. While any non-fee token is off-target: add change (if excess > target) or pull an input via a pluggable `CoinSelector`.
3. Repeat for the fee (native) token.
4. Emit `(inputs, outputs)` as `BalanceRecipe`.

```rust
use moonproof_wallet::{
    balance, BalanceRequest, Imbalances, SimpleCoin, SmallestFirstSelector,
    TokenType, TransactionCostModel,
};

let native = TokenType::new("native");
let recipe = balance(BalanceRequest {
    coins: vec![SimpleCoin::new(native.clone(), 500)],
    initial_imbalances: Imbalances::from_entry(native.clone(), -100),
    target_imbalances: Imbalances::new(),
    cost_model: TransactionCostModel::new(10, 20),
    fee_token: native,
    selector: &SmallestFirstSelector,
    create_output: |r| SimpleCoin::new(r.token_type, r.value),
    is_coin_equal: |a, b| a == b,
})?;
```

**Fee accounting.** The TS reference handles fee-token outputs specially: `addOutput` subtracts the output-fee overhead from the output's face value (so the recipient receives `face − overhead`) while the imbalance math uses the full face value. For non-fee tokens, the recipient gets the full face value and the overhead is debited from the native imbalance separately. Our Rust `CounterOffer::add_output` reproduces this exactly — deviating here would cause either overpaying fees or rejected txs.

**Pluggable coin selection.** Any type implementing `CoinSelector<T>`. Default `SmallestFirstSelector` is a single-pass `Iterator::min_by_key` — no allocations, no sort.

### `address` — Bech32m address formats

Port of `@midnight-ntwrk/wallet-sdk-address-format`.

- HRP layout: `mn_<type>[_<network>]` — network segment omitted on mainnet.
- Segment character set: `[A-Za-z1-9-]+` (matching the TS reference's regex).
- Types: `shield-addr` (64 B), `shield-cpk` (32 B), `shield-epk` (32 B), `addr` (unshielded, 32 B), `dust` (SCALE compact big integer ≤ BLS12-381 scalar modulus).

```rust
use moonproof_wallet::{NetworkId, ShieldedAddress, ShieldedCoinPublicKey,
                       ShieldedEncryptionPublicKey};

let addr = ShieldedAddress::new(
    ShieldedCoinPublicKey::from_hex("aa".repeat(32).as_str())?,
    ShieldedEncryptionPublicKey::from_hex("bb".repeat(32).as_str())?,
);
let s = addr.encode(&NetworkId::TestNet)?.to_string()?;
// "mn_shield-addr_testnet1..."

let parsed = ShieldedAddress::parse(&s)?;
assert_eq!(addr, parsed);
```

DustAddresses use SCALE-compact big-integer encoding (4 length modes: 6-bit, 14-bit, 30-bit, bigint), implemented inline — no external SCALE codec dependency. Values are validated against the BLS12-381 scalar modulus on construction.

### `abstractions` — shared primitives

- `NetworkId` enum (MainNet / TestNet / DevNet / QaNet / Undeployed / Preview / PreProd + `Custom(String)`), round-tripping through the canonical string labels
- `ProtocolVersion` newtype + `ProtocolVersionRange` with half-open containment
- `SyncProgress` with `is_strictly_complete` and `is_complete_within(max_gap)` (default `DEFAULT_MAX_GAP = 50`, matching the TS reference)
- `WalletSeed` — zeroize-on-drop, redacted `Debug`, hex constructor

### `types` — value types

- `TokenType` — newtype over `String`, hash-keyable
- `Amount` — signed 256-bit newtype over `ethnum::I256` (stack-allocated, covers full `u128` UTXO totals without overflow)
- `CoinRecipe` — trait the coin types of every sub-wallet implement
- `TransactionCostModel { input_fee_overhead, output_fee_overhead }` with `::ZERO`

### `error` — typed surface

`WalletError` enum with `#[from]` for `std::io::Error`. `Result<T>` alias. No panics on library paths.

### `unshielded` — public UTXO wallet

Port of `@midnight-ntwrk/wallet-sdk-unshielded-wallet/v1/UnshieldedState.ts`. The state machine tracks which UTXOs are available for spending vs which are already committed to an in-flight tx:

```rust
use moonproof_wallet::{
    TokenType, UnshieldedState, UnshieldedUpdate, UnshieldedUtxo, UtxoId,
    UtxoMeta, UtxoWithMeta,
};

let utxo = UtxoWithMeta::new(
    UnshieldedUtxo::new(
        UtxoId::new([0xAB; 32], 0),
        1_000,
        TokenType::new("native"),
        [0xCD; 32],
    ),
    UtxoMeta::new(/* ctime */ 0, /* registered_for_dust */ false),
);

// Apply indexer-reported chain event.
let state = UnshieldedState::empty()
    .apply_update(&UnshieldedUpdate::success(vec![utxo.clone()], vec![]))?;

// Submit a tx that spends this utxo — mark it pending.
let state = state.spend(&utxo)?;

// If the tx later fails on chain, restore it to available:
let state = state.apply_failed_update(
    &UnshieldedUpdate::failure(vec![], vec![utxo.clone()]),
)?;
```

**Design points:**

- `UtxoId { intent_hash: [u8; 32], output_no: u32 }` is the map key — structural equality, no string hashing on the hot path.
- Rollbacks (`rollback_spend`, `rollback_spend_by_id`, `apply_failed_update`) are **idempotent and fault-tolerant** — races between the indexer and the wallet's own `spend` call can't produce an invalid state. Directly matches the TS reference's "rollbacks can't fail" invariant.
- `UnshieldedState` is an immutable value type: every mutation consumes `self` and returns a new state. Callers hold state in `Arc` or `RwLock` as needed.
- `IndexMap` for both maps — deterministic iteration for reproducible tx builds and snapshot tests.
- `UnshieldedUtxo` implements [`CoinRecipe`], so it feeds the balancer directly with no adapter.

Balance queries via `unshielded::balances`:

```rust
let native = TokenType::new("native");
let summary = state.balance_for(&native);
// summary.available, summary.pending, summary.total()

// All tokens at once, deterministic order:
let all = state.balances();
```

### Transacting — recipe layer

The recipe layer is pure logic: it consumes `UnshieldedState`, a transfer spec and a fee-token cost model, and produces a `TransferRecipe { inputs, recipient_outputs, change_outputs }`. `unshielded::ledger_adapter` turns a recipe into the ledger's `Intent` and `UnshieldedOffer` and signs it.

```rust
use moonproof_wallet::{
    build_transfer_recipe, TokenType, TransactionCostModel, UnshieldedState,
    UnshieldedTransfer,
};

let recipe = build_transfer_recipe(
    &wallet_state,
    sender_address_bytes,              // where change goes
    &[UnshieldedTransfer::new(500, TokenType::new("native"), recipient)],
    TokenType::new("native"),          // fee token
    TransactionCostModel::new(1_000, 2_000),
)?;

// recipe.inputs        — UTXOs we'll spend
// recipe.recipient_outputs — caller-ordered outputs to recipients
// recipe.change_outputs    — balancer-produced change, always back to sender
```

**Fee accounting.** Each recipient output pays the per-output fee overhead in the fee token. For non-fee-token recipient outputs, the overhead is debited from the native imbalance explicitly, so the balancer pulls enough native to cover it. For fee-token recipient outputs, the overhead is baked into the output's face value (matching the balancer's own change-output semantics — recipient nets `amount - output_fee_overhead` on the wire).

**14 tests** cover the recipe layer:

- Single fee-token transfer; non-fee-token transfer needing two input tokens; multi-token transfer with N recipient outputs
- Insufficient fee token → `InsufficientFunds { token: fee_token }`
- Insufficient target token → `InsufficientFunds { token: target }`
- Empty transfer list → empty recipe
- Invariants: inputs ⊆ wallet.available, change always to sender, output ordering (recipients first, then change)
- `initial_imbalances` unit tests: fee-token transfer, non-fee-token transfer, multi-transfer accumulation, `u128::MAX` overflow rejection

**Tests (25 unit tests ported 1:1 from the TS suite):**

- `applyUpdate`: SUCCESS single, SUCCESS multiple, rejects FAILURE, PARTIAL_SUCCESS equivalence, creates+spends in one step, removes confirmed spent from pending, empty no-op, silently ignores unknown spent, places each created by its id.
- `applyFailedUpdate`: restores pending, rejects SUCCESS, rejects PARTIAL_SUCCESS, restores spent + clears pending, inserts unknown spent into available (convergence invariant).
- `spend` / `spend_by_id`: moves to pending, errors when not available, errors match `UtxoNotFound`.
- `rollback_spend` / `rollback_spend_by_id`: restores pending → available, idempotent (calling twice is safe).
- `restore` / `to_arrays`: round trip preserving counts.
- Lifecycle: create → spend → confirm leaves both empty; create → spend → fail restores available.
- `CoinRecipe` conformance for `UnshieldedUtxo` and `UtxoWithMeta`.
- Balance aggregation: empty, per-token sums, available vs pending separation, `balance_for` pairing, `balances()` map, filter by token, saturating total.

## Key storage

Key storage is the caller's concern (hardware wallet, KMS, encrypted local store), as in the TypeScript SDK. `SecretKey` zeroizes on drop; `moonproof-keystore` provides an encrypted file format and OS keychain bridges for hosts that want one.

## Performance philosophy

- **Native compile, no WASM.** Rust consumers use this directly; JS consumers get it through `@moonproof/node` (NAPI-RS).
- **Stack over heap.** Stack-allocated `ethnum::I256` (`Amount`) for value math, `Copy` where possible, no `Box` unless ownership requires it.
- **Deterministic iteration.** `IndexMap` for the imbalance map — tx building is reproducible across runs.
- **Zero-alloc hot paths.** `Iterator::min_by_key` in the selector; `Vec::swap_remove` for coin removal.
- **Prefix re-use.** `CompositeRoleKey::derive` derives the `m/44'/2400'/account'` prefix once across all roles.
- **Zeroize on drop.** Every secret type (`SecretKey`, `WalletSeed`); redacted `Debug` impls.

## Testing

```bash
cargo test -p moonproof-wallet
```

Unit test suite (`cargo test -p moonproof-wallet` covers 400+ tests across HD, balancer, abstractions, addresses, unshielded, shielded, dust, facade, sync, and signing):

- HD (10): BIP32 test vector, Midnight path hardening, role child numbers, seed validation, determinism, index / role / account independence, composite vs single equivalence, mnemonic round-trip, debug redaction.
- Balancer (19): nothing-to-balance, exact-match, insufficient-funds error shape, no-overspend, multi-token, selector correctness, fee-token output above/below overhead, all TS reference tests (balance custom token, balance multiple token types, fail on insufficient fees, fail on below-overhead change, provided selector, targets, no-target-tokens), plus invariants (inputs ⊆ candidate pool, non-fee targets met exactly).
- Abstractions (7): network-id round trip + unknown-label fallback, protocol range rejections + half-open containment, sync progress connectivity / strict / within-gap semantics, wallet-seed hex round trip + redacted debug.
- Address (12): mainnet vs non-mainnet HRP layout, round-trip for CPK / EPK / shielded addr / unshielded addr / custom network, wrong-type rejection, invalid-segment rejection, DustAddress BLS-modulus ceiling, DustAddress round-trip across all four SCALE length modes, SCALE encoding boundary values.
- Unshielded state (25): see section above; 1:1 port of `UnshieldedState.test.ts`.
- Unshielded balances (7): empty state, per-token sums, available/pending separation, `balance_for`, full `balances()` map, token filter, saturating overflow.
- Unshielded transacting (14): single fee-token transfer, non-fee-token transfer with two input tokens, multi-token transfer, insufficient fee token, insufficient target token, empty list, inputs ⊆ wallet.available invariant, change always goes to sender, all-outputs ordering (recipients first then change), initial-imbalance accounting for fee-token/non-fee/multi/overflow.

The TypeScript reference also fuzzes with `fast-check`; this crate has no property-based tests.

## Dependencies

- [`bip32`] — BIP32 over secp256k1, same algorithm as `@scure/bip32`
- [`bip39`] — BIP39 mnemonic encode/decode
- [`bech32`] — Bech32 / Bech32m
- [`num-bigint`], [`num-traits`] — big integers for DustAddress
- [`zeroize`] — secret-memory hygiene
- [`indexmap`] — deterministic hash map
- [`moonproof-ledger`] — isolated ledger facade re-exporting Midnight ledger, zswap, base-crypto, and transient-crypto primitives (enforced by `cargo xtask check-ledger-boundary`)

## Cross-reference with the TypeScript SDK

| TS package | Rust module / crate |
|-----------|--------------------|
| `wallet-sdk-hd` | `moonproof_wallet::hd` |
| `wallet-sdk-capabilities/balancer` | `moonproof_wallet::balancer` |
| `wallet-sdk-address-format` | `moonproof_wallet::address` |
| `wallet-sdk-abstractions` | `moonproof_wallet::abstractions` |
| `wallet-sdk-indexer-client` | `moonproof-indexer-client` (sibling crate) |
| `wallet-sdk-node-client` | `moonproof-node-client` (sibling crate) |
| `wallet-sdk-prover-client` | `moonproof-prover` (sibling crate) |
| `wallet-sdk-unshielded-wallet` | `moonproof_wallet::unshielded` |
| `wallet-sdk-shielded-wallet` | `moonproof_wallet::shielded` |
| `wallet-sdk-dust-wallet` | `moonproof_wallet::dust` |
| `wallet-sdk-runtime` | `moonproof_wallet::runtime`, `moonproof_wallet::session` |
| `wallet-sdk-facade` | `moonproof_wallet::facade` |

[`bip32`]: https://crates.io/crates/bip32
[`bip39`]: https://crates.io/crates/bip39
[`bech32`]: https://crates.io/crates/bech32
[`num-bigint`]: https://crates.io/crates/num-bigint
[`num-traits`]: https://crates.io/crates/num-traits
[`zeroize`]: https://crates.io/crates/zeroize
[`indexmap`]: https://crates.io/crates/indexmap
[`midnight-ledger`]: https://github.com/midnightntwrk/midnight-ledger
[`midnight-zswap`]: https://github.com/midnightntwrk/midnight-ledger
[`midnight-base-crypto`]: https://github.com/midnightntwrk/midnight-ledger
[`midnight-transient-crypto`]: https://github.com/midnightntwrk/midnight-ledger