harmoniis-wallet 0.1.106

Smart-contract wallet for the Harmoniis marketplace for agents and robots (RGB contracts, Witness-backed bearer state, Webcash fees)
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
use crate::{
    crypto::{generate_secret_hex, sha256_bytes},
    error::{Error, Result},
};
use serde::{Deserialize, Serialize};
use zeroize::{Zeroize, ZeroizeOnDrop};

// ── WitnessSecret ─────────────────────────────────────────────────────────────

/// Format: `n:{contract_id}:secret:{hex64}`
/// Matches backend arbitration.rs and witness.rs exactly.
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct WitnessSecret {
    contract_id: String,
    hex_value: String,
}

impl WitnessSecret {
    /// Generate a fresh random secret for the given contract.
    pub fn generate(contract_id: &str) -> Self {
        Self {
            contract_id: contract_id.to_string(),
            hex_value: generate_secret_hex(),
        }
    }

    /// Parse from `n:{contract_id}:secret:{hex64}` string.
    pub fn parse(s: &str) -> Result<Self> {
        // Format: n:<id>:secret:<hex64>
        // Split on ":secret:" to handle contract_ids that contain colons
        let prefix = "n:";
        let mid = ":secret:";
        if !s.starts_with(prefix) {
            return Err(Error::InvalidFormat(format!(
                "WitnessSecret must start with 'n:': {s}"
            )));
        }
        let without_prefix = &s[prefix.len()..];
        let sep_pos = without_prefix
            .rfind(mid)
            .ok_or_else(|| Error::InvalidFormat(format!("missing ':secret:' in: {s}")))?;
        let contract_id = &without_prefix[..sep_pos];
        let hex_value = &without_prefix[sep_pos + mid.len()..];
        if hex_value.len() != 64 {
            return Err(Error::InvalidFormat(format!(
                "hex_value must be 64 chars, got {}: {s}",
                hex_value.len()
            )));
        }
        if !hex_value.chars().all(|c| c.is_ascii_hexdigit()) {
            return Err(Error::InvalidFormat(format!(
                "hex_value must be hex digits: {s}"
            )));
        }
        Ok(Self {
            contract_id: contract_id.to_string(),
            hex_value: hex_value.to_string(),
        })
    }

    /// Serialize to wire format: `n:{contract_id}:secret:{hex64}`
    pub fn display(&self) -> String {
        format!("n:{}:secret:{}", self.contract_id, self.hex_value)
    }

    /// Compute the public proof by SHA256-ing the 32 raw bytes of hex_value.
    pub fn public_proof(&self) -> WitnessProof {
        let raw = hex::decode(&self.hex_value)
            .expect("hex_value is always valid hex; generated/parsed that way");
        let public_hash = sha256_bytes(&raw);
        WitnessProof {
            contract_id: self.contract_id.clone(),
            public_hash,
        }
    }

    pub fn contract_id(&self) -> &str {
        &self.contract_id
    }

    pub fn hex_value(&self) -> &str {
        &self.hex_value
    }
}

impl std::fmt::Debug for WitnessSecret {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WitnessSecret")
            .field("contract_id", &self.contract_id)
            .field("hex_value", &"[redacted]")
            .finish()
    }
}

// ── WitnessProof ───────────────────────────────────────────────────────────────

/// Format: `n:{contract_id}:public:{sha256_hex64}`
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WitnessProof {
    pub contract_id: String,
    pub public_hash: String,
}

impl WitnessProof {
    /// Parse from `n:{contract_id}:public:{hash64}` string.
    pub fn parse(s: &str) -> Result<Self> {
        let prefix = "n:";
        let mid = ":public:";
        if !s.starts_with(prefix) {
            return Err(Error::InvalidFormat(format!(
                "WitnessProof must start with 'n:': {s}"
            )));
        }
        let without_prefix = &s[prefix.len()..];
        let sep_pos = without_prefix
            .rfind(mid)
            .ok_or_else(|| Error::InvalidFormat(format!("missing ':public:' in: {s}")))?;
        let contract_id = &without_prefix[..sep_pos];
        let public_hash = &without_prefix[sep_pos + mid.len()..];
        if public_hash.len() != 64 {
            return Err(Error::InvalidFormat(format!(
                "public_hash must be 64 chars, got {}: {s}",
                public_hash.len()
            )));
        }
        Ok(Self {
            contract_id: contract_id.to_string(),
            public_hash: public_hash.to_string(),
        })
    }

    /// Serialize to wire format: `n:{contract_id}:public:{hash64}`
    pub fn display(&self) -> String {
        format!("n:{}:public:{}", self.contract_id, self.public_hash)
    }
}

// ── Contract ──────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ContractStatus {
    Issued,
    Active,
    Delivered,
    Burned,
    Refunded,
}

impl ContractStatus {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Issued => "issued",
            Self::Active => "active",
            Self::Delivered => "delivered",
            Self::Burned => "burned",
            Self::Refunded => "refunded",
        }
    }

    pub fn parse(s: &str) -> Result<Self> {
        match s {
            "issued" => Ok(Self::Issued),
            "active" => Ok(Self::Active),
            "delivered" => Ok(Self::Delivered),
            "burned" => Ok(Self::Burned),
            "refunded" => Ok(Self::Refunded),
            _ => Err(Error::InvalidFormat(format!("unknown status: {s}"))),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ContractType {
    Service,
    ProductDigital,
    ProductPhysical,
}

impl ContractType {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Service => "service",
            Self::ProductDigital => "product_digital",
            Self::ProductPhysical => "product_physical",
        }
    }

    pub fn parse(s: &str) -> Result<Self> {
        match s {
            "service" => Ok(Self::Service),
            "product_digital" => Ok(Self::ProductDigital),
            "product_physical" => Ok(Self::ProductPhysical),
            _ => Err(Error::InvalidFormat(format!("unknown contract type: {s}"))),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Role {
    Buyer,
    Seller,
}

impl Role {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Buyer => "buyer",
            Self::Seller => "seller",
        }
    }

    pub fn parse(s: &str) -> Result<Self> {
        match s {
            "buyer" => Ok(Self::Buyer),
            "seller" => Ok(Self::Seller),
            _ => Err(Error::InvalidFormat(format!("unknown role: {s}"))),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Contract {
    pub contract_id: String,
    pub contract_type: ContractType,
    pub status: ContractStatus,
    /// Stored as display string: `n:{id}:secret:{hex64}`
    pub witness_secret: Option<String>,
    /// Stored as display string: `n:{id}:public:{hash64}`
    pub witness_proof: Option<String>,
    pub amount_units: u64,
    pub work_spec: String,
    pub buyer_fingerprint: String,
    pub seller_fingerprint: Option<String>,
    pub reference_post: Option<String>,
    pub delivery_deadline: Option<String>,
    pub role: Role,
    pub delivered_text: Option<String>,
    pub certificate_id: Option<String>,
    pub arbitration_profit_wats: Option<u64>,
    pub seller_value_wats: Option<u64>,
    pub created_at: String,
    pub updated_at: String,
}

impl Contract {
    pub fn new(
        contract_id: String,
        contract_type: ContractType,
        amount_units: u64,
        work_spec: String,
        buyer_fingerprint: String,
        role: Role,
    ) -> Self {
        let now = chrono::Utc::now().to_rfc3339();
        Self {
            contract_id,
            contract_type,
            status: ContractStatus::Issued,
            witness_secret: None,
            witness_proof: None,
            amount_units,
            work_spec,
            buyer_fingerprint,
            seller_fingerprint: None,
            reference_post: None,
            delivery_deadline: None,
            role,
            delivered_text: None,
            certificate_id: None,
            arbitration_profit_wats: None,
            seller_value_wats: None,
            created_at: now.clone(),
            updated_at: now,
        }
    }
}

// ── StablecashSecret (RGB20) ──────────────────────────────────────────────────
//
// PHASE:  SANDBOX — not yet in production.
// Enable via the Exchange service once the BTC ↔ USDH bridge is live.
// RGB20 is the fungible layer; all production contracts remain RGB21.

/// RGB20 fungible bearer token — split/merge allowed, sum must balance.
///
/// **⚠ SANDBOX ONLY** — Stablecash (USDH) is not yet in production.
/// Use only against testnet or local backends with `--sandbox` flag.
///
/// Wire format: `u{amount_units}:{contract_id}:secret:{hex64}`
/// Proof format: `u{amount_units}:{contract_id}:public:{sha256_hex64}`
///
/// The canonical Stablecash contract_id is `USDH_MAIN`.
/// Amount is in integer atomic units (minimum unit is 0.00000001): 1 USDH = 100_000_000 units.
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct StablecashSecret {
    pub amount_units: u64,
    pub contract_id: String,
    hex_value: String,
}

impl StablecashSecret {
    /// Generate a fresh random Stablecash secret.
    pub fn generate(amount_units: u64, contract_id: &str) -> Self {
        Self {
            amount_units,
            contract_id: contract_id.to_string(),
            hex_value: crate::crypto::generate_secret_hex(),
        }
    }

    /// Parse from `u{amount}:{contract_id}:secret:{hex64}`.
    pub fn parse(s: &str) -> Result<Self> {
        if !s.starts_with('u') {
            return Err(Error::InvalidFormat(format!(
                "StablecashSecret must start with 'u': {s}"
            )));
        }
        let rest = &s[1..];
        let colon1 = rest
            .find(':')
            .ok_or_else(|| Error::InvalidFormat(format!("missing first ':' in: {s}")))?;
        let amount_str = &rest[..colon1];
        let amount_units: u64 = amount_str
            .parse()
            .map_err(|_| Error::InvalidFormat(format!("invalid amount in: {s}")))?;
        let after_amount = &rest[colon1 + 1..];

        // Now split on ":secret:" (rfind to be robust)
        let mid = ":secret:";
        let sep = after_amount
            .rfind(mid)
            .ok_or_else(|| Error::InvalidFormat(format!("missing ':secret:' in: {s}")))?;
        let contract_id = &after_amount[..sep];
        let hex_value = &after_amount[sep + mid.len()..];

        if hex_value.len() != 64 || !hex_value.chars().all(|c| c.is_ascii_hexdigit()) {
            return Err(Error::InvalidFormat(format!(
                "hex_value must be 64 lowercase hex chars in: {s}"
            )));
        }
        Ok(Self {
            amount_units,
            contract_id: contract_id.to_string(),
            hex_value: hex_value.to_string(),
        })
    }

    /// Serialize to wire format: `u{amount}:{contract_id}:secret:{hex64}`
    pub fn display(&self) -> String {
        format!(
            "u{}:{}:secret:{}",
            self.amount_units, self.contract_id, self.hex_value
        )
    }

    /// Compute the public proof.
    pub fn public_proof(&self) -> StablecashProof {
        let raw = hex::decode(&self.hex_value).expect("always valid hex");
        StablecashProof {
            amount_units: self.amount_units,
            contract_id: self.contract_id.clone(),
            public_hash: crate::crypto::sha256_bytes(&raw),
        }
    }

    pub fn hex_value(&self) -> &str {
        &self.hex_value
    }
}

impl std::fmt::Debug for StablecashSecret {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StablecashSecret")
            .field("amount_units", &self.amount_units)
            .field("contract_id", &self.contract_id)
            .field("hex_value", &"[redacted]")
            .finish()
    }
}

/// RGB20 public proof — `u{amount}:{contract_id}:public:{sha256_hex64}`
///
/// **⚠ SANDBOX ONLY** — see [`StablecashSecret`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StablecashProof {
    pub amount_units: u64,
    pub contract_id: String,
    pub public_hash: String,
}

impl StablecashProof {
    pub fn parse(s: &str) -> Result<Self> {
        if !s.starts_with('u') {
            return Err(Error::InvalidFormat(format!(
                "StablecashProof must start with 'u': {s}"
            )));
        }
        let rest = &s[1..];
        let colon1 = rest
            .find(':')
            .ok_or_else(|| Error::InvalidFormat(format!("missing first ':' in: {s}")))?;
        let amount_units: u64 = rest[..colon1]
            .parse()
            .map_err(|_| Error::InvalidFormat(format!("invalid amount in: {s}")))?;
        let after_amount = &rest[colon1 + 1..];
        let mid = ":public:";
        let sep = after_amount
            .rfind(mid)
            .ok_or_else(|| Error::InvalidFormat(format!("missing ':public:' in: {s}")))?;
        let contract_id = &after_amount[..sep];
        let public_hash = &after_amount[sep + mid.len()..];
        if public_hash.len() != 64 {
            return Err(Error::InvalidFormat(format!(
                "public_hash must be 64 chars in: {s}"
            )));
        }
        Ok(Self {
            amount_units,
            contract_id: contract_id.to_string(),
            public_hash: public_hash.to_string(),
        })
    }

    pub fn display(&self) -> String {
        format!(
            "u{}:{}:public:{}",
            self.amount_units, self.contract_id, self.public_hash
        )
    }
}

// ── Voucher decimal helpers ──────────────────────────────────────────────────

/// 1 credit = 100,000,000 atomic units (same as webcash: 1 webcash = 100,000,000 wats).
const VOUCHER_ATOMIC_PER_CREDIT: u64 = 100_000_000;

/// Parse a decimal amount string (integer or fractional, up to 8 decimal places)
/// into atomic units. Returns error if invalid or more than 8 decimal places.
///
/// Examples: "5" -> 500_000_000, "0.5" -> 50_000_000, "0.00000001" -> 1
fn voucher_parse_decimal(amount_str: &str) -> Result<u64> {
    if let Some(dot_pos) = amount_str.find('.') {
        let int_part = &amount_str[..dot_pos];
        let frac_part = &amount_str[dot_pos + 1..];
        if frac_part.is_empty() {
            return Err(Error::InvalidFormat(format!(
                "trailing dot with no decimals: {amount_str}"
            )));
        }
        if frac_part.len() > 8 {
            return Err(Error::InvalidFormat(format!(
                "too many decimal places (max 8): {amount_str}"
            )));
        }
        let int_val: u64 = if int_part.is_empty() {
            0
        } else {
            int_part
                .parse()
                .map_err(|_| Error::InvalidFormat(format!("invalid integer part: {amount_str}")))?
        };
        let padded = format!("{:0<8}", frac_part);
        let frac_val: u64 = padded
            .parse()
            .map_err(|_| Error::InvalidFormat(format!("invalid fractional part: {amount_str}")))?;
        let total = int_val
            .checked_mul(VOUCHER_ATOMIC_PER_CREDIT)
            .and_then(|v| v.checked_add(frac_val))
            .ok_or_else(|| Error::InvalidFormat(format!("amount overflow: {amount_str}")))?;
        Ok(total)
    } else {
        let int_val: u64 = amount_str
            .parse()
            .map_err(|_| Error::InvalidFormat(format!("invalid amount: {amount_str}")))?;
        int_val
            .checked_mul(VOUCHER_ATOMIC_PER_CREDIT)
            .ok_or_else(|| Error::InvalidFormat(format!("amount overflow: {amount_str}")))
    }
}

/// Format atomic units as a clean decimal string.
/// No trailing zeros for whole numbers: 500_000_000 -> "5", not "5.00000000".
/// Fractional: 50_000_000 -> "0.5", 1 -> "0.00000001".
pub fn voucher_format_decimal(atomic: u64) -> String {
    let whole = atomic / VOUCHER_ATOMIC_PER_CREDIT;
    let frac = atomic % VOUCHER_ATOMIC_PER_CREDIT;
    if frac == 0 {
        whole.to_string()
    } else {
        let frac_str = format!("{:08}", frac);
        let trimmed = frac_str.trim_end_matches('0');
        format!("{whole}.{trimmed}")
    }
}

// ── VoucherSecret ────────────────────────────────────────────────────────────

/// Prepaid credit bearer token — split/merge via replace endpoint.
///
/// Wire format: `v{amount}:secret:{hex64}`
/// Proof format: `v{amount}:public:{sha256_hex64}`
///
/// Amount is in atomic units (1 credit = 100,000,000 atomic units).
/// Supports 8 decimal places: `v0.00000001:secret:{hex}` = 1 atomic unit.
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct VoucherSecret {
    pub amount_units: u64,
    hex_value: String,
}

impl VoucherSecret {
    /// Generate a fresh random Voucher secret.
    /// `amount_units` is in atomic units.
    pub fn generate(amount_units: u64) -> Self {
        Self {
            amount_units,
            hex_value: crate::crypto::generate_secret_hex(),
        }
    }

    /// Parse from `v{amount}:secret:{hex64}`.
    /// Amount can be integer ("5") or decimal ("0.5", "0.00000001").
    /// Internally stored as atomic units.
    pub fn parse(s: &str) -> Result<Self> {
        if !s.starts_with('v') {
            return Err(Error::InvalidFormat(format!(
                "VoucherSecret must start with 'v': {s}"
            )));
        }
        let rest = &s[1..];
        let mid = ":secret:";
        let sep = rest
            .find(mid)
            .ok_or_else(|| Error::InvalidFormat(format!("missing ':secret:' in: {s}")))?;
        let amount_str = &rest[..sep];
        let amount_units = voucher_parse_decimal(amount_str)?;
        let hex_value = &rest[sep + mid.len()..];
        if hex_value.len() != 64 || !hex_value.chars().all(|c| c.is_ascii_hexdigit()) {
            return Err(Error::InvalidFormat(format!(
                "hex_value must be 64 lowercase hex chars in: {s}"
            )));
        }
        Ok(Self {
            amount_units,
            hex_value: hex_value.to_string(),
        })
    }

    /// Serialize to wire format: `v{amount}:secret:{hex64}`
    /// Amount displayed as clean decimal (no trailing zeros for whole credits).
    pub fn display(&self) -> String {
        format!(
            "v{}:secret:{}",
            voucher_format_decimal(self.amount_units),
            self.hex_value
        )
    }

    /// Amount as a human-readable decimal string.
    pub fn display_amount(&self) -> String {
        voucher_format_decimal(self.amount_units)
    }

    /// Compute the public proof.
    pub fn public_proof(&self) -> VoucherProof {
        let raw = hex::decode(&self.hex_value).expect("always valid hex");
        VoucherProof {
            amount_units: self.amount_units,
            public_hash: crate::crypto::sha256_bytes(&raw),
        }
    }

    pub fn hex_value(&self) -> &str {
        &self.hex_value
    }
}

impl std::fmt::Debug for VoucherSecret {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VoucherSecret")
            .field("amount_units", &self.amount_units)
            .field("amount_display", &voucher_format_decimal(self.amount_units))
            .field("hex_value", &"[redacted]")
            .finish()
    }
}

/// Voucher public proof — `v{amount}:public:{sha256_hex64}`
/// Amount is in atomic units (1 credit = 100,000,000 atomic units).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VoucherProof {
    pub amount_units: u64,
    pub public_hash: String,
}

impl VoucherProof {
    pub fn parse(s: &str) -> Result<Self> {
        if !s.starts_with('v') {
            return Err(Error::InvalidFormat(format!(
                "VoucherProof must start with 'v': {s}"
            )));
        }
        let rest = &s[1..];
        let mid = ":public:";
        let sep = rest
            .find(mid)
            .ok_or_else(|| Error::InvalidFormat(format!("missing ':public:' in: {s}")))?;
        let amount_units = voucher_parse_decimal(&rest[..sep])?;
        let public_hash = &rest[sep + mid.len()..];
        if public_hash.len() != 64 {
            return Err(Error::InvalidFormat(format!(
                "public_hash must be 64 chars in: {s}"
            )));
        }
        Ok(Self {
            amount_units,
            public_hash: public_hash.to_string(),
        })
    }

    pub fn display(&self) -> String {
        format!(
            "v{}:public:{}",
            voucher_format_decimal(self.amount_units),
            self.public_hash
        )
    }
}

// ── Certificate ───────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Certificate {
    pub certificate_id: String,
    pub contract_id: Option<String>,
    /// Stored as display string
    pub witness_secret: Option<String>,
    pub witness_proof: Option<String>,
    pub created_at: String,
}