sal-vault 0.1.0

SAL Vault - Cryptographic functionality including key management, digital signatures, symmetric encryption, Ethereum wallets, and encrypted key-value store
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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
//! Rhai bindings for SAL vault functionality

use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};

use ethers::types::{Address, U256};
use hex;
use once_cell::sync::Lazy;
use rhai::{Dynamic, Engine, EvalAltResult};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Mutex;
use tokio::runtime::Runtime;

use crate::{ethereum, keyspace};

use crate::symmetric::implementation as symmetric_impl;
// Global Tokio runtime for blocking async operations
static RUNTIME: Lazy<Mutex<Runtime>> =
    Lazy::new(|| Mutex::new(Runtime::new().expect("Failed to create Tokio runtime")));

// Global provider registry
static PROVIDERS: Lazy<
    Mutex<HashMap<String, ethers::providers::Provider<ethers::providers::Http>>>,
> = Lazy::new(|| Mutex::new(HashMap::new()));

// Global keyspace registry for testing (stores keyspaces with their passwords)
static KEYSPACE_REGISTRY: Lazy<Mutex<HashMap<String, (keyspace::KeySpace, String)>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

// Key space management functions
fn load_key_space(name: &str, password: &str) -> bool {
    // Get the key spaces directory from config
    let home_dir = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
    let key_spaces_dir = home_dir.join(".hero-vault").join("key-spaces");

    // Check if directory exists
    if !key_spaces_dir.exists() {
        log::error!("Key spaces directory does not exist");
        return false;
    }

    // Get the key space file path
    let space_path = key_spaces_dir.join(format!("{}.json", name));

    // Check if file exists
    if !space_path.exists() {
        log::error!("Key space file not found: {}", space_path.display());
        return false;
    }

    // Read the file
    let serialized = match fs::read_to_string(&space_path) {
        Ok(data) => data,
        Err(e) => {
            log::error!("Error reading key space file: {}", e);
            return false;
        }
    };

    // Deserialize the encrypted space
    let encrypted_space = match symmetric_impl::deserialize_encrypted_space(&serialized) {
        Ok(space) => space,
        Err(e) => {
            log::error!("Error deserializing key space: {}", e);
            return false;
        }
    };

    // Decrypt the space
    let space = match symmetric_impl::decrypt_key_space(&encrypted_space, password) {
        Ok(space) => space,
        Err(e) => {
            log::error!("Error decrypting key space: {}", e);
            return false;
        }
    };

    // Set as current space
    match keyspace::set_current_space(space) {
        Ok(_) => true,
        Err(e) => {
            log::error!("Error setting current space: {}", e);
            false
        }
    }
}

fn create_key_space(name: &str, password: &str) -> bool {
    match keyspace::session_manager::create_space(name) {
        Ok(_) => {
            // Get the current space
            match keyspace::get_current_space() {
                Ok(space) => {
                    // Store in registry for testing
                    if let Ok(mut registry) = KEYSPACE_REGISTRY.lock() {
                        registry.insert(name.to_string(), (space.clone(), password.to_string()));
                    }

                    // Encrypt the key space
                    let encrypted_space = match symmetric_impl::encrypt_key_space(&space, password)
                    {
                        Ok(encrypted) => encrypted,
                        Err(e) => {
                            log::error!("Error encrypting key space: {}", e);
                            return false;
                        }
                    };

                    // Serialize the encrypted space
                    let serialized =
                        match symmetric_impl::serialize_encrypted_space(&encrypted_space) {
                            Ok(json) => json,
                            Err(e) => {
                                log::error!("Error serializing encrypted space: {}", e);
                                return false;
                            }
                        };

                    // Get the key spaces directory
                    let home_dir = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
                    let key_spaces_dir = home_dir.join(".hero-vault").join("key-spaces");

                    // Create directory if it doesn't exist
                    if !key_spaces_dir.exists() {
                        match fs::create_dir_all(&key_spaces_dir) {
                            Ok(_) => {}
                            Err(e) => {
                                log::error!("Error creating key spaces directory: {}", e);
                                return false;
                            }
                        }
                    }

                    // Write to file
                    let space_path = key_spaces_dir.join(format!("{}.json", name));
                    match fs::write(&space_path, serialized) {
                        Ok(_) => {
                            log::info!("Key space created and saved to {}", space_path.display());
                            true
                        }
                        Err(e) => {
                            log::error!("Error writing key space file: {}", e);
                            false
                        }
                    }
                }
                Err(e) => {
                    log::error!("Error getting current space: {}", e);
                    false
                }
            }
        }
        Err(e) => {
            log::error!("Error creating key space: {}", e);
            false
        }
    }
}

// Auto-save function for internal use
fn auto_save_key_space(password: &str) -> bool {
    match keyspace::get_current_space() {
        Ok(space) => {
            // Encrypt the key space
            let encrypted_space = match symmetric_impl::encrypt_key_space(&space, password) {
                Ok(encrypted) => encrypted,
                Err(e) => {
                    log::error!("Error encrypting key space: {}", e);
                    return false;
                }
            };

            // Serialize the encrypted space
            let serialized = match symmetric_impl::serialize_encrypted_space(&encrypted_space) {
                Ok(json) => json,
                Err(e) => {
                    log::error!("Error serializing encrypted space: {}", e);
                    return false;
                }
            };

            // Get the key spaces directory
            let home_dir = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
            let key_spaces_dir = home_dir.join(".hero-vault").join("key-spaces");

            // Create directory if it doesn't exist
            if !key_spaces_dir.exists() {
                match fs::create_dir_all(&key_spaces_dir) {
                    Ok(_) => {}
                    Err(e) => {
                        log::error!("Error creating key spaces directory: {}", e);
                        return false;
                    }
                }
            }

            // Write to file
            let space_path = key_spaces_dir.join(format!("{}.json", space.name));
            match fs::write(&space_path, serialized) {
                Ok(_) => {
                    log::info!("Key space saved to {}", space_path.display());
                    true
                }
                Err(e) => {
                    log::error!("Error writing key space file: {}", e);
                    false
                }
            }
        }
        Err(e) => {
            log::error!("Error getting current space: {}", e);
            false
        }
    }
}

fn encrypt_key_space(password: &str) -> String {
    match keyspace::get_current_space() {
        Ok(space) => match symmetric_impl::encrypt_key_space(&space, password) {
            Ok(encrypted_space) => match serde_json::to_string(&encrypted_space) {
                Ok(json) => json,
                Err(e) => {
                    log::error!("Error serializing encrypted space: {}", e);
                    String::new()
                }
            },
            Err(e) => {
                log::error!("Error encrypting key space: {}", e);
                String::new()
            }
        },
        Err(e) => {
            log::error!("Error getting current space: {}", e);
            String::new()
        }
    }
}

fn decrypt_key_space(encrypted: &str, password: &str) -> bool {
    match serde_json::from_str(encrypted) {
        Ok(encrypted_space) => {
            match symmetric_impl::decrypt_key_space(&encrypted_space, password) {
                Ok(space) => match keyspace::set_current_space(space) {
                    Ok(_) => true,
                    Err(e) => {
                        log::error!("Error setting current space: {}", e);
                        false
                    }
                },
                Err(e) => {
                    log::error!("Error decrypting key space: {}", e);
                    false
                }
            }
        }
        Err(e) => {
            log::error!("Error parsing encrypted space: {}", e);
            false
        }
    }
}

// keyspace management functions
fn create_keyspace(name: &str, password: &str) -> bool {
    match keyspace::session_manager::create_keypair(name) {
        Ok(_) => {
            // Auto-save the key space after creating a keyspace
            auto_save_key_space(password)
        }
        Err(e) => {
            log::error!("Error creating keyspace: {}", e);
            false
        }
    }
}

fn select_keyspace(name: &str) -> bool {
    // First check if it's already the current keyspace
    {
        let session = crate::keyspace::session_manager::SESSION.lock().unwrap();
        if let Some(ref current_space_obj) = session.current_space {
            if current_space_obj.name == name {
                log::debug!("Keyspace '{}' is already selected.", name);
                return true;
            }
        }
    }

    // Before switching, save the current keyspace state to registry
    if let Ok(current_space) = keyspace::get_current_space() {
        if let Ok(mut registry) = KEYSPACE_REGISTRY.lock() {
            // Find the password for the current space
            if let Some((_, password)) = registry.get(&current_space.name).cloned() {
                // Update the registry with the current state
                registry.insert(current_space.name.clone(), (current_space, password));
            }
        }
    }

    // Try to get from registry first (for testing)
    if let Ok(registry) = KEYSPACE_REGISTRY.lock() {
        if let Some((space, _password)) = registry.get(name) {
            match keyspace::session_manager::set_current_space(space.clone()) {
                Ok(_) => {
                    log::debug!("Selected keyspace '{}' from registry", name);
                    return true;
                }
                Err(e) => {
                    log::error!("Error setting current space: {}", e);
                    return false;
                }
            }
        }
    }

    log::warn!("Keyspace '{}' not found in registry. Use 'load_key_space(name, password)' to load from disk.", name);
    false
}

fn rhai_list_keyspaces_actual() -> Vec<String> {
    let home_dir = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
    let key_spaces_dir = home_dir.join(".hero-vault").join("key-spaces");

    if !key_spaces_dir.exists() {
        log::debug!(
            "Key spaces directory does not exist: {}",
            key_spaces_dir.display()
        );
        return Vec::new();
    }

    let mut spaces = Vec::new();
    match std::fs::read_dir(key_spaces_dir) {
        Ok(entries) => {
            for entry in entries {
                if let Ok(entry) = entry {
                    let path = entry.path();
                    if path.is_file() {
                        if let Some(ext) = path.extension() {
                            if ext == "json" {
                                if let Some(stem) = path.file_stem() {
                                    if let Some(name) = stem.to_str() {
                                        spaces.push(name.to_string());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        Err(e) => {
            log::error!("Error reading key spaces directory: {}", e);
        }
    }
    spaces
}

fn rhai_list_keypairs() -> Vec<String> {
    match keyspace::session_manager::list_keypairs() {
        Ok(keypairs) => keypairs,
        Err(e) => {
            log::error!("Error listing keypairs: {}", e);
            Vec::new()
        }
    }
}

fn rhai_count_keyspaces() -> i64 {
    rhai_list_keyspaces_actual().len() as i64
}

fn rhai_count_keypairs() -> i64 {
    rhai_list_keypairs().len() as i64
}

fn rhai_select_keypair(name: &str) -> bool {
    match keyspace::session_manager::select_keypair(name) {
        Ok(_) => true,
        Err(e) => {
            log::error!("Error selecting keypair '{}': {}", name, e);
            false
        }
    }
}

fn rhai_clear_session() {
    keyspace::session_manager::clear_session();
    // Also clear the registry for testing
    if let Ok(mut registry) = KEYSPACE_REGISTRY.lock() {
        registry.clear();
    }
}

fn rhai_create_keypair(name: &str) -> bool {
    match keyspace::session_manager::create_keypair(name) {
        Ok(_) => {
            // Update the registry with the current state after creating keypair
            if let Ok(current_space) = keyspace::get_current_space() {
                if let Ok(mut registry) = KEYSPACE_REGISTRY.lock() {
                    // Find the password for the current space
                    if let Some((_, password)) = registry.get(&current_space.name).cloned() {
                        // Update the registry with the current state
                        registry.insert(current_space.name.clone(), (current_space, password));
                    }
                }
            }
            true
        }
        Err(e) => {
            log::error!("Error creating keypair '{}': {}", name, e);
            false
        }
    }
}

// Rhai wrapper for getting the public key of the selected keypair
fn rhai_keypair_pub_key() -> Result<String, Box<EvalAltResult>> {
    match keyspace::session_manager::get_selected_keypair() {
        Ok(keypair) => Ok(hex::encode(keypair.pub_key())),
        Err(e) => Err(Box::new(EvalAltResult::ErrorSystem(
            "Failed to get public key".to_string(),
            Box::new(e),
        ))),
    }
}

// Cryptographic operations
fn sign(message: &str) -> String {
    let message_bytes = message.as_bytes();
    match keyspace::session_manager::keypair_sign(message_bytes) {
        Ok(signature_bytes) => BASE64.encode(signature_bytes),
        Err(e) => {
            log::error!("Error signing message: {}", e);
            String::new()
        }
    }
}

fn verify(message: &str, signature: &str) -> bool {
    let message_bytes = message.as_bytes();
    match BASE64.decode(signature) {
        Ok(signature_bytes) => {
            match keyspace::session_manager::keypair_verify(message_bytes, &signature_bytes) {
                Ok(is_valid) => is_valid,
                Err(e) => {
                    log::error!("Error verifying signature: {}", e);
                    false
                }
            }
        }
        Err(e) => {
            log::error!("Error decoding signature: {}", e);
            false
        }
    }
}

// Symmetric encryption
fn generate_key() -> String {
    let key = symmetric_impl::generate_symmetric_key();
    BASE64.encode(key)
}

fn encrypt(key: &str, message: &str) -> String {
    match BASE64.decode(key) {
        Ok(key_bytes) => {
            let message_bytes = message.as_bytes();
            match symmetric_impl::encrypt_symmetric(&key_bytes, message_bytes) {
                Ok(ciphertext) => BASE64.encode(ciphertext),
                Err(e) => {
                    log::error!("Error encrypting message: {}", e);
                    String::new()
                }
            }
        }
        Err(e) => {
            log::error!("Error decoding key: {}", e);
            String::new()
        }
    }
}

fn decrypt(key: &str, ciphertext: &str) -> String {
    match BASE64.decode(key) {
        Ok(key_bytes) => match BASE64.decode(ciphertext) {
            Ok(ciphertext_bytes) => {
                match symmetric_impl::decrypt_symmetric(&key_bytes, &ciphertext_bytes) {
                    Ok(plaintext) => match String::from_utf8(plaintext) {
                        Ok(text) => text,
                        Err(e) => {
                            log::error!("Error converting plaintext to string: {}", e);
                            String::new()
                        }
                    },
                    Err(e) => {
                        log::error!("Error decrypting ciphertext: {}", e);
                        String::new()
                    }
                }
            }
            Err(e) => {
                log::error!("Error decoding ciphertext: {}", e);
                String::new()
            }
        },
        Err(e) => {
            log::error!("Error decoding key: {}", e);
            String::new()
        }
    }
}

// Ethereum operations

// Gnosis Chain operations
fn create_ethereum_wallet() -> bool {
    match ethereum::create_ethereum_wallet_for_network(ethereum::networks::gnosis()) {
        Ok(_) => true,
        Err(e) => {
            log::error!("Error creating Ethereum wallet: {}", e);
            false
        }
    }
}

fn get_ethereum_address() -> String {
    match ethereum::get_current_ethereum_wallet_for_network("Gnosis") {
        Ok(wallet) => wallet.address_string(),
        Err(e) => {
            log::error!("Error getting Ethereum address: {}", e);
            String::new()
        }
    }
}

// Peaq network operations
fn create_peaq_wallet() -> bool {
    match ethereum::create_peaq_wallet() {
        Ok(_) => true,
        Err(e) => {
            log::error!("Error creating Peaq wallet: {}", e);
            false
        }
    }
}

fn get_peaq_address() -> String {
    match ethereum::get_current_peaq_wallet() {
        Ok(wallet) => wallet.address_string(),
        Err(e) => {
            log::error!("Error getting Peaq address: {}", e);
            String::new()
        }
    }
}

// Agung testnet operations
fn create_agung_wallet() -> bool {
    match ethereum::create_agung_wallet() {
        Ok(_) => true,
        Err(e) => {
            log::error!("Error creating Agung wallet: {}", e);
            false
        }
    }
}

fn get_agung_address() -> String {
    match ethereum::get_current_agung_wallet() {
        Ok(wallet) => wallet.address_string(),
        Err(e) => {
            log::error!("Error getting Agung address: {}", e);
            String::new()
        }
    }
}

// Generic network operations
fn create_wallet_for_network(network_name: &str) -> bool {
    let network = match ethereum::networks::get_network_by_name(network_name) {
        Some(network) => network,
        None => {
            log::error!("Unknown network: {}", network_name);
            return false;
        }
    };

    match ethereum::create_ethereum_wallet_for_network(network) {
        Ok(_) => true,
        Err(e) => {
            log::error!("Error creating wallet for network {}: {}", network_name, e);
            false
        }
    }
}

// Get wallet address for a specific network
fn get_wallet_address_for_network(network_name: &str) -> String {
    let network_name_proper = match ethereum::networks::get_proper_network_name(network_name) {
        Some(name) => name,
        None => {
            log::error!("Unknown network: {}", network_name);
            return String::new();
        }
    };

    match ethereum::get_current_ethereum_wallet_for_network(network_name_proper) {
        Ok(wallet) => wallet.address_string(),
        Err(e) => {
            log::error!(
                "Error getting wallet address for network {}: {}",
                network_name,
                e
            );
            String::new()
        }
    }
}

// Clear wallets for a specific network
fn clear_wallets_for_network(network_name: &str) -> bool {
    let network_name_proper = match ethereum::networks::get_proper_network_name(network_name) {
        Some(name) => name,
        None => {
            log::error!("Unknown network: {}", network_name);
            return false;
        }
    };

    ethereum::clear_ethereum_wallets_for_network(network_name_proper);
    true
}

// List supported networks
fn list_supported_networks() -> rhai::Array {
    let mut arr = rhai::Array::new();
    for name in ethereum::networks::list_network_names() {
        arr.push(Dynamic::from(name.to_lowercase()));
    }
    arr
}

// Get network token symbol
fn get_network_token_symbol(network_name: &str) -> String {
    match ethereum::networks::get_network_by_name(network_name) {
        Some(network) => network.token_symbol,
        None => {
            log::error!("Unknown network: {}", network_name);
            String::new()
        }
    }
}

// Get network explorer URL
fn get_network_explorer_url(network_name: &str) -> String {
    match ethereum::networks::get_network_by_name(network_name) {
        Some(network) => network.explorer_url,
        None => {
            log::error!("Unknown network: {}", network_name);
            String::new()
        }
    }
}

// Create a wallet from a private key for a specific network
fn create_wallet_from_private_key_for_network(private_key: &str, network_name: &str) -> bool {
    let network = match ethereum::networks::get_network_by_name(network_name) {
        Some(network) => network,
        None => {
            log::error!("Unknown network: {}", network_name);
            return false;
        }
    };

    match ethereum::create_ethereum_wallet_from_private_key_for_network(private_key, network) {
        Ok(_) => true,
        Err(e) => {
            log::error!(
                "Error creating wallet from private key for network {}: {}",
                network_name,
                e
            );
            false
        }
    }
}

// Create a provider for the Agung network
fn create_agung_provider() -> String {
    match ethereum::create_agung_provider() {
        Ok(provider) => {
            // Generate a unique ID for the provider
            let id = format!("provider_{}", uuid::Uuid::new_v4());

            // Store the provider in the registry
            if let Ok(mut providers) = PROVIDERS.lock() {
                providers.insert(id.clone(), provider);
                return id;
            }

            log::error!("Failed to acquire provider registry lock");
            String::new()
        }
        Err(e) => {
            log::error!("Error creating Agung provider: {}", e);
            String::new()
        }
    }
}

// Get the balance of an address on a specific network
fn get_balance(network_name: &str, address: &str) -> String {
    // Get the runtime
    let rt = match RUNTIME.lock() {
        Ok(rt) => rt,
        Err(e) => {
            log::error!("Failed to acquire runtime lock: {}", e);
            return String::new();
        }
    };

    // Parse the address
    let addr = match Address::from_str(address) {
        Ok(addr) => addr,
        Err(e) => {
            log::error!("Invalid address format: {}", e);
            return String::new();
        }
    };

    // Get the proper network name
    let network_name_proper = match ethereum::networks::get_proper_network_name(network_name) {
        Some(name) => name,
        None => {
            log::error!("Unknown network: {}", network_name);
            return String::new();
        }
    };

    // Get the network config
    let network = match ethereum::networks::get_network_by_name(network_name_proper) {
        Some(n) => n,
        None => {
            log::error!("Failed to get network config for: {}", network_name_proper);
            return String::new();
        }
    };

    // Create a provider
    let provider = match ethereum::create_provider(&network) {
        Ok(p) => p,
        Err(e) => {
            log::error!("Failed to create provider: {}", e);
            return String::new();
        }
    };

    // Execute the balance query in a blocking manner
    match rt.block_on(async { ethereum::get_balance(&provider, addr).await }) {
        Ok(balance) => balance.to_string(),
        Err(e) => {
            log::error!("Failed to get balance: {}", e);
            String::new()
        }
    }
}

// Send ETH from one address to another using the blocking approach
fn send_eth(wallet_network: &str, to_address: &str, amount_str: &str) -> String {
    // Get the runtime
    let rt = match RUNTIME.lock() {
        Ok(rt) => rt,
        Err(e) => {
            log::error!("Failed to acquire runtime lock: {}", e);
            return String::new();
        }
    };

    // Parse the address
    let to_addr = match Address::from_str(to_address) {
        Ok(addr) => addr,
        Err(e) => {
            log::error!("Invalid address format: {}", e);
            return String::new();
        }
    };

    // Parse the amount (using string to handle large numbers)
    let amount = match U256::from_dec_str(amount_str) {
        Ok(amt) => amt,
        Err(e) => {
            log::error!("Invalid amount format: {}", e);
            return String::new();
        }
    };

    // Get the proper network name
    let network_name_proper = match ethereum::networks::get_proper_network_name(wallet_network) {
        Some(name) => name,
        None => {
            log::error!("Unknown network: {}", wallet_network);
            return String::new();
        }
    };

    // Get the wallet
    let wallet = match ethereum::get_current_ethereum_wallet_for_network(network_name_proper) {
        Ok(w) => w,
        Err(e) => {
            log::error!("Failed to get wallet: {}", e);
            return String::new();
        }
    };

    // Create a provider
    let provider = match ethereum::create_provider(&wallet.network) {
        Ok(p) => p,
        Err(e) => {
            log::error!("Failed to create provider: {}", e);
            return String::new();
        }
    };

    // Execute the transaction in a blocking manner
    match rt.block_on(async { ethereum::send_eth(&wallet, &provider, to_addr, amount).await }) {
        Ok(tx_hash) => format!("{:?}", tx_hash),
        Err(e) => {
            log::error!("Transaction failed: {}", e);
            String::new()
        }
    }
}

// Smart contract operations

// Load a contract ABI from a JSON string and create a contract instance
fn load_contract_abi(network_name: &str, address: &str, abi_json: &str) -> String {
    // Get the network
    let network = match ethereum::networks::get_network_by_name(network_name) {
        Some(network) => network,
        None => {
            log::error!("Unknown network: {}", network_name);
            return String::new();
        }
    };

    // Parse the ABI
    let abi = match ethereum::load_abi_from_json(abi_json) {
        Ok(abi) => abi,
        Err(e) => {
            log::error!("Error parsing ABI: {}", e);
            return String::new();
        }
    };

    // Create the contract
    match ethereum::Contract::from_address_string(address, abi, network) {
        Ok(contract) => {
            // Serialize the contract to JSON for storage
            match serde_json::to_string(&contract) {
                Ok(json) => json,
                Err(e) => {
                    log::error!("Error serializing contract: {}", e);
                    String::new()
                }
            }
        }
        Err(e) => {
            log::error!("Error creating contract: {}", e);
            String::new()
        }
    }
}

// Load a contract ABI from a file
fn load_contract_abi_from_file(network_name: &str, address: &str, file_path: &str) -> String {
    // Read the ABI file
    match fs::read_to_string(file_path) {
        Ok(abi_json) => load_contract_abi(network_name, address, &abi_json),
        Err(e) => {
            log::error!("Error reading ABI file: {}", e);
            String::new()
        }
    }
}

// Use the utility functions from the ethereum module

// Call a read-only function on a contract (no arguments version)
fn call_contract_read_no_args(contract_json: &str, function_name: &str) -> Dynamic {
    call_contract_read(contract_json, function_name, rhai::Array::new())
}

// Call a read-only function on a contract with arguments
fn call_contract_read(contract_json: &str, function_name: &str, args: rhai::Array) -> Dynamic {
    // Deserialize the contract
    let contract: ethereum::Contract = match serde_json::from_str(contract_json) {
        Ok(contract) => contract,
        Err(e) => {
            log::error!("Error deserializing contract: {}", e);
            return Dynamic::UNIT;
        }
    };

    // Prepare the arguments
    let tokens = match ethereum::prepare_function_arguments(&contract.abi, function_name, &args) {
        Ok(tokens) => tokens,
        Err(e) => {
            log::error!("Error preparing arguments: {}", e);
            return Dynamic::UNIT;
        }
    };

    // Get the runtime
    let rt = match RUNTIME.lock() {
        Ok(rt) => rt,
        Err(e) => {
            log::error!("Failed to acquire runtime lock: {}", e);
            return Dynamic::UNIT;
        }
    };

    // Create a provider
    let provider = match ethereum::create_provider(&contract.network) {
        Ok(p) => p,
        Err(e) => {
            log::error!("Failed to create provider: {}", e);
            return Dynamic::UNIT;
        }
    };

    // Execute the call in a blocking manner
    match rt.block_on(async {
        ethereum::call_read_function(&contract, &provider, function_name, tokens).await
    }) {
        Ok(result) => ethereum::convert_token_to_rhai(&result),
        Err(e) => {
            log::error!("Failed to call contract function: {}", e);
            Dynamic::UNIT
        }
    }
}

// Call a state-changing function on a contract (no arguments version)
fn call_contract_write_no_args(contract_json: &str, function_name: &str) -> String {
    call_contract_write(contract_json, function_name, rhai::Array::new())
}

// Call a state-changing function on a contract with arguments
fn call_contract_write(contract_json: &str, function_name: &str, args: rhai::Array) -> String {
    // Deserialize the contract
    let contract: ethereum::Contract = match serde_json::from_str(contract_json) {
        Ok(contract) => contract,
        Err(e) => {
            log::error!("Error deserializing contract: {}", e);
            return String::new();
        }
    };

    // Prepare the arguments
    let tokens = match ethereum::prepare_function_arguments(&contract.abi, function_name, &args) {
        Ok(tokens) => tokens,
        Err(e) => {
            log::error!("Error preparing arguments: {}", e);
            return String::new();
        }
    };

    // Get the runtime
    let rt = match RUNTIME.lock() {
        Ok(rt) => rt,
        Err(e) => {
            log::error!("Failed to acquire runtime lock: {}", e);
            return String::new();
        }
    };

    // Get the wallet
    let network_name_proper = contract.network.name.as_str();
    let wallet = match ethereum::get_current_ethereum_wallet_for_network(network_name_proper) {
        Ok(w) => w,
        Err(e) => {
            log::error!("Failed to get wallet: {}", e);
            return String::new();
        }
    };

    // Create a provider
    let provider = match ethereum::create_provider(&contract.network) {
        Ok(p) => p,
        Err(e) => {
            log::error!("Failed to create provider: {}", e);
            return String::new();
        }
    };

    // Execute the transaction in a blocking manner
    match rt.block_on(async {
        ethereum::call_write_function(&contract, &wallet, &provider, function_name, tokens).await
    }) {
        Ok(tx_hash) => format!("{:?}", tx_hash),
        Err(e) => {
            // Log the error details for debugging
            log::debug!("\nERROR DETAILS: Transaction failed: {}", e);
            log::debug!("Contract address: {}", contract.address);
            log::debug!("Function: {}", function_name);
            log::debug!("Arguments: {:?}", args);
            log::debug!("Wallet address: {}", wallet.address);
            log::debug!("Network: {}", contract.network.name);
            log::error!("Transaction failed: {}", e);
            String::new()
        }
    }
}

/// Register crypto functions with the Rhai engine
pub fn register_crypto_module(engine: &mut Engine) -> Result<(), Box<EvalAltResult>> {
    // Register key space functions
    engine.register_fn("load_key_space", load_key_space);
    engine.register_fn("create_key_space", create_key_space);
    engine.register_fn("encrypt_key_space", encrypt_key_space);
    engine.register_fn("decrypt_key_space", decrypt_key_space);

    // Register keyspace functions
    engine.register_fn("create_keyspace", create_keyspace);
    engine.register_fn("select_keyspace", select_keyspace);
    engine.register_fn("list_keyspaces", rhai_list_keyspaces_actual);
    engine.register_fn("list_keypairs", rhai_list_keypairs);
    engine.register_fn("count_keyspaces", rhai_count_keyspaces);
    engine.register_fn("count_keypairs", rhai_count_keypairs);
    engine.register_fn("select_keypair", rhai_select_keypair);
    engine.register_fn("clear_session", rhai_clear_session);
    engine.register_fn("create_keypair", rhai_create_keypair);
    engine.register_fn("keypair_pub_key", rhai_keypair_pub_key);

    // Register signing/verification functions
    engine.register_fn("sign", sign);
    engine.register_fn("verify", verify);

    // Register symmetric encryption functions
    engine.register_fn("generate_key", generate_key);
    engine.register_fn("encrypt", encrypt);
    engine.register_fn("decrypt", decrypt);

    // Register Ethereum functions (Gnosis Chain)
    engine.register_fn("create_ethereum_wallet", create_ethereum_wallet);
    engine.register_fn("get_ethereum_address", get_ethereum_address);

    // Register Peaq network functions
    engine.register_fn("create_peaq_wallet", create_peaq_wallet);
    engine.register_fn("get_peaq_address", get_peaq_address);

    // Register Agung testnet functions
    engine.register_fn("create_agung_wallet", create_agung_wallet);
    engine.register_fn("get_agung_address", get_agung_address);

    // Register generic network functions
    engine.register_fn("create_wallet_for_network", create_wallet_for_network);
    engine.register_fn(
        "get_wallet_address_for_network",
        get_wallet_address_for_network,
    );
    engine.register_fn("clear_wallets_for_network", clear_wallets_for_network);
    engine.register_fn("list_supported_networks", list_supported_networks);
    engine.register_fn("get_network_token_symbol", get_network_token_symbol);
    engine.register_fn("get_network_explorer_url", get_network_explorer_url);

    // Register new Ethereum functions for wallet creation from private key and transactions
    engine.register_fn(
        "create_wallet_from_private_key_for_network",
        create_wallet_from_private_key_for_network,
    );
    engine.register_fn("create_agung_provider", create_agung_provider);
    engine.register_fn("send_eth", send_eth);
    engine.register_fn("get_balance", get_balance);

    // Register smart contract functions
    engine.register_fn("load_contract_abi", load_contract_abi);
    engine.register_fn("load_contract_abi_from_file", load_contract_abi_from_file);

    // Register the read function with different arities
    engine.register_fn("call_contract_read", call_contract_read_no_args);
    engine.register_fn("call_contract_read", call_contract_read);

    // Register the write function with different arities
    engine.register_fn("call_contract_write", call_contract_write_no_args);
    engine.register_fn("call_contract_write", call_contract_write);

    Ok(())
}