moonproof-wallet
Native Rust wallet for the Midnight blockchain. Port of the TypeScript @midnight-ntwrk/wallet-sdk 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/balanceris 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]:signDatawith 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.
use ;
let wallet = from_mnemonic?;
// Single role:
let signing_key = wallet
.account
.role
.derive?;
// Composite derivation across all roles at an index — re-uses the
// m/44'/2400'/account' prefix once:
let keys = wallet.account.roles.derive?;
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:
- Seed a
CounterOfferwith initial imbalances. - While any non-fee token is off-target: add change (if excess > target) or pull an input via a pluggable
CoinSelector. - Repeat for the fee (native) token.
- Emit
(inputs, outputs)asBalanceRecipe.
use ;
let native = new;
let recipe = balance?;
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).
use ;
let addr = new;
let s = addr.encode?.to_string?;
// "mn_shield-addr_testnet1..."
let parsed = parse?;
assert_eq!;
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
NetworkIdenum (MainNet / TestNet / DevNet / QaNet / Undeployed / Preview / PreProd +Custom(String)), round-tripping through the canonical string labelsProtocolVersionnewtype +ProtocolVersionRangewith half-open containmentSyncProgresswithis_strictly_completeandis_complete_within(max_gap)(defaultDEFAULT_MAX_GAP = 50, matching the TS reference)WalletSeed— zeroize-on-drop, redactedDebug, hex constructor
types — value types
TokenType— newtype overString, hash-keyableAmount— signed 256-bit newtype overethnum::I256(stack-allocated, covers fullu128UTXO totals without overflow)CoinRecipe— trait the coin types of every sub-wallet implementTransactionCostModel { 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:
use ;
let utxo = new;
// Apply indexer-reported chain event.
let state = empty
.apply_update?;
// Submit a tx that spends this utxo — mark it pending.
let state = state.spend?;
// If the tx later fails on chain, restore it to available:
let state = state.apply_failed_update?;
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 ownspendcall can't produce an invalid state. Directly matches the TS reference's "rollbacks can't fail" invariant. UnshieldedStateis an immutable value type: every mutation consumesselfand returns a new state. Callers hold state inArcorRwLockas needed.IndexMapfor both maps — deterministic iteration for reproducible tx builds and snapshot tests.UnshieldedUtxoimplements [CoinRecipe], so it feeds the balancer directly with no adapter.
Balance queries via unshielded::balances:
let native = new;
let summary = state.balance_for;
// 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.
use ;
let recipe = build_transfer_recipe?;
// 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_imbalancesunit tests: fee-token transfer, non-fee-token transfer, multi-transfer accumulation,u128::MAXoverflow 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 matchUtxoNotFound.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.
CoinRecipeconformance forUnshieldedUtxoandUtxoWithMeta.- Balance aggregation: empty, per-token sums, available vs pending separation,
balance_forpairing,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,Copywhere possible, noBoxunless ownership requires it. - Deterministic iteration.
IndexMapfor the imbalance map — tx building is reproducible across runs. - Zero-alloc hot paths.
Iterator::min_by_keyin the selector;Vec::swap_removefor coin removal. - Prefix re-use.
CompositeRoleKey::derivederives them/44'/2400'/account'prefix once across all roles. - Zeroize on drop. Every secret type (
SecretKey,WalletSeed); redactedDebugimpls.
Testing
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, fullbalances()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/bip32bip39— BIP39 mnemonic encode/decodebech32— Bech32 / Bech32mnum-bigint,num-traits— big integers for DustAddresszeroize— secret-memory hygieneindexmap— deterministic hash map- [
moonproof-ledger] — isolated ledger facade re-exporting Midnight ledger, zswap, base-crypto, and transient-crypto primitives (enforced bycargo 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 |