tenzro-wallet 0.1.0

MPC wallet for Tenzro Network — FROST-Ed25519 + ML-DSA-65 hybrid threshold wallets, Argon2id keystore, transaction history, contacts
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
//! Transaction validation for Tenzro Network wallets.
//!
//! This module validates transactions before signing, ensuring:
//! - Chain ID is correct for the target network
//! - Nonce is valid (sequential, not replayed)
//! - Gas parameters are within bounds
//! - Addresses are valid (non-zero sender, valid format)
//! - Transaction data size is within limits
//! - Sufficient balance for value + gas

use crate::error::{Result, WalletError};
use tenzro_types::primitives::{Address, ChainId, Nonce};
use tenzro_types::transaction::{Transaction, TransactionType};

/// Maximum transaction data size (256 KB)
const MAX_TX_DATA_SIZE: usize = 262_144;

/// Maximum gas limit per transaction (30M, matches tenzro-vm)
const MAX_GAS_LIMIT: u64 = 30_000_000;

/// Minimum gas limit
const MIN_GAS_LIMIT: u64 = 21_000;

/// Maximum gas price (1000 Gwei = 1_000_000_000_000)
const MAX_GAS_PRICE: u64 = 1_000_000_000_000;

/// Minimum gas price (1 Gwei = 1_000_000_000)
const MIN_GAS_PRICE: u64 = 1_000_000_000;

/// Maximum memo length (1 KB)
const MAX_MEMO_LENGTH: usize = 1024;

/// Validation configuration for transaction checks.
#[derive(Debug, Clone)]
pub struct ValidationConfig {
    /// Expected chain ID for this network
    pub chain_id: ChainId,
    /// Maximum allowed gas limit
    pub max_gas_limit: u64,
    /// Minimum gas limit
    pub min_gas_limit: u64,
    /// Maximum gas price
    pub max_gas_price: u64,
    /// Minimum gas price
    pub min_gas_price: u64,
    /// Maximum transaction data size in bytes
    pub max_data_size: usize,
    /// Maximum memo length
    pub max_memo_length: usize,
    /// Whether to enforce strict nonce ordering
    pub strict_nonce: bool,
}

impl Default for ValidationConfig {
    fn default() -> Self {
        Self {
            chain_id: ChainId(1337), // Tenzro default chain ID
            max_gas_limit: MAX_GAS_LIMIT,
            min_gas_limit: MIN_GAS_LIMIT,
            max_gas_price: MAX_GAS_PRICE,
            min_gas_price: MIN_GAS_PRICE,
            max_data_size: MAX_TX_DATA_SIZE,
            max_memo_length: MAX_MEMO_LENGTH,
            strict_nonce: true,
        }
    }
}

impl ValidationConfig {
    /// Create a new validation config with a specific chain ID
    pub fn with_chain_id(mut self, chain_id: ChainId) -> Self {
        self.chain_id = chain_id;
        self
    }

    /// Set strict nonce enforcement
    pub fn with_strict_nonce(mut self, strict: bool) -> Self {
        self.strict_nonce = strict;
        self
    }

    /// Set gas bounds
    pub fn with_gas_bounds(mut self, min: u64, max: u64) -> Self {
        self.min_gas_limit = min;
        self.max_gas_limit = max;
        self
    }
}

/// Validation error details providing specific failure reasons.
#[derive(Debug, Clone)]
pub struct ValidationError {
    /// The field that failed validation
    pub field: String,
    /// Human-readable error message
    pub message: String,
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.field, self.message)
    }
}

/// Transaction validator enforcing network rules before signing.
pub struct TransactionValidator {
    config: ValidationConfig,
}

impl TransactionValidator {
    /// Create a new validator with default configuration
    pub fn new() -> Self {
        Self {
            config: ValidationConfig::default(),
        }
    }

    /// Create a new validator with custom configuration
    pub fn with_config(config: ValidationConfig) -> Self {
        Self { config }
    }

    /// Validate a transaction against all rules.
    ///
    /// Returns Ok(()) if valid, or a WalletError with details if invalid.
    pub fn validate(&self, tx: &Transaction) -> Result<()> {
        let mut errors = Vec::new();

        self.validate_chain_id(tx, &mut errors);
        self.validate_addresses(tx, &mut errors);
        self.validate_gas(tx, &mut errors);
        self.validate_data_size(tx, &mut errors);
        self.validate_memo(tx, &mut errors);
        self.validate_tx_type(tx, &mut errors);

        if errors.is_empty() {
            Ok(())
        } else {
            let msg = errors
                .iter()
                .map(|e| e.to_string())
                .collect::<Vec<_>>()
                .join("; ");
            Err(WalletError::TransactionValidationFailed(msg))
        }
    }

    /// Validate a transaction with a known expected nonce.
    pub fn validate_with_nonce(
        &self,
        tx: &Transaction,
        expected_nonce: Nonce,
    ) -> Result<()> {
        let mut errors = Vec::new();

        self.validate_chain_id(tx, &mut errors);
        self.validate_addresses(tx, &mut errors);
        self.validate_gas(tx, &mut errors);
        self.validate_data_size(tx, &mut errors);
        self.validate_memo(tx, &mut errors);
        self.validate_tx_type(tx, &mut errors);

        if self.config.strict_nonce && tx.nonce != expected_nonce {
            errors.push(ValidationError {
                field: "nonce".to_string(),
                message: format!(
                    "expected nonce {}, got {}",
                    expected_nonce.0, tx.nonce.0
                ),
            });
        }

        if errors.is_empty() {
            Ok(())
        } else {
            let msg = errors
                .iter()
                .map(|e| e.to_string())
                .collect::<Vec<_>>()
                .join("; ");
            Err(WalletError::TransactionValidationFailed(msg))
        }
    }

    /// Validate with balance check.
    pub fn validate_with_balance(
        &self,
        tx: &Transaction,
        available_balance: u128,
    ) -> Result<()> {
        self.validate(tx)?;

        // Calculate total cost: value + gas
        let gas_cost = (tx.gas_limit as u128)
            .checked_mul(tx.gas_price as u128)
            .ok_or_else(|| {
                WalletError::TransactionValidationFailed(
                    "gas cost overflow".to_string(),
                )
            })?;

        let value = match &tx.tx_type {
            TransactionType::Transfer { amount } => *amount,
            TransactionType::ProviderStake { amount, .. } => *amount,
            TransactionType::BridgeTransfer { amount, .. } => *amount,
            _ => 0,
        };

        let total_cost = value
            .checked_add(gas_cost)
            .ok_or_else(|| {
                WalletError::TransactionValidationFailed(
                    "total cost overflow".to_string(),
                )
            })?;

        if available_balance < total_cost {
            return Err(WalletError::InsufficientBalance {
                have: available_balance,
                need: total_cost,
            });
        }

        Ok(())
    }

    fn validate_chain_id(&self, tx: &Transaction, errors: &mut Vec<ValidationError>) {
        if tx.chain_id != self.config.chain_id {
            errors.push(ValidationError {
                field: "chain_id".to_string(),
                message: format!(
                    "expected chain ID {}, got {}",
                    self.config.chain_id.0, tx.chain_id.0
                ),
            });
        }
    }

    fn validate_addresses(&self, tx: &Transaction, errors: &mut Vec<ValidationError>) {
        if tx.from == Address::zero() {
            errors.push(ValidationError {
                field: "from".to_string(),
                message: "sender address cannot be zero".to_string(),
            });
        }

        // `to` may be zero for typed transactions where the recipient is
        // either nonexistent (contract creation, governance ops) or encoded
        // inside the typed payload (release/refund derive recipient from VM
        // state via `escrow_id`). Plain `Transfer` and `BridgeTransfer` still
        // require a non-zero recipient.
        if tx.to == Address::zero() {
            match &tx.tx_type {
                TransactionType::ContractDeploy { .. }
                | TransactionType::ReleaseEscrow { .. }
                | TransactionType::RefundEscrow { .. }
                | TransactionType::GovernancePropose { .. }
                | TransactionType::GovernanceVote { .. }
                | TransactionType::ProviderUnstake { .. } => {
                    // `to` is structurally ignored by the VM for these variants.
                }
                _ => {
                    errors.push(ValidationError {
                        field: "to".to_string(),
                        message: "recipient address cannot be zero for this transaction type".to_string(),
                    });
                }
            }
        }

        // Sender and recipient should be different for transfers
        if tx.from == tx.to
            && let TransactionType::Transfer { .. } = &tx.tx_type
        {
            errors.push(ValidationError {
                field: "to".to_string(),
                message: "cannot transfer to self".to_string(),
            });
        }
    }

    fn validate_gas(&self, tx: &Transaction, errors: &mut Vec<ValidationError>) {
        if tx.gas_limit == 0 {
            errors.push(ValidationError {
                field: "gas_limit".to_string(),
                message: "gas limit cannot be zero".to_string(),
            });
        } else if tx.gas_limit < self.config.min_gas_limit {
            errors.push(ValidationError {
                field: "gas_limit".to_string(),
                message: format!(
                    "gas limit {} below minimum {}",
                    tx.gas_limit, self.config.min_gas_limit
                ),
            });
        } else if tx.gas_limit > self.config.max_gas_limit {
            errors.push(ValidationError {
                field: "gas_limit".to_string(),
                message: format!(
                    "gas limit {} exceeds maximum {}",
                    tx.gas_limit, self.config.max_gas_limit
                ),
            });
        }

        if tx.gas_price == 0 {
            errors.push(ValidationError {
                field: "gas_price".to_string(),
                message: "gas price cannot be zero".to_string(),
            });
        } else if tx.gas_price < self.config.min_gas_price {
            errors.push(ValidationError {
                field: "gas_price".to_string(),
                message: format!(
                    "gas price {} below minimum {}",
                    tx.gas_price, self.config.min_gas_price
                ),
            });
        } else if tx.gas_price > self.config.max_gas_price {
            errors.push(ValidationError {
                field: "gas_price".to_string(),
                message: format!(
                    "gas price {} exceeds maximum {}",
                    tx.gas_price, self.config.max_gas_price
                ),
            });
        }
    }

    fn validate_data_size(&self, tx: &Transaction, errors: &mut Vec<ValidationError>) {
        let data_size = match &tx.tx_type {
            TransactionType::ContractDeploy { code, args } => code.len() + args.len(),
            TransactionType::ContractCall { function, args } => function.len() + args.len(),
            TransactionType::AgentRegister { config } => config.len(),
            TransactionType::AgentExecute { task } => task.len(),
            TransactionType::ModelInference { model_id, input } => model_id.len() + input.len(),
            TransactionType::TeeProviderRegister { attestation, info } => {
                attestation.len() + info.len()
            }
            TransactionType::GovernancePropose { proposal } => proposal.len(),
            _ => 0,
        };

        if data_size > self.config.max_data_size {
            errors.push(ValidationError {
                field: "data".to_string(),
                message: format!(
                    "transaction data size {} exceeds maximum {}",
                    data_size, self.config.max_data_size
                ),
            });
        }
    }

    fn validate_memo(&self, tx: &Transaction, errors: &mut Vec<ValidationError>) {
        if let Some(ref memo) = tx.memo
            && memo.len() > self.config.max_memo_length
        {
            errors.push(ValidationError {
                field: "memo".to_string(),
                message: format!(
                    "memo length {} exceeds maximum {}",
                    memo.len(),
                    self.config.max_memo_length
                ),
            });
        }
    }

    fn validate_tx_type(&self, tx: &Transaction, errors: &mut Vec<ValidationError>) {
        match &tx.tx_type {
            TransactionType::Transfer { amount } => {
                if *amount == 0 {
                    errors.push(ValidationError {
                        field: "amount".to_string(),
                        message: "transfer amount cannot be zero".to_string(),
                    });
                }
            }
            TransactionType::ProviderStake { amount, provider_type } => {
                if *amount == 0 {
                    errors.push(ValidationError {
                        field: "amount".to_string(),
                        message: "stake amount cannot be zero".to_string(),
                    });
                }
                if provider_type.is_empty() {
                    errors.push(ValidationError {
                        field: "provider_type".to_string(),
                        message: "provider type cannot be empty".to_string(),
                    });
                }
            }
            TransactionType::ProviderUnstake { amount } => {
                if *amount == 0 {
                    errors.push(ValidationError {
                        field: "amount".to_string(),
                        message: "unstake amount cannot be zero".to_string(),
                    });
                }
            }
            TransactionType::ContractDeploy { code, .. } => {
                if code.is_empty() {
                    errors.push(ValidationError {
                        field: "code".to_string(),
                        message: "contract code cannot be empty".to_string(),
                    });
                }
                if code.len() > 24_576 {
                    errors.push(ValidationError {
                        field: "code".to_string(),
                        message: format!(
                            "contract code size {} exceeds maximum 24576 bytes",
                            code.len()
                        ),
                    });
                }
            }
            TransactionType::ContractCall { function, .. } => {
                if function.is_empty() {
                    errors.push(ValidationError {
                        field: "function".to_string(),
                        message: "function name cannot be empty".to_string(),
                    });
                }
            }
            TransactionType::ModelInference { model_id, input } => {
                if model_id.is_empty() {
                    errors.push(ValidationError {
                        field: "model_id".to_string(),
                        message: "model ID cannot be empty".to_string(),
                    });
                }
                if input.is_empty() {
                    errors.push(ValidationError {
                        field: "input".to_string(),
                        message: "inference input cannot be empty".to_string(),
                    });
                }
            }
            TransactionType::GovernanceVote { proposal_id, .. } => {
                if proposal_id.is_empty() {
                    errors.push(ValidationError {
                        field: "proposal_id".to_string(),
                        message: "proposal ID cannot be empty".to_string(),
                    });
                }
            }
            TransactionType::BridgeTransfer {
                target_chain,
                target_address,
                amount,
            } => {
                if *amount == 0 {
                    errors.push(ValidationError {
                        field: "amount".to_string(),
                        message: "bridge transfer amount cannot be zero".to_string(),
                    });
                }
                if target_chain.is_empty() {
                    errors.push(ValidationError {
                        field: "target_chain".to_string(),
                        message: "target chain cannot be empty".to_string(),
                    });
                }
                if target_address.is_empty() {
                    errors.push(ValidationError {
                        field: "target_address".to_string(),
                        message: "target address cannot be empty".to_string(),
                    });
                }
            }
            _ => {}
        }
    }
}

impl Default for TransactionValidator {
    fn default() -> Self {
        Self::new()
    }
}

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

    fn pq_pk() -> Vec<u8> {
        MlDsaSigningKey::generate().verifying_key_bytes().to_vec()
    }

    fn create_valid_transfer() -> Transaction {
        Transaction::new(
            ChainId(1337),
            Address::new([1u8; 32]),
            Address::new([2u8; 32]),
            Nonce(0),
            TransactionType::Transfer { amount: 1000 },
            21_000,
            1_000_000_000, // 1 Gwei
            pq_pk(),
        )
    }

    #[test]
    fn test_valid_transfer() {
        let validator = TransactionValidator::new();
        let tx = create_valid_transfer();
        assert!(validator.validate(&tx).is_ok());
    }

    #[test]
    fn test_wrong_chain_id() {
        let validator = TransactionValidator::new();
        let tx = Transaction::new(
            ChainId(999),
            Address::new([1u8; 32]),
            Address::new([2u8; 32]),
            Nonce(0),
            TransactionType::Transfer { amount: 1000 },
            21_000,
            1_000_000_000,
            pq_pk(),
        );
        let err = validator.validate(&tx).unwrap_err();
        assert!(err.to_string().contains("chain ID"));
    }

    #[test]
    fn test_zero_sender() {
        let validator = TransactionValidator::new();
        let tx = Transaction::new(
            ChainId(1337),
            Address::zero(),
            Address::new([2u8; 32]),
            Nonce(0),
            TransactionType::Transfer { amount: 1000 },
            21_000,
            1_000_000_000,
            pq_pk(),
        );
        let err = validator.validate(&tx).unwrap_err();
        assert!(err.to_string().contains("sender"));
    }

    #[test]
    fn test_self_transfer() {
        let validator = TransactionValidator::new();
        let addr = Address::new([1u8; 32]);
        let tx = Transaction::new(
            ChainId(1337),
            addr,
            addr,
            Nonce(0),
            TransactionType::Transfer { amount: 1000 },
            21_000,
            1_000_000_000,
            pq_pk(),
        );
        let err = validator.validate(&tx).unwrap_err();
        assert!(err.to_string().contains("self"));
    }

    #[test]
    fn test_gas_limit_too_low() {
        let validator = TransactionValidator::new();
        let tx = Transaction::new(
            ChainId(1337),
            Address::new([1u8; 32]),
            Address::new([2u8; 32]),
            Nonce(0),
            TransactionType::Transfer { amount: 1000 },
            100, // way too low
            1_000_000_000,
            pq_pk(),
        );
        let err = validator.validate(&tx).unwrap_err();
        assert!(err.to_string().contains("gas limit"));
    }

    #[test]
    fn test_gas_limit_too_high() {
        let validator = TransactionValidator::new();
        let tx = Transaction::new(
            ChainId(1337),
            Address::new([1u8; 32]),
            Address::new([2u8; 32]),
            Nonce(0),
            TransactionType::Transfer { amount: 1000 },
            50_000_000, // exceeds 30M max
            1_000_000_000,
            pq_pk(),
        );
        let err = validator.validate(&tx).unwrap_err();
        assert!(err.to_string().contains("gas limit"));
    }

    #[test]
    fn test_zero_transfer_amount() {
        let validator = TransactionValidator::new();
        let tx = Transaction::new(
            ChainId(1337),
            Address::new([1u8; 32]),
            Address::new([2u8; 32]),
            Nonce(0),
            TransactionType::Transfer { amount: 0 },
            21_000,
            1_000_000_000,
            pq_pk(),
        );
        let err = validator.validate(&tx).unwrap_err();
        assert!(err.to_string().contains("amount"));
    }

    #[test]
    fn test_nonce_validation() {
        let validator = TransactionValidator::new();
        let tx = create_valid_transfer();

        // Expected nonce 0, tx has nonce 0 → OK
        assert!(validator.validate_with_nonce(&tx, Nonce(0)).is_ok());

        // Expected nonce 1, tx has nonce 0 → fail
        let err = validator.validate_with_nonce(&tx, Nonce(1)).unwrap_err();
        assert!(err.to_string().contains("nonce"));
    }

    #[test]
    fn test_balance_validation() {
        let validator = TransactionValidator::new();
        let tx = create_valid_transfer();

        // gas_cost = 21_000 * 1_000_000_000 = 21_000_000_000_000
        // value = 1000
        // total = 21_000_000_001_000
        let sufficient = 22_000_000_000_000u128;
        assert!(validator.validate_with_balance(&tx, sufficient).is_ok());

        let insufficient = 100u128;
        let err = validator.validate_with_balance(&tx, insufficient).unwrap_err();
        assert!(err.to_string().contains("Insufficient"));
    }

    #[test]
    fn test_contract_code_too_large() {
        let validator = TransactionValidator::new();
        let tx = Transaction::new(
            ChainId(1337),
            Address::new([1u8; 32]),
            Address::zero(), // zero for contract deploy
            Nonce(0),
            TransactionType::ContractDeploy {
                code: vec![0u8; 25_000], // exceeds 24576
                args: vec![],
            },
            1_000_000,
            1_000_000_000,
            pq_pk(),
        );
        let err = validator.validate(&tx).unwrap_err();
        assert!(err.to_string().contains("contract code size"));
    }

    #[test]
    fn test_memo_too_long() {
        let validator = TransactionValidator::new();
        let mut tx = create_valid_transfer();
        tx.memo = Some("x".repeat(2000));
        let err = validator.validate(&tx).unwrap_err();
        assert!(err.to_string().contains("memo"));
    }

    #[test]
    fn test_custom_config() {
        let config = ValidationConfig::default()
            .with_chain_id(ChainId(42))
            .with_gas_bounds(10_000, 50_000_000);

        let validator = TransactionValidator::with_config(config);

        let tx = Transaction::new(
            ChainId(42),
            Address::new([1u8; 32]),
            Address::new([2u8; 32]),
            Nonce(0),
            TransactionType::Transfer { amount: 1000 },
            21_000,
            1_000_000_000,
            pq_pk(),
        );
        assert!(validator.validate(&tx).is_ok());
    }
}