onemoney-protocol 0.18.0

Official Rust SDK for OneMoney Protocol - L1 blockchain network client
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
//! Comprehensive cryptographic integration tests
//!
//! This file contains end-to-end cryptographic integration tests including:
//! - Complete signature generation and verification chains
//! - Cross-module cryptographic operations
//! - Key derivation and address generation
//! - Transaction signing workflows

use std::{error::Error, str::FromStr};

use alloy_primitives::{Address, U256};
use onemoney_protocol::{
    Signable, TokenMintPayload,
    crypto::{private_key_to_address, sign_transaction_payload},
};

//
// ============================================================================
// ADDRESS DERIVATION INTEGRATION TESTS
// ============================================================================
//

#[test]
fn test_address_derivation_integration() -> Result<(), Box<dyn Error>> {
    // Test with known private key
    let private_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

    let address1 = private_key_to_address(private_key)?;

    // Address should be valid format
    assert_eq!(address1.len(), 20);

    // Same private key should always produce same address
    let address2 = private_key_to_address(private_key)?;
    assert_eq!(address1, address2);

    println!("Derived address: {}", address1);
    Ok(())
}

#[test]
fn test_multiple_private_keys_produce_unique_addresses() -> Result<(), Box<dyn Error>> {
    let private_keys = [
        "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
        "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210",
        "1111111111111111111111111111111111111111111111111111111111111111",
        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
    ];

    let mut addresses = Vec::new();

    // Generate addresses from all private keys
    for private_key in &private_keys {
        let address = private_key_to_address(private_key)?;
        addresses.push(address);
    }

    // Verify all addresses are unique
    for i in 0..addresses.len() {
        for j in (i + 1)..addresses.len() {
            assert_ne!(
                addresses[i], addresses[j],
                "Private keys {} and {} produced the same address: {}",
                private_keys[i], private_keys[j], addresses[i]
            );
        }
    }

    println!(
        "Generated {} unique addresses from {} private keys",
        addresses.len(),
        private_keys.len()
    );
    Ok(())
}

#[test]
fn test_address_derivation_error_cases() {
    let invalid_keys = [
        "",                                                                    // Empty
        "123",                                                                 // Too short
        "xyz",                                                                 // Invalid characters
        "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef123", // Too long
        "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0",   // Too short (63 chars)
        "gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg",    // Invalid hex chars
    ];

    for invalid_key in &invalid_keys {
        let result = private_key_to_address(invalid_key);
        assert!(
            result.is_err(),
            "Invalid private key '{}' should produce an error, but got: {:?}",
            invalid_key,
            result
        );
    }
}

//
// ============================================================================
// TRANSACTION SIGNING INTEGRATION TESTS
// ============================================================================
//

#[test]
fn test_token_mint_payload_signing_integration() -> Result<(), Box<dyn Error>> {
    // Create a test token mint payload
    let token_address = Address::from_str("0x1234567890abcdef1234567890abcdef12345678")?;
    let to_address = Address::from_str("0xabcdefabcdefabcdefabcdefabcdefabcdefabcd")?;
    let amount = U256::from(1000000000000000000u64); // 1 token with 18 decimals

    let payload = TokenMintPayload {
        chain_id: 1,
        nonce: 1,
        token: token_address,
        recipient: to_address,
        value: amount,
    };

    // Test that payload implements Signable trait
    let hash = payload.signature_hash();
    assert_eq!(hash.len(), 32); // keccak256 produces 32 bytes

    // Test that hash is deterministic
    let hash2 = payload.signature_hash();
    assert_eq!(hash, hash2);

    // Test signing with different payloads produces different hashes
    let payload2 = TokenMintPayload {
        chain_id: 1,
        nonce: 2,
        token: token_address,
        recipient: to_address,
        value: U256::from(2000000000000000000u64), // Different amount
    };

    let hash3 = payload2.signature_hash();
    assert_ne!(hash, hash3);

    println!("Token mint payload hash: {:?}", hash);
    Ok(())
}

#[test]
fn test_end_to_end_transaction_signing() -> Result<(), Box<dyn Error>> {
    // Test complete workflow: create payload -> sign -> verify
    let private_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

    // Create payload
    let token_address = Address::from_str("0x1234567890abcdef1234567890abcdef12345678")?;
    let to_address = Address::from_str("0xabcdefabcdefabcdefabcdefabcdefabcdefabcd")?;
    let amount = U256::from(1000000000000000000u64);

    let payload = TokenMintPayload {
        chain_id: 1,
        nonce: 1,
        token: token_address,
        recipient: to_address,
        value: amount,
    };

    // Sign the payload
    let signature = sign_transaction_payload(&payload, private_key)?;

    // Verify signature has correct structure
    assert_ne!(signature.r, U256::ZERO);
    assert_ne!(signature.s, U256::ZERO);
    assert!(signature.v == 27 || signature.v == 28 || signature.v == 0 || signature.v == 1);

    // Test that same payload with same key produces same signature
    let signature2 = sign_transaction_payload(&payload, private_key)?;
    assert_eq!(signature.r, signature2.r);
    assert_eq!(signature.s, signature2.s);
    assert_eq!(signature.v, signature2.v);

    // Test that different payload produces different signature
    let payload2 = TokenMintPayload {
        chain_id: 1,
        nonce: 2,
        token: token_address,
        recipient: to_address,
        value: U256::from(2000000000000000000u64), // Different amount
    };

    let signature3 = sign_transaction_payload(&payload2, private_key)?;
    assert!(signature.r != signature3.r || signature.s != signature3.s);

    println!(
        "Transaction signature: r={}, s={}, v={}",
        signature.r, signature.s, signature.v
    );
    Ok(())
}

#[test]
fn test_signature_determinism_across_restarts() -> Result<(), Box<dyn Error>> {
    // Test that signatures are deterministic across multiple runs
    let private_key = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210";

    let token_address = Address::from_str("0x9999999999999999999999999999999999999999")?;
    let to_address = Address::from_str("0x8888888888888888888888888888888888888888")?;
    let amount = U256::from(5000000000000000000u64);

    let payload = TokenMintPayload {
        chain_id: 1,
        nonce: 1,
        token: token_address,
        recipient: to_address,
        value: amount,
    };

    // Generate multiple signatures to ensure determinism
    let signatures: Vec<_> = (0..5)
        .map(|_| sign_transaction_payload(&payload, private_key))
        .collect::<Result<Vec<_>, _>>()?;

    // All signatures should be identical
    for i in 1..signatures.len() {
        assert_eq!(signatures[0].r, signatures[i].r);
        assert_eq!(signatures[0].s, signatures[i].s);
        assert_eq!(signatures[0].v, signatures[i].v);
    }

    Ok(())
}

//
// ============================================================================
// CRYPTOGRAPHIC WORKFLOW INTEGRATION TESTS
// ============================================================================
//

#[test]
fn test_complete_key_to_signature_workflow() -> Result<(), Box<dyn Error>> {
    // Test complete workflow from private key to signature
    let private_key = "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890";

    // Step 1: Derive address from private key
    let derived_address = private_key_to_address(private_key)?;

    // Step 2: Create transaction payload involving the derived address
    let token_address = Address::from_str("0x1111111111111111111111111111111111111111")?;
    let amount = U256::from(1500000000000000000u64);

    let payload = TokenMintPayload {
        chain_id: 1,
        nonce: 3,
        token: token_address,
        recipient: derived_address, // Using the derived address as recipient
        value: amount,
    };

    // Step 3: Sign the payload with the private key
    let signature = sign_transaction_payload(&payload, private_key)?;

    // Step 4: Verify all components are valid
    assert_ne!(signature.r, U256::ZERO);
    assert_ne!(signature.s, U256::ZERO);

    // Step 5: Verify hash consistency
    let payload_hash = payload.signature_hash();
    assert_eq!(payload_hash.len(), 32);

    println!(
        "Complete workflow: key={} -> address={} -> signature=(r={}, s={}, v={})",
        &private_key[..8], // Show first 8 chars for privacy
        derived_address,
        signature.r,
        signature.s,
        signature.v
    );

    Ok(())
}

#[test]
fn test_multiple_transaction_types_signing() -> Result<(), Box<dyn Error>> {
    // Test signing different types of payloads with the same key
    let private_key = "5555555555555555555555555555555555555555555555555555555555555555";

    // Create multiple different payloads
    let token1 = Address::from_str("0x1111111111111111111111111111111111111111")?;
    let token2 = Address::from_str("0x2222222222222222222222222222222222222222")?;
    let recipient1 = Address::from_str("0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")?;
    let recipient2 = Address::from_str("0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")?;

    let payloads = [
        TokenMintPayload {
            chain_id: 1,
            nonce: 1,
            token: token1,
            recipient: recipient1,
            value: U256::from(1000u64),
        },
        TokenMintPayload {
            chain_id: 1,
            nonce: 1,
            token: token1,
            recipient: recipient2,
            value: U256::from(2000u64),
        },
        TokenMintPayload {
            chain_id: 1,
            nonce: 1,
            token: token2,
            recipient: recipient1,
            value: U256::from(3000u64),
        },
        TokenMintPayload {
            chain_id: 1,
            nonce: 1,
            token: token2,
            recipient: recipient2,
            value: U256::from(4000u64),
        },
    ];

    let mut signatures = Vec::new();
    let mut hashes = Vec::new();

    // Sign all payloads
    for payload in &payloads {
        let signature = sign_transaction_payload(payload, private_key)?;
        let hash = payload.signature_hash();

        signatures.push(signature);
        hashes.push(hash);
    }

    // Verify all signatures are different (different payloads)
    for i in 0..signatures.len() {
        for j in (i + 1)..signatures.len() {
            assert!(
                signatures[i].r != signatures[j].r || signatures[i].s != signatures[j].s,
                "Signatures {} and {} should be different but are the same",
                i,
                j
            );
        }
    }

    // Verify all hashes are different
    for i in 0..hashes.len() {
        for j in (i + 1)..hashes.len() {
            assert_ne!(
                hashes[i], hashes[j],
                "Hashes {} and {} should be different but are the same",
                i, j
            );
        }
    }

    println!("Successfully signed {} different payloads", payloads.len());
    Ok(())
}

//
// ============================================================================
// CRYPTOGRAPHIC EDGE CASES AND ERROR HANDLING
// ============================================================================
//

#[test]
fn test_signing_with_invalid_private_keys() {
    let invalid_keys = [
        "",                                                                    // Empty
        "123",                                                                 // Too short
        "xyz",                                                                 // Invalid characters
        "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef123", // Too long
    ];

    let token_address = Address::from_str("0x1234567890abcdef1234567890abcdef12345678").unwrap();
    let to_address = Address::from_str("0xabcdefabcdefabcdefabcdefabcdefabcdefabcd").unwrap();
    let amount = U256::from(1000u64);

    let payload = TokenMintPayload {
        chain_id: 1,
        nonce: 1,
        token: token_address,
        recipient: to_address,
        value: amount,
    };

    for invalid_key in &invalid_keys {
        let result = sign_transaction_payload(&payload, invalid_key);
        assert!(
            result.is_err(),
            "Invalid private key '{}' should produce an error, but signing succeeded",
            invalid_key
        );
    }
}

#[test]
fn test_extreme_value_handling() -> Result<(), Box<dyn Error>> {
    // Test signing with extreme values
    let private_key = "7777777777777777777777777777777777777777777777777777777777777777";

    let zero_address = Address::ZERO;
    let max_address = Address::from([0xFF; 20]);

    let payloads = [
        // Zero amount
        TokenMintPayload {
            chain_id: 1,
            nonce: 1,
            token: zero_address,
            recipient: zero_address,
            value: U256::ZERO,
        },
        // Maximum amount
        TokenMintPayload {
            chain_id: 1,
            nonce: 1,
            token: max_address,
            recipient: max_address,
            value: U256::MAX,
        },
        // Mixed extremes
        TokenMintPayload {
            chain_id: 1,
            nonce: 1,
            token: zero_address,
            recipient: max_address,
            value: U256::from(1u64),
        },
    ];

    for (i, payload) in payloads.iter().enumerate() {
        let signature = sign_transaction_payload(payload, private_key)?;

        // Verify signature is valid structure
        assert_ne!(signature.r, U256::ZERO, "Signature {} has zero r component", i);
        assert_ne!(signature.s, U256::ZERO, "Signature {} has zero s component", i);

        // Verify hash is generated
        let hash = payload.signature_hash();
        assert_eq!(hash.len(), 32, "Payload {} hash should be 32 bytes", i);
    }

    Ok(())
}

#[test]
fn test_concurrent_signing_consistency() -> Result<(), Box<dyn Error>> {
    // Test that concurrent signing operations produce consistent results
    use std::{
        sync::{Arc, Mutex},
        thread,
    };

    let private_key = "8888888888888888888888888888888888888888888888888888888888888888";
    let token_address = Address::from_str("0x3333333333333333333333333333333333333333")?;
    let to_address = Address::from_str("0x4444444444444444444444444444444444444444")?;
    let amount = U256::from(7777777777777777777u64);

    let payload = TokenMintPayload {
        chain_id: 1,
        nonce: 1,
        token: token_address,
        recipient: to_address,
        value: amount,
    };

    let signatures = Arc::new(Mutex::new(Vec::new()));
    let mut handles = Vec::new();

    // Spawn multiple threads to sign the same payload
    for _ in 0..5 {
        let payload_clone = payload.clone();
        let signatures_clone = Arc::clone(&signatures);
        let private_key_str = private_key.to_string();

        let handle = thread::spawn(move || {
            let signature = sign_transaction_payload(&payload_clone, &private_key_str).unwrap();
            signatures_clone.lock().unwrap().push(signature);
        });
        handles.push(handle);
    }

    // Wait for all threads to complete
    for handle in handles {
        handle.join().unwrap();
    }

    let signatures = signatures.lock().unwrap();
    assert_eq!(signatures.len(), 5);

    // All signatures should be identical
    for i in 1..signatures.len() {
        assert_eq!(signatures[0].r, signatures[i].r);
        assert_eq!(signatures[0].s, signatures[i].s);
        assert_eq!(signatures[0].v, signatures[i].v);
    }

    Ok(())
}

//
// ============================================================================
// PERFORMANCE AND SCALABILITY TESTS
// ============================================================================
//

#[test]
fn test_signing_performance_baseline() -> Result<(), Box<dyn Error>> {
    // Test that signing operations complete within reasonable time
    use std::time::Instant;

    let private_key = "9999999999999999999999999999999999999999999999999999999999999999";
    let token_address = Address::from_str("0x5555555555555555555555555555555555555555")?;
    let to_address = Address::from_str("0x6666666666666666666666666666666666666666")?;
    let amount = U256::from(12345678901234567890u64);

    let _payload = TokenMintPayload {
        chain_id: 1,
        nonce: 1,
        token: token_address,
        recipient: to_address,
        value: amount,
    };

    let iterations = 100;
    let start = Instant::now();

    // Perform multiple signing operations
    for i in 0..iterations {
        let test_payload = TokenMintPayload {
            chain_id: 1,
            nonce: 1,
            token: token_address,
            recipient: to_address,
            value: amount + U256::from(i), // Slightly different each time
        };

        let _signature = sign_transaction_payload(&test_payload, private_key)?;
    }

    let duration = start.elapsed();
    let avg_time_per_signature = duration / iterations;

    println!(
        "Signed {} transactions in {:?} (avg: {:?} per signature)",
        iterations, duration, avg_time_per_signature
    );

    // Sanity check: each signature should complete in reasonable time
    assert!(
        avg_time_per_signature.as_millis() < 100,
        "Average signing time {} ms is too slow",
        avg_time_per_signature.as_millis()
    );

    Ok(())
}