moonproof-wallet 0.2.1

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! Public value types shared across the wallet crate.
//!
//! ## `Amount` — 256-bit signed integer
//!
//! On-chain `Coin::value` is `u128` (`moonproof_ledger::coin_structure::coin::Coin.value`,
//! range `0..=2^128 − 1`). The wallet's balancer works in *imbalances*
//! — `inputs − outputs` — so the type has to be signed AND has to fit
//! a sum-of-many-u128-coins minus a sum-of-many-u128-coins without
//! overflow. `i128` cannot do that: its positive range is exactly half
//! of `u128`, so a single coin with `value > 2^127` already overflows
//! when cast.
//!
//! [`Amount`] is therefore a newtype over `ethnum::I256`:
//!
//! - 256 bits is **2× the source-bit width**, so any single u128 lifts
//!   cleanly and any sum/difference of u128 values fits without
//!   overflow given realistic transaction sizes (worst-case ≈ 2^130
//!   for tens of thousands of u128-max coins, well below 2^255).
//! - Stack-allocated, `Copy`, no heap allocation per arithmetic op —
//!   stays primitive-int-fast on the balancer hot path. Per-op cost is
//!   roughly 2-3× `i128` (4-6 instructions vs 2-3 on `x86_64`), still
//!   sub-microsecond.
//! - Lifts to/from `i128` and `u128` via `From` / `TryFrom`. Display
//!   and `FromStr` are decimal so it round-trips through FFI as a
//!   string at no precision loss (`UniFFI` does not support 128-bit
//!   integers, let alone 256-bit, regardless of declaration mode).
//!
//! ### Why not `num_bigint::BigInt`?
//! The TS reference uses `bigint` because JavaScript has no
//! fixed-width 256-bit integer type. `BigInt` is heap-allocated and
//! pays 10-100× the per-op cost of a stack integer. The balancer
//! processes hundreds of arithmetic ops per transaction and is on
//! every wallet user's hot path — primitive-int speed matters.
//! `I256`'s headroom over realistic u128 sums is so large that `BigInt`
//! gives no extra correctness in practice.
//!
//! ### Why not `i128` with `checked_*` everywhere?
//! Because `i128` cannot represent the full positive range of `u128`.
//! `checked_add` only flags overflows that already happened; the type
//! itself is too small to hold a single legal on-chain value above
//! `2^127`. That's a soundness gap, not an arithmetic-discipline gap.

use std::fmt;
use std::iter::Sum;
use std::num::ParseIntError;
use std::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use std::str::FromStr;

use ethnum::I256;
use serde::{Deserialize, Serialize};

use crate::error::{Result, WalletError};

/// A token type identifier. On-chain these are hex-encoded bytes; we keep
/// them as `String` so the balancer can key on them with `IndexMap` and
/// consumers can round-trip schema values without parsing.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct TokenType(pub String);

impl TokenType {
    #[inline]
    #[must_use]
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }

    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for TokenType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<String> for TokenType {
    #[inline]
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for TokenType {
    #[inline]
    fn from(s: &str) -> Self {
        Self(s.to_owned())
    }
}

// =============================================================================
// Amount — newtype over ethnum::I256.
// =============================================================================

/// Signed amount of a token (NIGHT / DUST / etc.). Positive = credit to
/// the tx's local side; negative = debit.
///
/// See the module docs for why this is a 256-bit type. Use
/// [`Amount::from_u128`] / [`Amount::from_i128`] for the common lifts;
/// arithmetic is just `+` / `-` / `*`. The arithmetic operators panic
/// on overflow in debug builds and wrap in release — same behavior as
/// stdlib integers. For boundary inputs (parsing untrusted strings,
/// summing arbitrary user-supplied chains) prefer the
/// [`Amount::checked_add`] / [`Amount::checked_sub`] / etc. variants
/// that return `Option`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct Amount(I256);

impl Amount {
    /// `0`.
    pub const ZERO: Self = Self(I256::ZERO);
    /// `1`.
    pub const ONE: Self = Self(I256::ONE);
    /// `-1`.
    pub const NEG_ONE: Self = Self(I256::MINUS_ONE);
    /// Largest representable value (`2^255 − 1`).
    pub const MAX: Self = Self(I256::MAX);
    /// Smallest representable value (`-2^255`).
    pub const MIN: Self = Self(I256::MIN);

    /// Lift a `u128` (the on-chain `Coin::value` shape). Infallible —
    /// any `u128` fits in `I256` without sign issues since the high
    /// 128 bits stay zero.
    #[inline]
    #[must_use]
    pub fn from_u128(value: u128) -> Self {
        Self(I256::from(value))
    }

    /// Lift an `i128`. Infallible — the sign extends into the upper
    /// 128 bits of `I256`.
    #[inline]
    #[must_use]
    pub fn from_i128(value: i128) -> Self {
        Self(I256::from(value))
    }

    /// Convert back to `u128`. Returns `None` if the amount is negative
    /// or doesn't fit in `u128` (exceeds `2^128 − 1`).
    #[inline]
    pub fn try_to_u128(self) -> Option<u128> {
        if self.0 < I256::ZERO {
            return None;
        }
        let (hi, lo) = self.0.into_words();
        if hi != 0 {
            return None;
        }
        // `lo` is i128 in ethnum's `into_words` for I256 — reinterpret as u128.
        // Since the high word is zero and the value is non-negative, the low
        // word's bit pattern is the u128 value.
        Some(u128::from_ne_bytes(lo.to_ne_bytes()))
    }

    /// Convert back to `i128`. Returns `None` if the amount doesn't
    /// fit in `i128` (`< -2^127` or `> 2^127 − 1`).
    #[inline]
    pub fn try_to_i128(self) -> Option<i128> {
        let min = I256::from(i128::MIN);
        let max = I256::from(i128::MAX);
        if self.0 < min || self.0 > max {
            return None;
        }
        let (_hi, lo) = self.0.into_words();
        Some(lo)
    }

    /// `true` if this amount is greater than zero. Convenience for
    /// imbalance-direction checks.
    #[inline]
    #[must_use]
    pub fn is_positive(self) -> bool {
        self.0 > I256::ZERO
    }

    /// `true` if this amount is less than zero.
    #[inline]
    #[must_use]
    pub fn is_negative(self) -> bool {
        self.0 < I256::ZERO
    }

    /// `true` if this amount is exactly zero.
    #[inline]
    #[must_use]
    pub fn is_zero(self) -> bool {
        self.0 == I256::ZERO
    }

    /// Absolute value. Saturates at [`Amount::MAX`] when called on
    /// [`Amount::MIN`] (since `-MIN > MAX`).
    #[inline]
    #[must_use]
    pub fn abs(self) -> Self {
        Self(self.0.checked_abs().unwrap_or(I256::MAX))
    }

    /// Checked addition. Returns `None` on overflow.
    #[inline]
    #[must_use]
    pub fn checked_add(self, rhs: Self) -> Option<Self> {
        self.0.checked_add(rhs.0).map(Self)
    }

    /// Checked subtraction. Returns `None` on overflow.
    #[inline]
    #[must_use]
    pub fn checked_sub(self, rhs: Self) -> Option<Self> {
        self.0.checked_sub(rhs.0).map(Self)
    }

    /// Checked multiplication. Returns `None` on overflow.
    #[inline]
    #[must_use]
    pub fn checked_mul(self, rhs: Self) -> Option<Self> {
        self.0.checked_mul(rhs.0).map(Self)
    }

    /// Checked negation. Returns `None` only for [`Amount::MIN`]
    /// (whose `-` doesn't fit).
    #[inline]
    #[must_use]
    pub fn checked_neg(self) -> Option<Self> {
        self.0.checked_neg().map(Self)
    }

    /// Borrow the inner `I256`. Useful in tight loops where the wrapper
    /// overhead matters.
    #[inline]
    #[must_use]
    pub const fn as_i256(self) -> I256 {
        self.0
    }
}

// ---- Arithmetic operators (delegate to I256). -------------------------------

impl Add for Amount {
    type Output = Self;
    #[inline]
    fn add(self, rhs: Self) -> Self {
        Self(self.0 + rhs.0)
    }
}

impl Sub for Amount {
    type Output = Self;
    #[inline]
    fn sub(self, rhs: Self) -> Self {
        Self(self.0 - rhs.0)
    }
}

impl Mul for Amount {
    type Output = Self;
    #[inline]
    fn mul(self, rhs: Self) -> Self {
        Self(self.0 * rhs.0)
    }
}

impl Neg for Amount {
    type Output = Self;
    #[inline]
    fn neg(self) -> Self {
        Self(-self.0)
    }
}

impl AddAssign for Amount {
    #[inline]
    fn add_assign(&mut self, rhs: Self) {
        self.0 += rhs.0;
    }
}

impl SubAssign for Amount {
    #[inline]
    fn sub_assign(&mut self, rhs: Self) {
        self.0 -= rhs.0;
    }
}

impl MulAssign for Amount {
    #[inline]
    fn mul_assign(&mut self, rhs: Self) {
        self.0 *= rhs.0;
    }
}

impl Sum for Amount {
    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
        iter.fold(Self::ZERO, Add::add)
    }
}

impl<'a> Sum<&'a Amount> for Amount {
    fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
        iter.copied().fold(Self::ZERO, Add::add)
    }
}

// ---- Conversions in. --------------------------------------------------------

impl From<i128> for Amount {
    #[inline]
    fn from(v: i128) -> Self {
        Self::from_i128(v)
    }
}

impl From<u128> for Amount {
    #[inline]
    fn from(v: u128) -> Self {
        Self::from_u128(v)
    }
}

impl From<i64> for Amount {
    #[inline]
    fn from(v: i64) -> Self {
        Self(I256::from(v))
    }
}

impl From<u64> for Amount {
    #[inline]
    fn from(v: u64) -> Self {
        Self(I256::from(v))
    }
}

impl From<i32> for Amount {
    #[inline]
    fn from(v: i32) -> Self {
        Self(I256::from(v))
    }
}

impl From<u32> for Amount {
    #[inline]
    fn from(v: u32) -> Self {
        Self(I256::from(v))
    }
}

impl From<i16> for Amount {
    #[inline]
    fn from(v: i16) -> Self {
        Self(I256::from(v))
    }
}

impl From<u16> for Amount {
    #[inline]
    fn from(v: u16) -> Self {
        Self(I256::from(v))
    }
}

impl From<i8> for Amount {
    #[inline]
    fn from(v: i8) -> Self {
        Self(I256::from(v))
    }
}

impl From<u8> for Amount {
    #[inline]
    fn from(v: u8) -> Self {
        Self(I256::from(v))
    }
}

// ---- Conversions out — fail when the value won't fit. ---------------------

impl TryFrom<Amount> for u128 {
    type Error = WalletError;

    fn try_from(value: Amount) -> std::result::Result<Self, Self::Error> {
        value
            .try_to_u128()
            .ok_or_else(|| WalletError::InvalidAmount(format!("{value} does not fit in u128")))
    }
}

impl TryFrom<Amount> for i128 {
    type Error = WalletError;

    fn try_from(value: Amount) -> std::result::Result<Self, Self::Error> {
        value
            .try_to_i128()
            .ok_or_else(|| WalletError::InvalidAmount(format!("{value} does not fit in i128")))
    }
}

// ---- Display / FromStr — decimal, FFI-friendly. -----------------------------

impl fmt::Display for Amount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl FromStr for Amount {
    type Err = WalletError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        I256::from_str_prefixed(s)
            .map(Self)
            .map_err(|e| WalletError::InvalidAmount(format!("'{s}': {e}")))
    }
}

// ---- Serde — string form, matches the FFI wire shape. -----------------------
//
// Using string serialization rather than I256's default JSON form keeps
// downstream consumers (the FFI `value: String` field, JSON-RPC clients,
// scenario fixtures) from depending on `ethnum`'s representation choice.

impl Serialize for Amount {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        serializer.collect_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for Amount {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> std::result::Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Self::from_str(&s).map_err(serde::de::Error::custom)
    }
}

// ---- Public re-exports + helpers used by the rest of the wallet crate. ------

/// `parse::<i128>` doesn't compose with our `WalletError`, so wallet
/// code that needs to parse a decimal-string amount uses
/// `Amount::from_str` and gets a `WalletError::InvalidAmount` for free.
pub fn parse_amount(s: &str) -> Result<Amount> {
    Amount::from_str(s)
}

// =============================================================================
// CoinRecipe + SimpleCoin — the balancer's input shape.
// =============================================================================

/// A coin / UTXO abstraction consumed by the balancer.
pub trait CoinRecipe {
    fn token_type(&self) -> &TokenType;
    fn value(&self) -> Amount;
}

/// Simple concrete `CoinRecipe` useful for tests and consumers that
/// don't need extra bookkeeping beyond (type, value).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SimpleCoin {
    pub token_type: TokenType,
    pub value: Amount,
}

impl SimpleCoin {
    /// Build a coin. Both arguments accept any `Into<TokenType>` /
    /// `Into<Amount>` so test fixtures and config-loaders can pass
    /// plain integer / string literals.
    #[inline]
    #[must_use]
    pub fn new(token_type: impl Into<TokenType>, value: impl Into<Amount>) -> Self {
        Self {
            token_type: token_type.into(),
            value: value.into(),
        }
    }
}

impl CoinRecipe for SimpleCoin {
    #[inline]
    fn token_type(&self) -> &TokenType {
        &self.token_type
    }

    #[inline]
    fn value(&self) -> Amount {
        self.value
    }
}

// =============================================================================
// TransactionCostModel — per-tx fee overhead model.
// =============================================================================

/// Per-transaction fee model. Fees are paid in the *native* token (DUST
/// on Midnight mainnet). Each input and each output consumes a flat
/// overhead that the balancer deducts from the native-token imbalance
/// as it runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct TransactionCostModel {
    pub input_fee_overhead: Amount,
    pub output_fee_overhead: Amount,
}

impl TransactionCostModel {
    /// Build a model. Both overhead arguments accept anything that
    /// converts to `Amount` (`u128` / `i128` / `i32` / etc.) so test
    /// fixtures and config-loaders can pass plain integer literals.
    #[inline]
    #[must_use]
    pub fn new(
        input_fee_overhead: impl Into<Amount>,
        output_fee_overhead: impl Into<Amount>,
    ) -> Self {
        Self {
            input_fee_overhead: input_fee_overhead.into(),
            output_fee_overhead: output_fee_overhead.into(),
        }
    }

    /// Zero-cost model — useful in tests where fees aren't the focus.
    pub const ZERO: Self = Self {
        input_fee_overhead: Amount::ZERO,
        output_fee_overhead: Amount::ZERO,
    };
}

// =============================================================================
// Conversion away from `ParseIntError` so callers can use `?` cleanly.
// =============================================================================

impl From<ParseIntError> for WalletError {
    fn from(e: ParseIntError) -> Self {
        WalletError::InvalidAmount(e.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn lifts_full_u128_range_without_overflow() {
        let max_u128 = u128::MAX;
        let amt = Amount::from_u128(max_u128);
        assert!(amt.is_positive());
        assert_eq!(amt.try_to_u128(), Some(max_u128));
    }

    #[test]
    fn sum_of_two_max_u128_does_not_overflow() {
        // The exact case that would overflow `i128`: two coins of u128::MAX.
        let a = Amount::from_u128(u128::MAX);
        let b = Amount::from_u128(u128::MAX);
        let sum = a + b;
        // No panic, and the sum is back-convertible through Display.
        let s = sum.to_string();
        // Sanity: the sum is exactly `2 * (2^128 - 1)` = `2^129 - 2`.
        let expected: I256 = (I256::ONE << 129u8) - I256::from(2u32);
        assert_eq!(sum.as_i256(), expected, "got {s}");
    }

    #[test]
    fn negative_imbalance_round_trips() {
        let inputs = Amount::from_u128(100);
        let outputs = Amount::from_u128(150);
        let imbalance = inputs - outputs;
        assert!(imbalance.is_negative());
        assert_eq!(imbalance, -Amount::from_u128(50));
    }

    #[test]
    fn checked_add_returns_none_on_overflow() {
        // Can't overflow with u128 inputs but we can with MAX + 1.
        assert_eq!(Amount::MAX.checked_add(Amount::ONE), None);
    }

    #[test]
    fn try_to_u128_rejects_negative() {
        assert_eq!(Amount::from_i128(-1).try_to_u128(), None);
    }

    #[test]
    fn try_to_u128_rejects_above_u128_max() {
        let big = Amount::from_u128(u128::MAX) + Amount::ONE;
        assert_eq!(big.try_to_u128(), None);
    }

    #[test]
    fn try_to_i128_rejects_above_i128_max() {
        let big = Amount::from_i128(i128::MAX) + Amount::ONE;
        assert_eq!(big.try_to_i128(), None);
    }

    #[test]
    fn try_to_i128_allows_full_i128_range() {
        assert_eq!(Amount::from_i128(i128::MAX).try_to_i128(), Some(i128::MAX));
        assert_eq!(Amount::from_i128(i128::MIN).try_to_i128(), Some(i128::MIN));
    }

    #[test]
    fn display_round_trip() {
        let a = Amount::from_u128(123_456_789_012_345_678_901_234_567_890_u128);
        let s = a.to_string();
        let b: Amount = s.parse().unwrap();
        assert_eq!(a, b);
    }

    #[test]
    fn negative_display_round_trip() {
        let a = -Amount::from_u128(42);
        let s = a.to_string();
        assert_eq!(s, "-42");
        let b: Amount = s.parse().unwrap();
        assert_eq!(a, b);
    }

    #[test]
    fn serde_uses_string_form() {
        let a = Amount::from_u128(u128::MAX);
        let json = serde_json::to_string(&a).unwrap();
        // String-encoded so it survives the JSON Number precision limit.
        assert!(json.starts_with('"'));
        let back: Amount = serde_json::from_str(&json).unwrap();
        assert_eq!(a, back);
    }

    #[test]
    fn sum_iterator() {
        let coins = [
            Amount::from_u128(10),
            Amount::from_u128(20),
            Amount::from_u128(30),
        ];
        let total: Amount = coins.iter().sum();
        assert_eq!(total, Amount::from_u128(60));
    }
}