moonproof-contracts 0.2.2

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
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
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
//! In-memory [`PrivateStateProvider`] — thread-safe `HashMap`-backed
//! implementation. Suitable for:
//!
//! - Unit tests of the submit pipeline (no disk, no encryption
//!   boundary to mock).
//! - Short-lived processes that don't need persistence.
//! - A building block for future disk-backed providers (wrap this and
//!   add a write-through cache / persistence layer).
//!
//! # Scope notes
//!
//! - **Scoping**: TS private-state providers namespace `set` / `get` /
//!   `remove` under a "current contract address" set via
//!   [`PrivateStateProvider::set_contract_address`]. Callers MUST
//!   call `set_contract_address` before the first state CRUD
//!   operation; we error if they don't, rather than silently writing
//!   to a default namespace. `clear` wipes every namespace regardless.
//! - **Signing keys** are keyed by an explicit [`ContractAddress`]
//!   argument — no scoping — so `setContractAddress` doesn't affect
//!   them. Matches the TS interface shape.
//! - **Export / import** are wire-compatible with the TS
//!   `@midnight-ntwrk/midnight-js-level-private-state-provider`
//!   encryption envelope:
//!   `base64( [ version u8 = 2 || salt[32] || iv[12] || tag[16] || ct ] )`
//!   where `ct = AES-256-GCM(PBKDF2-HMAC-SHA256(password, salt, 600k, 32))`.
//!   See [`crate::providers::storage_encryption`] for the envelope
//!   codec; the inner JSON payload is moonproof-native (`states` /
//!   `keys` map opaque hex bytes — TS uses superjson for arbitrary
//!   `PS`, but the runtime stores `Vec<u8>`, so a hex map is the
//!   matching representation).

use moonproof_utils::rt::{SystemTime, UNIX_EPOCH};
use std::collections::HashMap;
use std::sync::Arc;

use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::serialize::{Deserializable, Serializable};
use moonproof_ledger::signatures::SigningKey;
use moonproof_macros::async_trait;
use rand::{CryptoRng, RngCore};
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;

use crate::error::{ContractRuntimeError, Result};
use crate::providers::private_state::{
    ExportPrivateStatesOptions, ExportSigningKeysOptions, ImportConflictStrategy,
    ImportPrivateStatesOptions, ImportPrivateStatesResult, ImportSigningKeysOptions,
    ImportSigningKeysResult, PrivateStateExport, PrivateStateProvider, SigningKeyExport,
    MAX_EXPORT_SIGNING_KEYS, MAX_EXPORT_STATES,
};
use crate::providers::storage_encryption::{
    parse_envelope, Cipher, StorageEncryptionError, SALT_LENGTH,
};
use crate::types::PrivateStateId;

/// Format identifier embedded in [`PrivateStateExport::format`]. Must
/// match the TS literal `'midnight-private-state-export'` exactly so
/// callers can inspect the field on either side.
const PRIVATE_STATE_EXPORT_FORMAT: &str = "midnight-private-state-export";
/// Sibling format identifier for [`SigningKeyExport`].
const SIGNING_KEY_EXPORT_FORMAT: &str = "midnight-signing-key-export";
/// Payload schema version. Bumping this is a breaking change to the
/// inner JSON shape (e.g. switching from hex to base64). The envelope
/// version is independent and lives in
/// [`crate::providers::storage_encryption::ENCRYPTION_VERSION_V2`].
const PAYLOAD_FORMAT_VERSION: u32 = 1;

/// Thread-safe, in-memory [`PrivateStateProvider`]. Cheap to clone
/// (the inner state is reference-counted).
#[derive(Debug, Clone, Default)]
pub struct InMemoryPrivateStateProvider {
    inner: Arc<InnerState>,
}

/// The mutable shared state. One lock per sub-map so readers on one
/// don't block readers on the other.
#[derive(Debug, Default)]
struct InnerState {
    /// Nested: `contract_address` → `private_state_id` → blob. Matches
    /// TS scoping semantics where each contract's private states live
    /// in a separate namespace addressed by [`PrivateStateId`].
    states: RwLock<HashMap<ContractAddress, HashMap<PrivateStateId, Vec<u8>>>>,
    /// The "current" contract address set by the last
    /// `set_contract_address` call. Unscoped CRUD errors until this is
    /// populated.
    current_address: RwLock<Option<ContractAddress>>,
    /// Signing keys per contract address — independent of the
    /// scoping above.
    signing_keys: RwLock<HashMap<ContractAddress, SigningKey>>,
}

impl InMemoryPrivateStateProvider {
    /// Construct an empty provider.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Current scoped contract address, if any. Exposed for tests +
    /// debug — production callers should use
    /// [`PrivateStateProvider::set_contract_address`] to mutate.
    pub async fn current_contract_address(&self) -> Option<ContractAddress> {
        *self.inner.current_address.read().await
    }

    /// Read the unscoped count of stored state blobs across all
    /// namespaces. Used for tests only.
    #[cfg(test)]
    async fn total_state_count(&self) -> usize {
        self.inner
            .states
            .read()
            .await
            .values()
            .map(HashMap::len)
            .sum()
    }

    async fn current_address_or_error(&self) -> Result<ContractAddress> {
        self.inner
            .current_address
            .read()
            .await
            .ok_or_else(|| ContractRuntimeError::Provider {
                provider: "InMemoryPrivateStateProvider",
                message: "set_contract_address must be called before any state CRUD operation"
                    .to_owned(),
            })
    }
}

#[async_trait]
impl PrivateStateProvider for InMemoryPrivateStateProvider {
    async fn set_contract_address(&self, address: &ContractAddress) -> Result<()> {
        *self.inner.current_address.write().await = Some(*address);
        Ok(())
    }

    async fn set(&self, private_state_id: &PrivateStateId, state: Vec<u8>) -> Result<()> {
        let address = self.current_address_or_error().await?;
        let mut states = self.inner.states.write().await;
        states
            .entry(address)
            .or_default()
            .insert(private_state_id.clone(), state);
        Ok(())
    }

    async fn get(&self, private_state_id: &PrivateStateId) -> Result<Option<Vec<u8>>> {
        let address = self.current_address_or_error().await?;
        let states = self.inner.states.read().await;
        Ok(states
            .get(&address)
            .and_then(|ns| ns.get(private_state_id))
            .cloned())
    }

    async fn remove(&self, private_state_id: &PrivateStateId) -> Result<()> {
        let address = self.current_address_or_error().await?;
        let mut states = self.inner.states.write().await;
        if let Some(ns) = states.get_mut(&address) {
            ns.remove(private_state_id);
        }
        Ok(())
    }

    async fn clear(&self) -> Result<()> {
        self.inner.states.write().await.clear();
        Ok(())
    }

    async fn set_signing_key(
        &self,
        address: &ContractAddress,
        signing_key: SigningKey,
    ) -> Result<()> {
        self.inner
            .signing_keys
            .write()
            .await
            .insert(*address, signing_key);
        Ok(())
    }

    async fn get_signing_key(&self, address: &ContractAddress) -> Result<Option<SigningKey>> {
        Ok(self.inner.signing_keys.read().await.get(address).cloned())
    }

    async fn remove_signing_key(&self, address: &ContractAddress) -> Result<()> {
        self.inner.signing_keys.write().await.remove(address);
        Ok(())
    }

    async fn clear_signing_keys(&self) -> Result<()> {
        self.inner.signing_keys.write().await.clear();
        Ok(())
    }

    async fn export_private_states(
        &self,
        options: &ExportPrivateStatesOptions,
    ) -> Result<PrivateStateExport> {
        let password = options
            .password
            .as_deref()
            .ok_or_else(|| missing_password_error("export_private_states"))?;
        let max_states = options.max_states.unwrap_or(MAX_EXPORT_STATES);

        // Snapshot the current scope's private states. Mirrors TS's
        // "filter to the current contract address" step — except in
        // the in-memory provider every namespace is its own
        // HashMap<PSI, blob>, so we just look up the scoped sub-map.
        let address = self.current_address_or_error().await?;
        let states = self.inner.states.read().await;
        let scope = match states.get(&address) {
            Some(ns) if !ns.is_empty() => ns.clone(),
            _ => {
                return Err(ContractRuntimeError::Provider {
                    provider: "InMemoryPrivateStateProvider",
                    message: "no private states to export for the current scope".to_owned(),
                })
            }
        };
        if scope.len() > max_states {
            return Err(ContractRuntimeError::Provider {
                provider: "InMemoryPrivateStateProvider",
                message: format!(
                    "too many states to export ({}); max_states = {}",
                    scope.len(),
                    max_states
                ),
            });
        }

        let payload = build_private_state_payload(&scope);
        let payload_json =
            serde_json::to_string(&payload).map_err(|e| ContractRuntimeError::Provider {
                provider: "InMemoryPrivateStateProvider",
                message: format!("serialize private-state export payload: {e}"),
            })?;

        // Fresh per-export salt (TS does the same).
        let mut rng = rand::thread_rng();
        let cipher = Cipher::derive(&mut rng, password);
        let envelope = cipher.encrypt(&mut rng, &payload_json);

        Ok(PrivateStateExport {
            format: PRIVATE_STATE_EXPORT_FORMAT.to_owned(),
            encrypted_payload: envelope,
            salt: hex::encode(cipher.salt()),
        })
    }

    async fn import_private_states(
        &self,
        export: &PrivateStateExport,
        options: &ImportPrivateStatesOptions,
    ) -> Result<ImportPrivateStatesResult> {
        if export.format != PRIVATE_STATE_EXPORT_FORMAT {
            return Err(invalid_export_format(&export.format));
        }
        let password = options
            .password
            .as_deref()
            .ok_or_else(|| missing_password_error("import_private_states"))?;
        let max_states = options.max_states.unwrap_or(MAX_EXPORT_STATES);
        let conflict_strategy = options.conflict_strategy;

        // Decrypt the envelope. Single generic error to the caller —
        // matches TS's oracle-resistant ExportDecryptionError. The
        // error variant captures *what* failed for our own logging
        // but the message we surface stays generic.
        let payload_json = decrypt_envelope(&export.encrypted_payload, &export.salt, password)?;

        let payload: PrivateStatePayload =
            serde_json::from_str(&payload_json).map_err(|_| decrypt_failed_error())?;
        if payload.version != PAYLOAD_FORMAT_VERSION {
            return Err(invalid_export_format(&format!(
                "unsupported payload version {}",
                payload.version
            )));
        }
        if payload.states.len() != payload.state_count {
            return Err(decrypt_failed_error());
        }
        if payload.states.len() > max_states {
            return Err(invalid_export_format(&format!(
                "too many states ({}); max_states = {}",
                payload.states.len(),
                max_states
            )));
        }

        // Apply the import — we honour the scoped contract address
        // (must already be set by the caller via
        // `set_contract_address`).
        let address = self.current_address_or_error().await?;
        let mut states = self.inner.states.write().await;
        let scope = states.entry(address).or_default();

        // Detect conflicts up-front when the caller asked for the
        // strict strategy.
        if conflict_strategy == ImportConflictStrategy::Error {
            let conflicts = payload
                .states
                .keys()
                .filter(|k| scope.contains_key(&PrivateStateId::new(k.as_str())))
                .count();
            if conflicts > 0 {
                return Err(ContractRuntimeError::Provider {
                    provider: "InMemoryPrivateStateProvider",
                    message: format!(
                        "import would conflict with {conflicts} existing private \
                         state(s); use ImportConflictStrategy::Skip or Overwrite to \
                         proceed",
                    ),
                });
            }
        }

        let mut imported = 0;
        let mut skipped = 0;
        let mut overwritten = 0;
        for (id_str, hex_bytes) in payload.states {
            let bytes = hex::decode(&hex_bytes).map_err(|_| decrypt_failed_error())?;
            let id = PrivateStateId::new(id_str.as_str());
            match (scope.contains_key(&id), conflict_strategy) {
                (true, ImportConflictStrategy::Skip) => {
                    skipped += 1;
                }
                (true, ImportConflictStrategy::Overwrite) => {
                    scope.insert(id, bytes);
                    overwritten += 1;
                }
                (true, ImportConflictStrategy::Error) => {
                    // Already caught above, but keep the branch
                    // exhaustive.
                    return Err(ContractRuntimeError::Provider {
                        provider: "InMemoryPrivateStateProvider",
                        message: format!("conflict on private state id '{id_str}'"),
                    });
                }
                (false, _) => {
                    scope.insert(id, bytes);
                    imported += 1;
                }
            }
        }

        Ok(ImportPrivateStatesResult {
            imported,
            skipped,
            overwritten,
        })
    }

    async fn export_signing_keys(
        &self,
        options: &ExportSigningKeysOptions,
    ) -> Result<SigningKeyExport> {
        let password = options
            .password
            .as_deref()
            .ok_or_else(|| missing_password_error("export_signing_keys"))?;
        let max_keys = options.max_keys.unwrap_or(MAX_EXPORT_SIGNING_KEYS);

        let signing_keys = self.inner.signing_keys.read().await;
        if signing_keys.is_empty() {
            return Err(ContractRuntimeError::Provider {
                provider: "InMemoryPrivateStateProvider",
                message: "no signing keys to export".to_owned(),
            });
        }
        if signing_keys.len() > max_keys {
            return Err(ContractRuntimeError::Provider {
                provider: "InMemoryPrivateStateProvider",
                message: format!(
                    "too many keys to export ({}); max_keys = {}",
                    signing_keys.len(),
                    max_keys
                ),
            });
        }

        let mut keys: HashMap<String, String> = HashMap::with_capacity(signing_keys.len());
        for (addr, sk) in signing_keys.iter() {
            let mut sk_bytes = Vec::new();
            Serializable::serialize(sk, &mut sk_bytes).map_err(|e| {
                ContractRuntimeError::Provider {
                    provider: "InMemoryPrivateStateProvider",
                    message: format!("serialize signing key: {e}"),
                }
            })?;
            keys.insert(hex::encode(addr.0 .0), hex::encode(&sk_bytes));
        }

        let payload = SigningKeyPayload {
            version: PAYLOAD_FORMAT_VERSION,
            exported_at_unix_secs: now_unix_secs(),
            key_count: keys.len(),
            keys,
        };
        let payload_json =
            serde_json::to_string(&payload).map_err(|e| ContractRuntimeError::Provider {
                provider: "InMemoryPrivateStateProvider",
                message: format!("serialize signing-key export payload: {e}"),
            })?;

        let mut rng = rand::thread_rng();
        let cipher = Cipher::derive(&mut rng, password);
        let envelope = cipher.encrypt(&mut rng, &payload_json);

        Ok(SigningKeyExport {
            format: SIGNING_KEY_EXPORT_FORMAT.to_owned(),
            encrypted_payload: envelope,
            salt: hex::encode(cipher.salt()),
        })
    }

    async fn import_signing_keys(
        &self,
        export: &SigningKeyExport,
        options: &ImportSigningKeysOptions,
    ) -> Result<ImportSigningKeysResult> {
        if export.format != SIGNING_KEY_EXPORT_FORMAT {
            return Err(invalid_export_format(&export.format));
        }
        let password = options
            .password
            .as_deref()
            .ok_or_else(|| missing_password_error("import_signing_keys"))?;
        let max_keys = options.max_keys.unwrap_or(MAX_EXPORT_SIGNING_KEYS);
        let conflict_strategy = options.conflict_strategy;

        let payload_json = decrypt_envelope(&export.encrypted_payload, &export.salt, password)?;
        let payload: SigningKeyPayload =
            serde_json::from_str(&payload_json).map_err(|_| decrypt_failed_error())?;
        if payload.version != PAYLOAD_FORMAT_VERSION {
            return Err(invalid_export_format(&format!(
                "unsupported payload version {}",
                payload.version
            )));
        }
        if payload.keys.len() != payload.key_count {
            return Err(decrypt_failed_error());
        }
        if payload.keys.len() > max_keys {
            return Err(invalid_export_format(&format!(
                "too many keys ({}); max_keys = {}",
                payload.keys.len(),
                max_keys
            )));
        }

        let mut signing_keys = self.inner.signing_keys.write().await;

        if conflict_strategy == ImportConflictStrategy::Error {
            let mut conflicts = 0;
            for addr_hex in payload.keys.keys() {
                if let Some(addr) = parse_contract_address(addr_hex) {
                    if signing_keys.contains_key(&addr) {
                        conflicts += 1;
                    }
                }
            }
            if conflicts > 0 {
                return Err(ContractRuntimeError::Provider {
                    provider: "InMemoryPrivateStateProvider",
                    message: format!(
                        "import would conflict with {conflicts} existing signing key(s); \
                         use ImportConflictStrategy::Skip or Overwrite to proceed",
                    ),
                });
            }
        }

        let mut imported = 0;
        let mut skipped = 0;
        let mut overwritten = 0;
        for (addr_hex, sk_hex) in payload.keys {
            let addr = parse_contract_address(&addr_hex).ok_or_else(decrypt_failed_error)?;
            let sk_bytes = hex::decode(&sk_hex).map_err(|_| decrypt_failed_error())?;
            let mut cursor = sk_bytes.as_slice();
            let sk: SigningKey =
                Deserializable::deserialize(&mut cursor, 0).map_err(|_| decrypt_failed_error())?;

            match (signing_keys.contains_key(&addr), conflict_strategy) {
                (true, ImportConflictStrategy::Skip) => {
                    skipped += 1;
                }
                (true, ImportConflictStrategy::Overwrite) => {
                    signing_keys.insert(addr, sk);
                    overwritten += 1;
                }
                (true, ImportConflictStrategy::Error) => {
                    return Err(ContractRuntimeError::Provider {
                        provider: "InMemoryPrivateStateProvider",
                        message: format!("conflict on signing key for address {addr_hex}"),
                    });
                }
                (false, _) => {
                    signing_keys.insert(addr, sk);
                    imported += 1;
                }
            }
        }

        Ok(ImportSigningKeysResult {
            imported,
            skipped,
            overwritten,
        })
    }
}

// =====================================================================
// Internal helpers — payload schema, error mapping, byte plumbing.
// =====================================================================

#[derive(Debug, Serialize, Deserialize)]
struct PrivateStatePayload {
    version: u32,
    /// Unix-seconds timestamp at export time. Stored as a number so
    /// the payload schema is byte-stable across timezones (TS uses
    /// ISO strings; both are equally authentic — the timestamp lives
    /// inside the AEAD-protected ciphertext).
    exported_at_unix_secs: u64,
    state_count: usize,
    /// `private_state_id → hex(bytes)` map. Hex (not base64) keeps
    /// the JSON inspectable in case an operator needs to debug the
    /// envelope without a decryption helper.
    states: HashMap<String, String>,
}

#[derive(Debug, Serialize, Deserialize)]
struct SigningKeyPayload {
    version: u32,
    exported_at_unix_secs: u64,
    key_count: usize,
    /// `contract_address_hex → moonproof_ledger::serialize::Serializable bytes (hex)` map.
    keys: HashMap<String, String>,
}

fn build_private_state_payload(scope: &HashMap<PrivateStateId, Vec<u8>>) -> PrivateStatePayload {
    let mut states: HashMap<String, String> = HashMap::with_capacity(scope.len());
    for (id, bytes) in scope {
        states.insert(id.as_str().to_owned(), hex::encode(bytes));
    }
    PrivateStatePayload {
        version: PAYLOAD_FORMAT_VERSION,
        exported_at_unix_secs: now_unix_secs(),
        state_count: states.len(),
        states,
    }
}

fn now_unix_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs())
}

/// Decrypt an envelope using the salt that was stored alongside it
/// in the [`PrivateStateExport`] / [`SigningKeyExport`] wrapper.
/// Cross-checks that the header salt matches the wrapper salt — if
/// they disagree the wrapper is mis-formed.
fn decrypt_envelope(envelope_b64: &str, salt_hex: &str, password: &str) -> Result<String> {
    let parts = parse_envelope(envelope_b64).map_err(|e| map_storage_err(&e))?;
    let wrapper_salt = parse_salt_hex(salt_hex)?;
    if parts.salt != wrapper_salt {
        // Salt-mismatch is treated as a generic decryption failure
        // for the same oracle-resistance reason as TS.
        return Err(decrypt_failed_error());
    }
    let cipher = Cipher::derive_for_version(password, &parts.salt, parts.version)
        .map_err(|e| map_storage_err(&e))?;
    cipher
        .decrypt(envelope_b64)
        .map_err(|e| map_storage_err(&e))
}

fn parse_salt_hex(salt_hex: &str) -> Result<[u8; SALT_LENGTH]> {
    let bytes = hex::decode(salt_hex).map_err(|_| invalid_export_format("salt is not hex"))?;
    if bytes.len() != SALT_LENGTH {
        return Err(invalid_export_format(&format!(
            "salt length is {} bytes, expected {SALT_LENGTH}",
            bytes.len()
        )));
    }
    let mut out = [0u8; SALT_LENGTH];
    out.copy_from_slice(&bytes);
    Ok(out)
}

fn parse_contract_address(addr_hex: &str) -> Option<ContractAddress> {
    let bytes = hex::decode(addr_hex).ok()?;
    if bytes.len() != 32 {
        return None;
    }
    let mut buf = [0u8; 32];
    buf.copy_from_slice(&bytes);
    Some(ContractAddress(
        moonproof_ledger::base_crypto::hash::HashOutput(buf),
    ))
}

fn map_storage_err(err: &StorageEncryptionError) -> ContractRuntimeError {
    match err {
        StorageEncryptionError::TooShort(_)
        | StorageEncryptionError::UnsupportedVersion(_)
        | StorageEncryptionError::InvalidBase64(_) => invalid_export_format(&err.to_string()),
        StorageEncryptionError::Decrypt => decrypt_failed_error(),
    }
}

fn invalid_export_format(detail: &str) -> ContractRuntimeError {
    ContractRuntimeError::Provider {
        provider: "InMemoryPrivateStateProvider",
        message: format!("invalid export format: {detail}"),
    }
}

fn decrypt_failed_error() -> ContractRuntimeError {
    // Single generic error — matches TS `ExportDecryptionError`.
    // Distinct messages for "wrong password" vs "corrupted ciphertext"
    // would let an attacker mount an oracle attack; collapse into one.
    ContractRuntimeError::Provider {
        provider: "InMemoryPrivateStateProvider",
        message: "decryption failed (wrong password or corrupted export)".to_owned(),
    }
}

fn missing_password_error(method: &'static str) -> ContractRuntimeError {
    ContractRuntimeError::Provider {
        provider: "InMemoryPrivateStateProvider",
        message: format!("{method} requires a password (set options.password)"),
    }
}

#[allow(dead_code)]
fn _suppress_unused_rng_import() {
    // RngCore + CryptoRng are imported for documentation parity with
    // the storage-encryption module's API surface. Used inside
    // closures via rand::thread_rng() returning a CryptoRng-impling
    // ThreadRng; the explicit imports keep the trait surface visible
    // without tripping unused-import lints.
    let _: fn(&mut dyn RngCore) = |_| {};
    let _: fn(&dyn CryptoRng) = |_| {};
}

#[cfg(test)]
mod tests {
    use super::*;
    use moonproof_ledger::base_crypto::hash::HashOutput;

    fn addr(byte: u8) -> ContractAddress {
        ContractAddress(HashOutput([byte; 32]))
    }

    fn signing_key_bytes(byte: u8) -> SigningKey {
        moonproof_ledger::signatures::schnorr_signing_key(&[byte; 32])
            .expect("32 bytes parse into SigningKey")
    }

    #[tokio::test]
    async fn unscoped_crud_errors_until_set_contract_address_is_called() {
        let p = InMemoryPrivateStateProvider::new();
        let id = PrivateStateId::new("ps");
        let err = p.set(&id, vec![1, 2, 3]).await.unwrap_err();
        matches!(err, ContractRuntimeError::Provider { .. });
        assert!(format!("{err}").contains("set_contract_address must be called"));
    }

    #[tokio::test]
    async fn set_then_get_roundtrips_under_the_same_scope() {
        let p = InMemoryPrivateStateProvider::new();
        p.set_contract_address(&addr(0xAA)).await.unwrap();
        let id = PrivateStateId::new("ps");
        p.set(&id, vec![1, 2, 3]).await.unwrap();
        assert_eq!(p.get(&id).await.unwrap(), Some(vec![1, 2, 3]));
    }

    #[tokio::test]
    async fn get_returns_none_for_unknown_id() {
        let p = InMemoryPrivateStateProvider::new();
        p.set_contract_address(&addr(0xAA)).await.unwrap();
        assert_eq!(p.get(&PrivateStateId::new("missing")).await.unwrap(), None);
    }

    #[tokio::test]
    async fn state_is_scoped_by_current_contract_address() {
        let p = InMemoryPrivateStateProvider::new();
        let id = PrivateStateId::new("shared-id");

        p.set_contract_address(&addr(0x01)).await.unwrap();
        p.set(&id, b"for-contract-01".to_vec()).await.unwrap();

        p.set_contract_address(&addr(0x02)).await.unwrap();
        p.set(&id, b"for-contract-02".to_vec()).await.unwrap();
        assert_eq!(p.get(&id).await.unwrap(), Some(b"for-contract-02".to_vec()));

        p.set_contract_address(&addr(0x01)).await.unwrap();
        assert_eq!(p.get(&id).await.unwrap(), Some(b"for-contract-01".to_vec()));

        assert_eq!(p.total_state_count().await, 2);
    }

    #[tokio::test]
    async fn remove_deletes_only_current_scope() {
        let p = InMemoryPrivateStateProvider::new();
        let id = PrivateStateId::new("x");

        p.set_contract_address(&addr(0x01)).await.unwrap();
        p.set(&id, b"one".to_vec()).await.unwrap();
        p.set_contract_address(&addr(0x02)).await.unwrap();
        p.set(&id, b"two".to_vec()).await.unwrap();

        p.remove(&id).await.unwrap(); // Removes from addr(0x02)
        assert_eq!(p.get(&id).await.unwrap(), None);

        p.set_contract_address(&addr(0x01)).await.unwrap();
        assert_eq!(p.get(&id).await.unwrap(), Some(b"one".to_vec()));
    }

    #[tokio::test]
    async fn clear_wipes_all_namespaces() {
        let p = InMemoryPrivateStateProvider::new();
        let id = PrivateStateId::new("x");

        p.set_contract_address(&addr(0x01)).await.unwrap();
        p.set(&id, b"one".to_vec()).await.unwrap();
        p.set_contract_address(&addr(0x02)).await.unwrap();
        p.set(&id, b"two".to_vec()).await.unwrap();

        p.clear().await.unwrap();
        assert_eq!(p.total_state_count().await, 0);
        assert_eq!(p.get(&id).await.unwrap(), None);
    }

    #[tokio::test]
    async fn signing_key_crud_independent_of_scoping() {
        use moonproof_ledger::serialize::Serializable;

        let p = InMemoryPrivateStateProvider::new();
        let a = addr(0xAA);
        let b = addr(0xBB);
        let sk_a = signing_key_bytes(0x11);
        let sk_b = signing_key_bytes(0x22);

        // No set_contract_address call — signing keys use their own
        // namespace.
        p.set_signing_key(&a, sk_a.clone()).await.unwrap();
        p.set_signing_key(&b, sk_b.clone()).await.unwrap();

        let got_a = p.get_signing_key(&a).await.unwrap().unwrap();
        let got_b = p.get_signing_key(&b).await.unwrap().unwrap();
        // SigningKey has no PartialEq; compare via serialized form.
        let mut bytes_a = Vec::new();
        let mut bytes_b = Vec::new();
        let mut bytes_got_a = Vec::new();
        let mut bytes_got_b = Vec::new();
        Serializable::serialize(&sk_a, &mut bytes_a).unwrap();
        Serializable::serialize(&sk_b, &mut bytes_b).unwrap();
        Serializable::serialize(&got_a, &mut bytes_got_a).unwrap();
        Serializable::serialize(&got_b, &mut bytes_got_b).unwrap();
        assert_eq!(bytes_a, bytes_got_a);
        assert_eq!(bytes_b, bytes_got_b);
    }

    #[tokio::test]
    async fn get_signing_key_returns_none_for_unknown_address() {
        let p = InMemoryPrivateStateProvider::new();
        assert!(p.get_signing_key(&addr(0xFF)).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn remove_and_clear_signing_keys() {
        let p = InMemoryPrivateStateProvider::new();
        let a = addr(0xAA);
        let b = addr(0xBB);
        p.set_signing_key(&a, signing_key_bytes(0x11))
            .await
            .unwrap();
        p.set_signing_key(&b, signing_key_bytes(0x22))
            .await
            .unwrap();

        p.remove_signing_key(&a).await.unwrap();
        assert!(p.get_signing_key(&a).await.unwrap().is_none());
        assert!(p.get_signing_key(&b).await.unwrap().is_some());

        p.clear_signing_keys().await.unwrap();
        assert!(p.get_signing_key(&b).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn current_contract_address_accessor_reflects_last_set() {
        let p = InMemoryPrivateStateProvider::new();
        assert!(p.current_contract_address().await.is_none());
        p.set_contract_address(&addr(0x77)).await.unwrap();
        assert_eq!(p.current_contract_address().await, Some(addr(0x77)));
    }

    #[tokio::test]
    async fn clone_shares_the_underlying_state() {
        let p1 = InMemoryPrivateStateProvider::new();
        p1.set_contract_address(&addr(0x11)).await.unwrap();

        let p2 = p1.clone();
        p2.set(&PrivateStateId::new("x"), b"hello".to_vec())
            .await
            .unwrap();

        // p1 sees p2's write through the shared Arc<InnerState>.
        assert_eq!(
            p1.get(&PrivateStateId::new("x")).await.unwrap(),
            Some(b"hello".to_vec())
        );
    }

    // -----------------------------------------------------------------
    // Export / import round-trip tests — exercise the AES-256-GCM
    // envelope + JSON payload codec end-to-end.
    // -----------------------------------------------------------------

    const TEST_PASSWORD: &str = "TheQuickBrownFox-12345!";
    const OTHER_PASSWORD: &str = "DifferentPassword-67890?";

    fn export_opts() -> ExportPrivateStatesOptions {
        ExportPrivateStatesOptions {
            password: Some(TEST_PASSWORD.into()),
            max_states: None,
        }
    }

    fn import_opts(strategy: ImportConflictStrategy) -> ImportPrivateStatesOptions {
        ImportPrivateStatesOptions {
            password: Some(TEST_PASSWORD.into()),
            conflict_strategy: strategy,
            max_states: None,
        }
    }

    fn signing_key_export_opts() -> ExportSigningKeysOptions {
        ExportSigningKeysOptions {
            password: Some(TEST_PASSWORD.into()),
            max_keys: None,
        }
    }

    fn signing_key_import_opts(strategy: ImportConflictStrategy) -> ImportSigningKeysOptions {
        ImportSigningKeysOptions {
            password: Some(TEST_PASSWORD.into()),
            conflict_strategy: strategy,
            max_keys: None,
        }
    }

    /// ports: `storage-encryption.test.ts::should encrypt and decrypt round-trip`
    #[tokio::test]
    async fn export_then_import_private_states_round_trips() {
        let p = InMemoryPrivateStateProvider::new();
        p.set_contract_address(&addr(0xAA)).await.unwrap();
        p.set(&PrivateStateId::new("ps-a"), b"hello".to_vec())
            .await
            .unwrap();
        p.set(&PrivateStateId::new("ps-b"), b"world".to_vec())
            .await
            .unwrap();

        let export = p.export_private_states(&export_opts()).await.unwrap();
        assert_eq!(export.format, "midnight-private-state-export");
        assert_eq!(export.salt.len(), 64); // 32 bytes hex

        let target = InMemoryPrivateStateProvider::new();
        target.set_contract_address(&addr(0xAA)).await.unwrap();
        let result = target
            .import_private_states(&export, &import_opts(ImportConflictStrategy::Error))
            .await
            .unwrap();
        assert_eq!(result.imported, 2);
        assert_eq!(result.skipped, 0);
        assert_eq!(result.overwritten, 0);
        assert_eq!(
            target.get(&PrivateStateId::new("ps-a")).await.unwrap(),
            Some(b"hello".to_vec())
        );
        assert_eq!(
            target.get(&PrivateStateId::new("ps-b")).await.unwrap(),
            Some(b"world".to_vec())
        );
    }

    /// ports: `storage-encryption.test.ts::should fail to decrypt with wrong password`
    #[tokio::test]
    async fn import_with_wrong_password_returns_decrypt_error() {
        let p = InMemoryPrivateStateProvider::new();
        p.set_contract_address(&addr(0xAA)).await.unwrap();
        p.set(&PrivateStateId::new("ps-a"), b"hello".to_vec())
            .await
            .unwrap();
        let export = p.export_private_states(&export_opts()).await.unwrap();

        let target = InMemoryPrivateStateProvider::new();
        target.set_contract_address(&addr(0xAA)).await.unwrap();
        let bad_opts = ImportPrivateStatesOptions {
            password: Some(OTHER_PASSWORD.into()),
            conflict_strategy: ImportConflictStrategy::Error,
            max_states: None,
        };
        let err = target
            .import_private_states(&export, &bad_opts)
            .await
            .unwrap_err();
        // Single generic error matching TS's ExportDecryptionError —
        // distinguishing wrong-password from corrupted-ciphertext
        // would let an attacker mount an oracle attack.
        let msg = format!("{err}");
        assert!(msg.contains("decryption failed"), "{msg}");
    }

    /// ports: `storage-encryption.test.ts::should fail to decrypt malformed/truncated data`
    #[tokio::test]
    async fn import_with_truncated_envelope_returns_invalid_format() {
        let p = InMemoryPrivateStateProvider::new();
        p.set_contract_address(&addr(0xAA)).await.unwrap();
        p.set(&PrivateStateId::new("ps-a"), b"hello".to_vec())
            .await
            .unwrap();
        let mut export = p.export_private_states(&export_opts()).await.unwrap();
        // Lop off the last 30 base64 chars — still parses as base64,
        // but breaks the AES-GCM tag.
        export
            .encrypted_payload
            .truncate(export.encrypted_payload.len() - 30);

        let target = InMemoryPrivateStateProvider::new();
        target.set_contract_address(&addr(0xAA)).await.unwrap();
        let err = target
            .import_private_states(&export, &import_opts(ImportConflictStrategy::Error))
            .await
            .unwrap_err();
        let msg = format!("{err}");
        // Either the envelope parser rejects (too short) OR the
        // AES-GCM tag check fails — both are equally valid for the
        // truncation case. Just assert it's a refusal, not a silent
        // partial decrypt.
        assert!(
            msg.contains("decryption failed") || msg.contains("invalid export format"),
            "{msg}"
        );
    }

    /// Distinct exports of the same data must produce distinct
    /// envelopes (per-export salt + IV). Round-trip the SAME export
    /// twice and assert the encrypted payloads aren't equal.
    #[tokio::test]
    async fn re_exporting_same_data_produces_fresh_salt_and_iv() {
        let p = InMemoryPrivateStateProvider::new();
        p.set_contract_address(&addr(0xAA)).await.unwrap();
        p.set(&PrivateStateId::new("ps-a"), b"hello".to_vec())
            .await
            .unwrap();

        let e1 = p.export_private_states(&export_opts()).await.unwrap();
        let e2 = p.export_private_states(&export_opts()).await.unwrap();

        assert_ne!(e1.salt, e2.salt);
        assert_ne!(e1.encrypted_payload, e2.encrypted_payload);
    }

    /// Conflict-strategy = Error rejects when an existing id collides.
    #[tokio::test]
    async fn import_conflict_error_rejects_when_id_already_present() {
        let p = InMemoryPrivateStateProvider::new();
        p.set_contract_address(&addr(0xAA)).await.unwrap();
        p.set(&PrivateStateId::new("ps-a"), b"original".to_vec())
            .await
            .unwrap();

        let export = p.export_private_states(&export_opts()).await.unwrap();

        // Import back into the SAME provider — id "ps-a" already
        // present.
        let err = p
            .import_private_states(&export, &import_opts(ImportConflictStrategy::Error))
            .await
            .unwrap_err();
        assert!(format!("{err}").contains("conflict"));
    }

    /// Conflict-strategy = Skip preserves the existing entry.
    #[tokio::test]
    async fn import_conflict_skip_preserves_existing_entry() {
        let p = InMemoryPrivateStateProvider::new();
        p.set_contract_address(&addr(0xAA)).await.unwrap();
        p.set(&PrivateStateId::new("ps-a"), b"original".to_vec())
            .await
            .unwrap();
        p.set(&PrivateStateId::new("ps-b"), b"original-b".to_vec())
            .await
            .unwrap();
        let export = p.export_private_states(&export_opts()).await.unwrap();

        // Pre-populate target with a colliding "ps-a" but no "ps-b".
        let target = InMemoryPrivateStateProvider::new();
        target.set_contract_address(&addr(0xAA)).await.unwrap();
        target
            .set(&PrivateStateId::new("ps-a"), b"already-here".to_vec())
            .await
            .unwrap();

        let result = target
            .import_private_states(&export, &import_opts(ImportConflictStrategy::Skip))
            .await
            .unwrap();
        assert_eq!(result.skipped, 1);
        assert_eq!(result.imported, 1);
        assert_eq!(
            target.get(&PrivateStateId::new("ps-a")).await.unwrap(),
            Some(b"already-here".to_vec()),
            "existing entry must survive Skip strategy"
        );
        assert_eq!(
            target.get(&PrivateStateId::new("ps-b")).await.unwrap(),
            Some(b"original-b".to_vec())
        );
    }

    /// Conflict-strategy = Overwrite replaces the existing entry.
    #[tokio::test]
    async fn import_conflict_overwrite_replaces_existing_entry() {
        let p = InMemoryPrivateStateProvider::new();
        p.set_contract_address(&addr(0xAA)).await.unwrap();
        p.set(&PrivateStateId::new("ps-a"), b"new-value".to_vec())
            .await
            .unwrap();
        let export = p.export_private_states(&export_opts()).await.unwrap();

        let target = InMemoryPrivateStateProvider::new();
        target.set_contract_address(&addr(0xAA)).await.unwrap();
        target
            .set(&PrivateStateId::new("ps-a"), b"original".to_vec())
            .await
            .unwrap();

        let result = target
            .import_private_states(&export, &import_opts(ImportConflictStrategy::Overwrite))
            .await
            .unwrap();
        assert_eq!(result.overwritten, 1);
        assert_eq!(result.imported, 0);
        assert_eq!(
            target.get(&PrivateStateId::new("ps-a")).await.unwrap(),
            Some(b"new-value".to_vec()),
        );
    }

    /// Format-string check rejects exports tagged with a different
    /// format (e.g. a `SigningKeyExport` shape sent into
    /// `import_private_states`).
    #[tokio::test]
    async fn import_rejects_mismatched_format_field() {
        let p = InMemoryPrivateStateProvider::new();
        p.set_contract_address(&addr(0xAA)).await.unwrap();
        p.set(&PrivateStateId::new("ps-a"), b"hello".to_vec())
            .await
            .unwrap();
        let mut export = p.export_private_states(&export_opts()).await.unwrap();
        export.format = "bogus-format".into();

        let target = InMemoryPrivateStateProvider::new();
        target.set_contract_address(&addr(0xAA)).await.unwrap();
        let err = target
            .import_private_states(&export, &import_opts(ImportConflictStrategy::Error))
            .await
            .unwrap_err();
        assert!(format!("{err}").contains("invalid export format"));
    }

    /// Empty-state export errors so callers don't ship empty bundles.
    #[tokio::test]
    async fn export_empty_scope_errors() {
        let p = InMemoryPrivateStateProvider::new();
        p.set_contract_address(&addr(0xAA)).await.unwrap();
        let err = p.export_private_states(&export_opts()).await.unwrap_err();
        assert!(format!("{err}").contains("no private states to export"));
    }

    /// Round-trip the signing-key export — same envelope, distinct
    /// payload format.
    #[tokio::test]
    async fn export_then_import_signing_keys_round_trips() {
        let p = InMemoryPrivateStateProvider::new();
        let a = addr(0xAA);
        let b = addr(0xBB);
        let sk_a = signing_key_bytes(0x11);
        let sk_b = signing_key_bytes(0x22);
        p.set_signing_key(&a, sk_a.clone()).await.unwrap();
        p.set_signing_key(&b, sk_b.clone()).await.unwrap();

        let export = p
            .export_signing_keys(&signing_key_export_opts())
            .await
            .unwrap();
        assert_eq!(export.format, "midnight-signing-key-export");

        let target = InMemoryPrivateStateProvider::new();
        let result = target
            .import_signing_keys(
                &export,
                &signing_key_import_opts(ImportConflictStrategy::Error),
            )
            .await
            .unwrap();
        assert_eq!(result.imported, 2);

        let got_a = target.get_signing_key(&a).await.unwrap().unwrap();
        let got_b = target.get_signing_key(&b).await.unwrap().unwrap();
        let mut bytes_orig_a = Vec::new();
        let mut bytes_orig_b = Vec::new();
        let mut bytes_back_a = Vec::new();
        let mut bytes_back_b = Vec::new();
        Serializable::serialize(&sk_a, &mut bytes_orig_a).unwrap();
        Serializable::serialize(&sk_b, &mut bytes_orig_b).unwrap();
        Serializable::serialize(&got_a, &mut bytes_back_a).unwrap();
        Serializable::serialize(&got_b, &mut bytes_back_b).unwrap();
        assert_eq!(bytes_orig_a, bytes_back_a);
        assert_eq!(bytes_orig_b, bytes_back_b);
    }

    /// Wrong password on signing-key import must produce a generic
    /// decrypt error.
    #[tokio::test]
    async fn signing_key_import_with_wrong_password_returns_decrypt_error() {
        let p = InMemoryPrivateStateProvider::new();
        p.set_signing_key(&addr(0xAA), signing_key_bytes(0x11))
            .await
            .unwrap();
        let export = p
            .export_signing_keys(&signing_key_export_opts())
            .await
            .unwrap();

        let target = InMemoryPrivateStateProvider::new();
        let err = target
            .import_signing_keys(
                &export,
                &ImportSigningKeysOptions {
                    password: Some(OTHER_PASSWORD.into()),
                    conflict_strategy: ImportConflictStrategy::Error,
                    max_keys: None,
                },
            )
            .await
            .unwrap_err();
        assert!(format!("{err}").contains("decryption failed"));
    }

    /// Missing password on either side must error before doing
    /// crypto. Validates the precondition surface.
    #[tokio::test]
    async fn export_without_password_errors() {
        let p = InMemoryPrivateStateProvider::new();
        p.set_contract_address(&addr(0xAA)).await.unwrap();
        p.set(&PrivateStateId::new("ps-a"), b"hello".to_vec())
            .await
            .unwrap();
        let err = p
            .export_private_states(&ExportPrivateStatesOptions::default())
            .await
            .unwrap_err();
        assert!(format!("{err}").contains("requires a password"));
    }
}