tsp_sdk 0.13.0

Rust implementation of the Trust Spanning Protocol
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
//! Test utilities and helpers for writing tests.

use crate::{
    OwnedVid, RelationshipStatus, SecureStore,
    definitions::{Digest, PendingNestedRelationship, VerifiedVid},
    store::WalletState,
};
#[cfg(feature = "resolve")]
use crate::{
    ResolutionContext,
    vid::did::scid::{ScidLocator, ScidMethod, ScidResolutionContext, ScidSourceMethod},
};
use once_cell::sync::Lazy;
use std::{
    collections::BTreeMap,
    path::{Path, PathBuf},
};

#[cfg(feature = "async")]
use crate::{AskarSecureStorage, AsyncSecureStore, SecureStorage};

#[cfg(any(test, feature = "test-utils"))]
use tempfile::TempDir;

const MIN_TEST_PORT: u16 = 50_000;
const MAX_TEST_PORT: u16 = 59_999;
const TEST_PORT_SPAN: u32 = (MAX_TEST_PORT - MIN_TEST_PORT + 1) as u32;
static CAN_PROBE_TEST_PORTS: Lazy<bool> =
    Lazy::new(|| std::net::TcpListener::bind(("127.0.0.1", 0)).is_ok());

/// Port allocator to avoid conflicts in concurrent tests.
///
/// The allocator cycles over a dedicated test port range instead of
/// monotonically increasing without bounds.
pub struct TestPortAllocator;

static GLOBAL_PORT_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);

impl TestPortAllocator {
    /// Create a new port allocator.
    pub fn new() -> Self {
        Self
    }

    /// Allocate a test port from the configured test port range.
    pub fn allocate(&self) -> u16 {
        let start =
            GLOBAL_PORT_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % TEST_PORT_SPAN;

        // Probe for an available port when the runtime environment allows socket binding.
        // In restricted environments (e.g. sandboxed CI), fall back to deterministic cycling.
        if *CAN_PROBE_TEST_PORTS {
            for i in 0..TEST_PORT_SPAN {
                let offset = (start + i) % TEST_PORT_SPAN;
                let port = MIN_TEST_PORT + offset as u16;
                if std::net::TcpListener::bind(("127.0.0.1", port)).is_ok() {
                    return port;
                }
            }

            panic!("No available test ports in range {MIN_TEST_PORT}-{MAX_TEST_PORT}");
        }

        MIN_TEST_PORT + start as u16
    }

    /// Create a TCP endpoint URL with an allocated port.
    pub fn tcp_endpoint(&self) -> String {
        format!("tcp://127.0.0.1:{}", self.allocate())
    }
}

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

/// Create a test VID with a unique localhost TCP endpoint.
pub fn create_test_vid() -> OwnedVid {
    let allocator = TestPortAllocator::new();
    OwnedVid::new_did_peer(url::Url::parse(&allocator.tcp_endpoint()).unwrap())
}

/// Create a pair of test VIDs (alice, bob).
pub fn create_test_vid_pair() -> (OwnedVid, OwnedVid) {
    (create_test_vid(), create_test_vid())
}

/// Load a test VID from a file.
#[cfg(feature = "async")]
pub async fn create_vid_from_file(path: &str) -> OwnedVid {
    OwnedVid::from_file(path)
        .await
        .unwrap_or_else(|e| panic!("Failed to load VID from {path}: {e}"))
}

/// Create a test SecureStore.
pub fn create_test_store() -> SecureStore {
    SecureStore::new()
}

/// Create a test did:scid resolution context for WebVH-backed identities.
#[cfg(feature = "resolve")]
pub fn create_test_scid_context(presented_did: &str) -> ResolutionContext {
    let scid = crate::vid::did::scid::parse(presented_did)
        .expect("presented did:scid should parse")
        .scid;

    ResolutionContext::Scid(ScidResolutionContext {
        version: 1,
        method: ScidMethod::Vh,
        source_method: ScidSourceMethod::Webvh,
        locator: ScidLocator::Src(format!("did:webvh:{scid}:example.com:test")),
    })
}

/// Create a test AsyncSecureStore.
#[cfg(feature = "async")]
pub fn create_async_test_store() -> AsyncSecureStore {
    AsyncSecureStore::new()
}

fn relationship_digest(seed: usize) -> Digest {
    let mut digest = [0_u8; 32];
    digest[..8].copy_from_slice(&(seed as u64).to_le_bytes());
    digest[8..16].copy_from_slice((!(seed as u64)).to_le_bytes().as_ref());
    digest[16..24].copy_from_slice(((seed as u64).wrapping_mul(31)).to_le_bytes().as_ref());
    digest[24..32].copy_from_slice(((seed as u64).wrapping_mul(131)).to_le_bytes().as_ref());
    digest
}

fn relationship_status_for(index: usize) -> RelationshipStatus {
    match index % 4 {
        0 => RelationshipStatus::Unrelated,
        1 => RelationshipStatus::Unidirectional {
            thread_id: relationship_digest(index),
        },
        2 => RelationshipStatus::ReverseUnidirectional {
            thread_id: relationship_digest(index),
        },
        _ => RelationshipStatus::Bidirectional {
            thread_id: relationship_digest(index),
            remote_thread_id: relationship_digest(index + 1_000),
            outstanding_nested_requests: vec![PendingNestedRelationship {
                thread_id: relationship_digest(index + 10_000),
                local_nested_vid: format!("did:example:nested:{index}"),
            }],
        },
    }
}

impl RelationshipStatus {
    /// A bidirectional relationship for tests. The two thread ids are distinct
    /// and non-zero: the all-zero digest is the NULL digest of a `TSP_RFD`
    /// (spec 7.3), not a thread id any relationship would hold.
    fn bi_test(thread_id: u8, remote_thread_id: u8) -> Self {
        Self::Bidirectional {
            thread_id: [thread_id; 32],
            remote_thread_id: [remote_thread_id; 32],
            outstanding_nested_requests: vec![],
        }
    }
}

/// Create a store with `n` relationships in mixed states.
pub fn create_store_with_relationships(n: usize) -> SecureStore {
    let store = create_test_store();
    let local_vid = create_test_vid();

    store.add_private_vid(local_vid.clone(), None).unwrap();
    store
        .set_alias(
            "local-owner".to_string(),
            local_vid.identifier().to_string(),
        )
        .unwrap();

    for i in 0..n {
        let remote_vid = create_test_vid();
        store.add_verified_vid(remote_vid.clone(), None).unwrap();
        store
            .set_relation_and_status_for_vid(
                remote_vid.identifier(),
                relationship_status_for(i),
                local_vid.identifier(),
            )
            .unwrap();
    }

    store
}

/// Create a store that mimics a dirty wallet with existing identities,
/// nested relationships, aliases, and key history.
pub fn create_prepopulated_store() -> SecureStore {
    let store = create_store_with_relationships(8);

    let root_local = store.resolve_alias("local-owner").unwrap().unwrap();

    let nested_local = create_test_vid();
    store.add_private_vid(nested_local.clone(), None).unwrap();
    store
        .set_parent_for_vid(nested_local.identifier(), Some(&root_local))
        .unwrap();

    let remote_parent = create_test_vid();
    store.add_verified_vid(remote_parent.clone(), None).unwrap();
    store
        .set_relation_and_status_for_vid(
            remote_parent.identifier(),
            RelationshipStatus::Bidirectional {
                thread_id: relationship_digest(20_001),
                remote_thread_id: relationship_digest(20_011),
                outstanding_nested_requests: vec![PendingNestedRelationship {
                    thread_id: relationship_digest(20_002),
                    local_nested_vid: "did:example:nested:20_002".to_string(),
                }],
            },
            &root_local,
        )
        .unwrap();

    let remote_nested = create_test_vid();
    store.add_verified_vid(remote_nested.clone(), None).unwrap();
    store
        .set_parent_for_vid(remote_nested.identifier(), Some(remote_parent.identifier()))
        .unwrap();
    store
        .set_relation_and_status_for_vid(
            remote_nested.identifier(),
            RelationshipStatus::Bidirectional {
                thread_id: relationship_digest(20_101),
                remote_thread_id: relationship_digest(20_111),
                outstanding_nested_requests: vec![PendingNestedRelationship {
                    thread_id: relationship_digest(20_102),
                    local_nested_vid: "did:example:nested:20_102".to_string(),
                }],
            },
            nested_local.identifier(),
        )
        .unwrap();

    // Keep some persisted key history around as part of the fixture state.
    store
        .import_key(
            "test-history-key-1",
            crate::KeyType::Ed25519,
            zeroize::Zeroizing::new(vec![1, 2, 3, 4]),
        )
        .unwrap();
    store
        .import_key(
            "test-history-key-2",
            crate::KeyType::Ed25519,
            zeroize::Zeroizing::new(vec![5, 6, 7, 8]),
        )
        .unwrap();

    store
}

/// Snapshot shape used to compare wallet exports across reopen cycles.
pub type StoreExportSnapshot = (
    BTreeMap<String, String>,
    Vec<String>,
    BTreeMap<String, String>,
);

/// Return a stable string form for a relationship status.
pub fn relationship_status_signature(status: RelationshipStatus) -> String {
    match status {
        RelationshipStatus::Unrelated => "Unrelated".to_string(),
        RelationshipStatus::Unidirectional { thread_id } => format!("Uni:{thread_id:?}"),
        RelationshipStatus::ReverseUnidirectional { thread_id } => format!("RevUni:{thread_id:?}"),
        RelationshipStatus::Bidirectional {
            thread_id,
            remote_thread_id,
            outstanding_nested_requests,
        } => format!("Bi:{thread_id:?}:{remote_thread_id:?}:{outstanding_nested_requests:?}"),
    }
}

fn export_snapshot_parts(state: WalletState) -> StoreExportSnapshot {
    let WalletState {
        vids,
        aliases,
        method_state,
        keys,
    } = state;
    let mut vid_rows = vids
        .into_iter()
        .map(|exported| {
            let tunnel = exported
                .tunnel
                .as_ref()
                .map(|route| route.join(">"))
                .unwrap_or_default();
            format!(
                "{}|{}|{}|{}|{}|{}",
                exported.id,
                exported.is_private(),
                exported.relation_vid.unwrap_or_default(),
                exported.parent_vid.unwrap_or_default(),
                tunnel,
                relationship_status_signature(exported.relation_status)
            )
        })
        .collect::<Vec<_>>();
    vid_rows.sort();

    let mut key_rows = keys
        .aliases()
        .into_iter()
        .map(|alias| {
            let public = crate::SecureArea::public_key(keys.as_ref(), &alias).ok();
            (alias, format!("{public:?}"))
        })
        .collect::<BTreeMap<_, _>>();
    key_rows.extend(
        method_state
            .resolution_contexts
            .into_iter()
            .map(|(k, v)| (format!("resolution_context:{k}"), format!("{v:?}"))),
    );

    (
        aliases.into_iter().collect::<BTreeMap<_, _>>(),
        vid_rows,
        key_rows,
    )
}

/// Export a synchronous store into a normalized snapshot.
pub fn export_snapshot_sync(store: &SecureStore) -> StoreExportSnapshot {
    let state = store.export().unwrap();
    export_snapshot_parts(state)
}

/// Seed data for relationship transition tests on dirty wallets.
#[cfg(feature = "async")]
pub struct DirtyTransitionSeed {
    pub local_vid: String,
    pub remote_unrelated_vid: String,
    pub remote_bidirectional_vid: String,
}

/// Create an async store pre-seeded for relationship transition tests.
#[cfg(feature = "async")]
pub fn create_dirty_store_with_transition_seed() -> (AsyncSecureStore, DirtyTransitionSeed) {
    let store = create_async_test_store();

    let local = create_test_vid();
    let remote_unrelated = create_test_vid();
    let remote_bidirectional = create_test_vid();

    store.add_private_vid(local.clone(), None).unwrap();
    store
        .add_verified_vid(remote_unrelated.clone(), None)
        .unwrap();
    store
        .add_verified_vid(remote_bidirectional.clone(), None)
        .unwrap();

    store
        .set_alias("local-owner".to_string(), local.identifier().to_string())
        .unwrap();
    store
        .set_relation_and_status_for_vid(
            remote_unrelated.identifier(),
            RelationshipStatus::Unrelated,
            local.identifier(),
        )
        .unwrap();
    store
        .set_relation_and_status_for_vid(
            remote_bidirectional.identifier(),
            RelationshipStatus::Bidirectional {
                thread_id: relationship_digest(30_001),
                remote_thread_id: relationship_digest(30_011),
                outstanding_nested_requests: vec![PendingNestedRelationship {
                    thread_id: relationship_digest(30_002),
                    local_nested_vid: "did:example:nested:30_002".to_string(),
                }],
            },
            local.identifier(),
        )
        .unwrap();
    store
        .import_key(
            "transition-seed-key",
            crate::KeyType::Ed25519,
            zeroize::Zeroizing::new(vec![9, 8, 7, 6]),
        )
        .unwrap();

    (
        store,
        DirtyTransitionSeed {
            local_vid: local.identifier().to_string(),
            remote_unrelated_vid: remote_unrelated.identifier().to_string(),
            remote_bidirectional_vid: remote_bidirectional.identifier().to_string(),
        },
    )
}

/// Seed data for high-entropy dirty wallet tests.
#[cfg(feature = "async")]
pub struct HighEntropyDirtySeed {
    pub local_vid: String,
    pub bidirectional_remote_vid: String,
    pub routed_remote_vid: String,
}

/// Create a large dirty wallet with mixed relations, nested VIDs, aliases,
/// custom keys, and routed entries.
#[cfg(feature = "async")]
pub fn create_high_entropy_dirty_store() -> (AsyncSecureStore, HighEntropyDirtySeed) {
    let store = create_async_test_store();
    let local_vid = create_test_vid();
    store.add_private_vid(local_vid.clone(), None).unwrap();
    store
        .set_alias(
            "local-owner".to_string(),
            local_vid.identifier().to_string(),
        )
        .unwrap();
    store
        .set_alias(
            "high-entropy-root".to_string(),
            local_vid.identifier().to_string(),
        )
        .unwrap();

    let route_hop_a = create_test_vid();
    let route_hop_b = create_test_vid();
    for hop in [&route_hop_a, &route_hop_b] {
        store.add_verified_vid(hop.clone(), None).unwrap();
        store
            .set_relation_and_status_for_vid(
                hop.identifier(),
                RelationshipStatus::bi_test(0x11, 0x22),
                local_vid.identifier(),
            )
            .unwrap();
    }

    for i in 0..16 {
        store
            .import_key(
                &format!("high-entropy-key-{i:02}"),
                crate::KeyType::Ed25519,
                zeroize::Zeroizing::new(vec![i as u8, i as u8 ^ 0x5A, i as u8 ^ 0xA5, 0xFF]),
            )
            .unwrap();
    }

    let mut bidirectional_remote_vid = None;
    let mut routed_remote_vid = None;

    for i in 0..64 {
        let remote_vid = create_test_vid();
        store.add_verified_vid(remote_vid.clone(), None).unwrap();
        let relationship = relationship_status_for(i + 100);
        if bidirectional_remote_vid.is_none()
            && matches!(relationship, RelationshipStatus::Bidirectional { .. })
        {
            bidirectional_remote_vid = Some(remote_vid.identifier().to_string());
        }
        store
            .set_relation_and_status_for_vid(
                remote_vid.identifier(),
                relationship,
                local_vid.identifier(),
            )
            .unwrap();

        if i % 8 == 0 {
            store
                .set_route_for_vid(
                    remote_vid.identifier(),
                    &[route_hop_a.identifier(), route_hop_b.identifier()],
                )
                .unwrap();
            if routed_remote_vid.is_none() {
                routed_remote_vid = Some(remote_vid.identifier().to_string());
            }
        }
    }

    for i in 0..4 {
        let nested_local = create_test_vid();
        store.add_private_vid(nested_local.clone(), None).unwrap();
        store
            .set_parent_for_vid(nested_local.identifier(), Some(local_vid.identifier()))
            .unwrap();
        store
            .set_alias(
                format!("nested-local-{i}"),
                nested_local.identifier().to_string(),
            )
            .unwrap();

        let remote_parent = create_test_vid();
        let remote_nested = create_test_vid();
        store.add_verified_vid(remote_parent.clone(), None).unwrap();
        store.add_verified_vid(remote_nested.clone(), None).unwrap();

        store
            .set_relation_and_status_for_vid(
                remote_parent.identifier(),
                RelationshipStatus::Bidirectional {
                    thread_id: relationship_digest(40_000 + i),
                    remote_thread_id: relationship_digest(40_100 + i),
                    outstanding_nested_requests: vec![PendingNestedRelationship {
                        thread_id: relationship_digest(41_000 + i),
                        local_nested_vid: format!("did:example:nested:41_{i:03}"),
                    }],
                },
                local_vid.identifier(),
            )
            .unwrap();
        store
            .set_parent_for_vid(remote_nested.identifier(), Some(remote_parent.identifier()))
            .unwrap();
        store
            .set_relation_and_status_for_vid(
                remote_nested.identifier(),
                RelationshipStatus::Bidirectional {
                    thread_id: relationship_digest(42_000 + i),
                    remote_thread_id: relationship_digest(42_100 + i),
                    outstanding_nested_requests: vec![PendingNestedRelationship {
                        thread_id: relationship_digest(43_000 + i),
                        local_nested_vid: format!("did:example:nested:43_{i:03}"),
                    }],
                },
                nested_local.identifier(),
            )
            .unwrap();
    }

    (
        store,
        HighEntropyDirtySeed {
            local_vid: local_vid.identifier().to_string(),
            bidirectional_remote_vid: bidirectional_remote_vid
                .expect("high-entropy fixture is missing a bidirectional remote"),
            routed_remote_vid: routed_remote_vid
                .expect("high-entropy fixture is missing a routed remote"),
        },
    )
}

/// Pre-seeded routed topology for dirty wallet restart tests.
#[cfg(feature = "async")]
pub struct RoutedDirtyTopology {
    pub sender: AsyncSecureStore,
    pub intermediary: AsyncSecureStore,
    pub receiver: AsyncSecureStore,
    pub sender_vid: String,
    pub intermediary_vid: String,
    pub receiver_vid: String,
}

/// Create sender/intermediary/receiver stores with persisted route metadata.
#[cfg(feature = "async")]
pub fn create_routed_dirty_topology() -> RoutedDirtyTopology {
    let sender = create_async_test_store();
    let intermediary = create_async_test_store();
    let receiver = create_async_test_store();

    let sender_vid = create_test_vid();
    let intermediary_vid = create_test_vid();
    let receiver_vid = create_test_vid();

    sender.add_private_vid(sender_vid.clone(), None).unwrap();
    intermediary
        .add_private_vid(intermediary_vid.clone(), None)
        .unwrap();
    receiver
        .add_private_vid(receiver_vid.clone(), None)
        .unwrap();

    sender
        .add_verified_vid(intermediary_vid.clone(), None)
        .unwrap();
    sender.add_verified_vid(receiver_vid.clone(), None).unwrap();
    sender
        .set_relation_and_status_for_vid(
            intermediary_vid.identifier(),
            RelationshipStatus::bi_test(0x11, 0x22),
            sender_vid.identifier(),
        )
        .unwrap();
    sender
        .set_relation_and_status_for_vid(
            receiver_vid.identifier(),
            RelationshipStatus::bi_test(0x11, 0x22),
            sender_vid.identifier(),
        )
        .unwrap();
    // the exit entry is the receiver's own VID at the intermediary (spec 5.3.3)
    sender
        .set_route_for_vid(
            receiver_vid.identifier(),
            &[intermediary_vid.identifier(), receiver_vid.identifier()],
        )
        .unwrap();

    intermediary
        .add_verified_vid(sender_vid.clone(), None)
        .unwrap();
    intermediary
        .add_verified_vid(receiver_vid.clone(), None)
        .unwrap();
    intermediary
        .set_relation_and_status_for_vid(
            receiver_vid.identifier(),
            RelationshipStatus::bi_test(0x11, 0x22),
            intermediary_vid.identifier(),
        )
        .unwrap();
    intermediary
        .set_relation_and_status_for_vid(
            intermediary_vid.identifier(),
            RelationshipStatus::bi_test(0x11, 0x22),
            receiver_vid.identifier(),
        )
        .unwrap();
    intermediary
        .set_relation_and_status_for_vid(
            sender_vid.identifier(),
            RelationshipStatus::Unrelated,
            intermediary_vid.identifier(),
        )
        .unwrap();

    receiver.add_verified_vid(sender_vid.clone(), None).unwrap();
    receiver
        .add_verified_vid(intermediary_vid.clone(), None)
        .unwrap();
    receiver
        .set_relation_and_status_for_vid(
            sender_vid.identifier(),
            RelationshipStatus::bi_test(0x11, 0x22),
            receiver_vid.identifier(),
        )
        .unwrap();
    receiver
        .set_relation_and_status_for_vid(
            intermediary_vid.identifier(),
            RelationshipStatus::bi_test(0x11, 0x22),
            receiver_vid.identifier(),
        )
        .unwrap();

    RoutedDirtyTopology {
        sender,
        intermediary,
        receiver,
        sender_vid: sender_vid.identifier().to_string(),
        intermediary_vid: intermediary_vid.identifier().to_string(),
        receiver_vid: receiver_vid.identifier().to_string(),
    }
}

/// Export an async store into a normalized snapshot.
#[cfg(feature = "async")]
pub fn export_snapshot(store: &AsyncSecureStore) -> StoreExportSnapshot {
    let state = store.export().unwrap();
    export_snapshot_parts(state)
}

/// Repository-backed wallet fixtures used for smoke tests and future
/// compatibility coverage.
#[cfg(all(feature = "async", not(target_arch = "wasm32")))]
#[derive(Clone, Copy, Debug)]
pub enum RepoWalletFixture {
    CurrentDirtySmall,
}

#[cfg(all(feature = "async", not(target_arch = "wasm32")))]
impl RepoWalletFixture {
    fn file_name(self) -> &'static str {
        match self {
            Self::CurrentDirtySmall => "current-dirty-small.sqlite",
        }
    }

    pub fn password(self) -> &'static [u8] {
        b"test-password"
    }

    pub fn path(self) -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/wallets")
            .join(self.file_name())
    }
}

/// Fixture for persisted wallets backed by a real SQLite file.
#[cfg(all(feature = "async", not(target_arch = "wasm32")))]
pub struct PersistedStoreFixture {
    _dir: TempDir,
    wallet_path: PathBuf,
    sqlite_url: String,
    password: Vec<u8>,
}

#[cfg(all(feature = "async", not(target_arch = "wasm32")))]
impl PersistedStoreFixture {
    /// Create a new persisted wallet fixture.
    pub async fn new() -> Self {
        let dir = tempfile::tempdir().expect("Failed to create temporary persisted wallet dir");
        let wallet_path = dir.path().join("wallet.sqlite");
        let sqlite_url = format!("sqlite://{}", wallet_path.to_string_lossy());
        let password = b"test-password".to_vec();

        let storage = AskarSecureStorage::new(&sqlite_url, &password)
            .await
            .expect("Failed to create persisted wallet storage");
        storage
            .close()
            .await
            .expect("Failed to close persisted wallet storage");

        Self {
            _dir: dir,
            wallet_path,
            sqlite_url,
            password,
        }
    }

    /// Copy an existing wallet file into a temporary persisted fixture.
    pub fn from_existing_wallet(source_path: &Path, password: &[u8]) -> Self {
        let dir = tempfile::tempdir().expect("Failed to create temporary persisted wallet dir");
        let wallet_path = dir.path().join("wallet.sqlite");
        std::fs::copy(source_path, &wallet_path)
            .unwrap_or_else(|e| panic!("Failed to copy wallet fixture from {source_path:?}: {e}"));
        let sqlite_url = format!("sqlite://{}", wallet_path.to_string_lossy());

        Self {
            _dir: dir,
            wallet_path,
            sqlite_url,
            password: password.to_vec(),
        }
    }

    /// Return the storage URL used by this fixture.
    pub fn storage_url(&self) -> &str {
        &self.sqlite_url
    }

    /// Return the raw password used by this fixture.
    pub fn password(&self) -> &[u8] {
        &self.password
    }

    /// Return the SQLite file path used by this fixture.
    pub fn sqlite_path(&self) -> &Path {
        &self.wallet_path
    }

    /// Persist an in-memory async store to the SQLite wallet.
    pub async fn persist_from(&self, store: &AsyncSecureStore) {
        let storage = AskarSecureStorage::open(&self.sqlite_url, &self.password)
            .await
            .expect("Failed to open persisted wallet storage");
        storage
            .persist(store.export().expect("Failed to export async store"))
            .await
            .expect("Failed to persist async store");
        storage
            .close()
            .await
            .expect("Failed to close persisted wallet storage");
    }

    /// Reopen the SQLite wallet and import it into a fresh async store.
    pub async fn reopen_into_store(&self) -> AsyncSecureStore {
        let storage = AskarSecureStorage::open(&self.sqlite_url, &self.password)
            .await
            .expect("Failed to reopen persisted wallet storage");
        let state = storage
            .read()
            .await
            .expect("Failed to read persisted wallet storage");
        storage
            .close()
            .await
            .expect("Failed to close reopened wallet storage");

        let store = AsyncSecureStore::new();
        store
            .import(state)
            .expect("Failed to import persisted store data");
        store
    }
}

/// Create a persisted store fixture backed by a real SQLite file.
#[cfg(all(feature = "async", not(target_arch = "wasm32")))]
pub async fn create_persisted_store() -> PersistedStoreFixture {
    PersistedStoreFixture::new().await
}

/// Create a persisted fixture from a repo-tracked sqlite wallet.
#[cfg(all(feature = "async", not(target_arch = "wasm32")))]
pub fn create_repo_wallet_fixture(fixture: RepoWalletFixture) -> PersistedStoreFixture {
    PersistedStoreFixture::from_existing_wallet(&fixture.path(), fixture.password())
}

/// Persist and reopen an async store repeatedly using the same fixture.
#[cfg(all(feature = "async", not(target_arch = "wasm32")))]
pub async fn persist_reopen_cycle(
    store: &AsyncSecureStore,
    fixture: &PersistedStoreFixture,
    times: usize,
) -> AsyncSecureStore {
    if times == 0 {
        return store.clone();
    }

    let mut current = store.clone();
    for _ in 0..times {
        fixture.persist_from(&current).await;
        current = fixture.reopen_into_store().await;
    }

    current
}

/// Corrupt a sqlite file intentionally for failure-path testing.
#[cfg(not(target_arch = "wasm32"))]
pub fn corrupt_sqlite_file(path: &Path) {
    std::fs::write(path, b"not-a-valid-sqlite-file")
        .expect("Failed to write corrupted sqlite fixture");
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use super::*;

    #[test]
    fn test_create_test_vid() {
        let vid = create_test_vid();
        assert!(vid.identifier().starts_with("did:peer:"));
    }

    #[test]
    fn test_create_store_with_relationships() {
        let store = create_store_with_relationships(6);
        let vids = store.list_vids().unwrap();
        assert!(vids.len() >= 7);
    }

    #[test]
    fn test_create_prepopulated_store_has_history_keys() {
        let store = create_prepopulated_store();
        assert!(store.has_key("test-history-key-1"));
        assert!(store.has_key("test-history-key-2"));
        let (_, vid_rows, _) = export_snapshot_sync(&store);
        assert!(vid_rows.iter().any(|row| row.contains("Bi:")));
    }

    #[test]
    fn test_port_allocator_range() {
        let allocator = TestPortAllocator::new();
        let port = allocator.allocate();
        assert!((MIN_TEST_PORT..=MAX_TEST_PORT).contains(&port));
    }

    #[test]
    fn test_port_allocator_cycles_after_range() {
        let allocator = TestPortAllocator::new();
        let mut seen = HashSet::new();
        let mut found_duplicate = false;

        for _ in 0..(TEST_PORT_SPAN as usize + 32) {
            let port = allocator.allocate();
            assert!((MIN_TEST_PORT..=MAX_TEST_PORT).contains(&port));
            if !seen.insert(port) {
                found_duplicate = true;
                break;
            }
        }

        assert!(found_duplicate);
    }

    #[cfg(all(feature = "async", not(target_arch = "wasm32")))]
    #[tokio::test]
    async fn test_persisted_store_fixture_roundtrip() {
        let fixture = create_persisted_store().await;

        let original = create_async_test_store();
        let vid = create_test_vid();
        original.add_private_vid(vid, None).unwrap();

        fixture.persist_from(&original).await;
        let reopened = fixture.reopen_into_store().await;

        assert_eq!(
            original.export().unwrap().vids.len(),
            reopened.export().unwrap().vids.len()
        );
    }

    #[cfg(feature = "async")]
    #[test]
    fn test_create_dirty_store_with_transition_seed() {
        let (store, seed) = create_dirty_store_with_transition_seed();
        assert_eq!(
            store.resolve_alias("local-owner").unwrap().as_deref(),
            Some(seed.local_vid.as_str())
        );
        assert!(store.has_key("transition-seed-key"));
    }

    #[cfg(feature = "async")]
    #[test]
    fn test_create_high_entropy_dirty_store_shapes_state() {
        let (store, seed) = create_high_entropy_dirty_store();
        assert_eq!(
            store.resolve_alias("high-entropy-root").unwrap().as_deref(),
            Some(seed.local_vid.as_str())
        );
        assert!(store.has_key("high-entropy-key-00"));
        let (_aliases, vid_rows, _keys) = export_snapshot(&store);
        assert!(vid_rows.iter().any(|row| row.contains(">")));
        assert!(vid_rows.iter().any(|row| row.contains("Bi:")));
    }

    #[cfg(feature = "async")]
    #[test]
    fn test_create_routed_dirty_topology_has_tunnel_metadata() {
        let topology = create_routed_dirty_topology();
        let (_aliases, vid_rows, _keys) = export_snapshot(&topology.sender);
        let routed_row = vid_rows
            .iter()
            .find(|row| row.starts_with(&topology.receiver_vid))
            .unwrap();
        assert!(routed_row.contains(&topology.intermediary_vid));
    }

    #[cfg(feature = "async")]
    #[test]
    fn test_create_routed_dirty_topology_supports_direct_open_message_flow() {
        let topology = create_routed_dirty_topology();
        let (_endpoint, mut sealed_message) = topology
            .sender
            .seal_message(
                &topology.sender_vid,
                &topology.receiver_vid,
                b"direct-open-flow",
            )
            .unwrap();

        let crate::ReceivedTspMessage::ForwardRequest {
            next_hop,
            route,
            opaque_payload,
            ..
        } = topology
            .intermediary
            .open_message(&mut sealed_message)
            .unwrap()
        else {
            panic!("intermediary did not decode routed payload");
        };

        let (_endpoint, mut forwarded_message) = topology
            .intermediary
            .make_next_routed_message(&next_hop, route, &opaque_payload)
            .unwrap();

        let crate::ReceivedTspMessage::GenericMessage {
            sender, message, ..
        } = topology
            .receiver
            .open_message(&mut forwarded_message)
            .unwrap()
        else {
            panic!("receiver did not decode forwarded payload");
        };

        assert_eq!(sender, topology.sender_vid);
        assert_eq!(message.iter().as_slice(), b"direct-open-flow");
    }

    #[cfg(all(feature = "async", not(target_arch = "wasm32")))]
    #[tokio::test]
    async fn test_persist_reopen_cycle_helper() {
        let fixture = create_persisted_store().await;
        let original = create_async_test_store();
        let vid = create_test_vid();
        original.add_private_vid(vid, None).unwrap();

        let reopened = persist_reopen_cycle(&original, &fixture, 2).await;
        assert_eq!(
            original.export().unwrap().vids.len(),
            reopened.export().unwrap().vids.len()
        );
    }

    #[cfg(all(feature = "async", not(target_arch = "wasm32")))]
    #[tokio::test]
    async fn test_repo_wallet_fixture_roundtrip() {
        let fixture = create_repo_wallet_fixture(RepoWalletFixture::CurrentDirtySmall);
        let reopened = fixture.reopen_into_store().await;
        let state = reopened.export().unwrap();
        assert!(!state.vids.is_empty());
        assert!(
            !state.aliases.is_empty()
                || !state.keys.aliases().is_empty()
                || !state.method_state.resolution_contexts.is_empty(),
            "repo wallet fixture should carry dirty wallet state"
        );
    }
}