solid-pod-rs-server 0.5.0-alpha.18

Drop-in Solid Pod server binary. Wraps solid-pod-rs with actix-web and a JSS-compatible layered config loader.
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
//! MRC20 trail persistence — the server-side load/save for a token's
//! Bitcoin-anchored state chain (ADR-059 Phase 4; JSS `token.js:189-208`).
//!
//! A trail lives at `/.well-known/token/{ticker}.json` in pod storage. JSS
//! persists the issuer **private key** straight inside the trail JSON
//! (`token.js:294`) so `transferToken` can re-sign the next state. We keep the
//! same on-disk shape but model it as a [`StoredTrail`](crate::trail_store::StoredTrail) = the public
//! [`Mrc20Trail`](solid_pod_rs::mrc20::Mrc20Trail) plus a `privkey` (and a `date_created` the library type does
//! not carry), so the secret never leaks onto the shared `Mrc20Trail` type that
//! flows through wasm/core and the portable proof.
//!
//! Native-only: it uses `Arc<dyn Storage>` (the pod's filesystem/cloud
//! backend). wasm consumers never compile this.

use std::sync::Arc;

use bytes::Bytes;
use serde::{Deserialize, Serialize};

use solid_pod_rs::blocktrail::{network_for_txo_chain, Blocktrail};
use solid_pod_rs::mrc20::{Mrc20State, Mrc20Trail};
use solid_pod_rs::payments::PaymentError;
use solid_pod_rs::storage::Storage;
use solid_pod_rs::PodError;

/// Pod-storage path of a trail file (JSS `token.js:194-196`). Ticker is
/// lower-cased so `PROV` and `prov` resolve to one file.
#[must_use]
pub fn trail_path(ticker: &str) -> String {
    format!("/.well-known/token/{}.json", ticker.to_lowercase())
}

/// Whether `path` is a pod-storage trail file that holds an issuer secret
/// ([`trail_path`], [`gitmark_trail_path`]). The public
/// `/.well-known/gitmark/{name}/blocktrails.json` is deliberately excluded:
/// it is the file a verifier reads and carries no secret.
#[must_use]
pub fn is_secret_trail_path(path: &str) -> bool {
    // Canonicalise first (decode once, collapse `//`, add the leading `/`) and
    // compare whole segments, so no spelling of the path slips past the test.
    // A path that cannot be canonicalised is treated as secret.
    let Some(canon) = crate::canonical_pod_path(path) else {
        return true;
    };
    let segs = lower_segments(&canon);
    let segs: Vec<&str> = segs.iter().map(String::as_str).collect();
    match segs.as_slice() {
        [".well-known", "token", ..] => true,
        // `/.well-known/gitmark/{name}/blocktrails.json` is the public file.
        [".well-known", "gitmark", _, "blocktrails.json"] => canon.ends_with('/'),
        [".well-known", "gitmark", ..] => true,
        _ => false,
    }
}

/// Whether `path` is under `/.well-known/prov/` (the pending-refunds list and
/// the epoch counter). Both are operator state: payer DIDs and amounts, and a
/// file whose corruption halts epoch anchoring.
#[must_use]
pub fn is_prov_state_path(path: &str) -> bool {
    let Some(canon) = crate::canonical_pod_path(path) else {
        return true;
    };
    let segs = lower_segments(&canon);
    matches!(
        segs.iter()
            .map(String::as_str)
            .collect::<Vec<_>>()
            .as_slice(),
        [".well-known", "prov", ..]
    )
}

/// Whether `path` is under `/.well-known/webledgers/`: the Web Ledger and the
/// payment state, replay set, order book and pool documents. They hold every
/// principal's balance, and a balance written there is spendable; only the
/// payment handlers, which use `Storage` directly, may change them.
#[must_use]
pub fn is_server_state_path(path: &str) -> bool {
    let Some(canon) = crate::canonical_pod_path(path) else {
        return true;
    };
    let segs = lower_segments(&canon);
    matches!(
        segs.iter()
            .map(String::as_str)
            .collect::<Vec<_>>()
            .as_slice(),
        [".well-known", "webledgers", ..]
    )
}

fn lower_segments(canon: &str) -> Vec<String> {
    canon
        .split('/')
        .filter(|s| !s.is_empty())
        // Full Unicode lower-casing, not ASCII-only: on a case-insensitive
        // filesystem `.well-known/TOKEN` and `.well-known/to\u{212A}en`
        // (Kelvin sign) reach the same directory as `token`.
        // `fold_case` adds the full-folding cases lower-casing misses.
        .map(solid_pod_rs::security::dotfile::fold_case)
        .collect()
}

/// The persisted trail — the public [`Mrc20Trail`] plus the issuer secret and
/// creation timestamp (JSS stores all of these in one JSON blob,
/// `token.js:290-303`). Serialises with camelCase keys to match the JSS file
/// format byte-for-byte so a JSS-written trail loads here and vice versa.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StoredTrail {
    pub ticker: String,
    pub name: String,
    pub supply: u64,
    /// Issuer private key (64-char hex). **Secret** — never placed on the
    /// public `Mrc20Trail` nor in any portable proof.
    pub privkey: String,
    pub pubkey_base: String,
    pub states: Vec<Mrc20State>,
    pub state_strings: Vec<String>,
    pub current_txid: String,
    pub current_vout: u32,
    pub current_amount: u64,
    pub network: String,
    #[serde(default)]
    pub date_created: String,
}

impl StoredTrail {
    /// Project to the public [`Mrc20Trail`] (drops the secret `privkey`).
    #[must_use]
    pub fn to_public(&self) -> Mrc20Trail {
        Mrc20Trail {
            ticker: self.ticker.clone(),
            name: self.name.clone(),
            supply: self.supply,
            pubkey_base: self.pubkey_base.clone(),
            states: self.states.clone(),
            state_strings: self.state_strings.clone(),
            current_txid: self.current_txid.clone(),
            current_vout: self.current_vout,
            current_amount: self.current_amount,
            network: self.network.clone(),
            date_created: self.date_created.clone(),
        }
    }

    /// Re-absorb a public [`Mrc20Trail`] (e.g. the appended trail returned by a
    /// transfer/anchor) while keeping this trail's secret `privkey`.
    pub fn merge_public(&mut self, public: &Mrc20Trail) {
        self.states = public.states.clone();
        self.state_strings = public.state_strings.clone();
        self.current_txid = public.current_txid.clone();
        self.current_vout = public.current_vout;
        self.current_amount = public.current_amount;
        self.supply = public.supply;
    }
}

/// Load a trail for `ticker`, or `None` if it does not exist (JSS
/// `loadTrail`, `token.js:198-203`). Only [`PodError::NotFound`] means absent:
/// any other read failure is an error, so a storage fault is never mistaken
/// for "no trail" (and a trail never overwritten on the strength of one).
pub async fn load_trail(
    storage: &Arc<dyn Storage>,
    ticker: &str,
) -> Result<Option<StoredTrail>, PaymentError> {
    match storage.get(&trail_path(ticker)).await {
        Ok((bytes, _meta)) => {
            let trail: StoredTrail = serde_json::from_slice(&bytes)
                .map_err(|e| PaymentError::Store(format!("malformed trail {ticker}: {e}")))?;
            Ok(Some(trail))
        }
        Err(PodError::NotFound(_)) => Ok(None),
        Err(e) => Err(PaymentError::Store(format!("read trail {ticker}: {e}"))),
    }
}

/// Persist a trail (JSS `saveTrail`, `token.js:205-208`). Pretty-printed to
/// match the JSS `JSON.stringify(trail, null, 2)` file format.
pub async fn save_trail(
    storage: &Arc<dyn Storage>,
    trail: &StoredTrail,
) -> Result<(), PaymentError> {
    let body = serde_json::to_vec_pretty(trail)
        .map_err(|e| PaymentError::Store(format!("serialise trail: {e}")))?;
    storage
        .put(
            &trail_path(&trail.ticker),
            Bytes::from(body),
            "application/json",
        )
        .await
        .map_err(|e| PaymentError::Store(format!("save trail: {e}")))?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Git-mark trails (new trails' profile)
// ---------------------------------------------------------------------------

/// The trail name a pod anchors under when nothing names one.
pub const DEFAULT_GITMARK_TRAIL: &str = "prov";

/// Pod-storage path of a git-mark trail file (with its base secret). The name
/// is lower-cased, as [`trail_path`] does for tickers.
#[must_use]
pub fn gitmark_trail_path(name: &str) -> String {
    format!("/.well-known/gitmark/{}.json", name.to_lowercase())
}

/// Pod-storage path of a git-mark trail's public `blocktrails.json` (no
/// secret), the file a verifier reads.
#[must_use]
pub fn gitmark_blocktrails_path(name: &str) -> String {
    format!(
        "/.well-known/gitmark/{}/blocktrails.json",
        name.to_lowercase()
    )
}

/// A persisted git-mark trail: the public [`Blocktrail`] (§5.2 shape) plus
/// the base key's secret, which spends each mark to the next.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StoredGitmarkTrail {
    /// The trail's name (what an anchor's `ticker` names).
    pub name: String,
    /// The base key's secret (64-char hex). **Secret**: never in the public
    /// `blocktrails.json`.
    pub privkey: String,
    /// The trail as a verifier reads it.
    pub trail: Blocktrail,
    /// Creation timestamp, set by the caller.
    #[serde(default)]
    pub date_created: String,
}

impl StoredGitmarkTrail {
    /// The network name of the trail's chain (`testnet4` for `tbtc4`), as
    /// [`solid_pod_rs::mrc20::bt_address`] takes it; empty when it names none.
    #[must_use]
    pub fn network(&self) -> String {
        self.trail
            .chain
            .as_deref()
            .map(network_for_txo_chain)
            .unwrap_or_default()
    }
}

/// Load the git-mark trail `name`, or `None` if there is none. Only
/// [`PodError::NotFound`] means absent; any other read failure is an error.
pub async fn load_gitmark_trail(
    storage: &Arc<dyn Storage>,
    name: &str,
) -> Result<Option<StoredGitmarkTrail>, PaymentError> {
    match storage.get(&gitmark_trail_path(name)).await {
        Ok((bytes, _meta)) => serde_json::from_slice(&bytes)
            .map(Some)
            .map_err(|e| PaymentError::Store(format!("malformed git-mark trail {name}: {e}"))),
        Err(PodError::NotFound(_)) => Ok(None),
        Err(e) => Err(PaymentError::Store(format!(
            "read git-mark trail {name}: {e}"
        ))),
    }
}

/// Pod-storage path of a git-mark trail's pending broadcast intent.
#[must_use]
pub fn gitmark_intent_path(name: &str) -> String {
    format!("/.well-known/gitmark/{}/intent.json", name.to_lowercase())
}

/// A broadcast about to happen: the txid the signed transaction will have and
/// the trail as it stands once that transaction is in. Written before the
/// broadcast, so a lost response or a failed save is resolved from the chain
/// on the next advance instead of leaving the stored head stale.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GitmarkIntent {
    /// The txid the broadcast transaction has.
    pub txid: String,
    /// The trail once the transaction is in (with its secret, as the trail file).
    pub stored: StoredGitmarkTrail,
}

/// Load the pending intent for git-mark trail `name`, if any. Only
/// [`PodError::NotFound`] means none.
pub async fn load_gitmark_intent(
    storage: &Arc<dyn Storage>,
    name: &str,
) -> Result<Option<GitmarkIntent>, PaymentError> {
    match storage.get(&gitmark_intent_path(name)).await {
        Ok((bytes, _meta)) => serde_json::from_slice(&bytes)
            .map(Some)
            .map_err(|e| PaymentError::Store(format!("malformed git-mark intent {name}: {e}"))),
        Err(PodError::NotFound(_)) => Ok(None),
        Err(e) => Err(PaymentError::Store(format!(
            "read git-mark intent {name}: {e}"
        ))),
    }
}

/// Persist the pending intent for a git-mark trail.
pub async fn save_gitmark_intent(
    storage: &Arc<dyn Storage>,
    intent: &GitmarkIntent,
) -> Result<(), PaymentError> {
    let body = serde_json::to_vec(intent)
        .map_err(|e| PaymentError::Store(format!("serialise git-mark intent: {e}")))?;
    storage
        .put(
            &gitmark_intent_path(&intent.stored.name),
            Bytes::from(body),
            "application/json",
        )
        .await
        .map_err(|e| PaymentError::Store(format!("save git-mark intent: {e}")))?;
    Ok(())
}

/// Remove the pending intent for git-mark trail `name` (already absent is fine).
pub async fn clear_gitmark_intent(
    storage: &Arc<dyn Storage>,
    name: &str,
) -> Result<(), PaymentError> {
    match storage.delete(&gitmark_intent_path(name)).await {
        Ok(()) | Err(PodError::NotFound(_)) => Ok(()),
        Err(e) => Err(PaymentError::Store(format!(
            "clear git-mark intent {name}: {e}"
        ))),
    }
}

/// Take the in-process lock for `key`, serialising every read-modify-write of
/// the file(s) it names. Anchorers are built per request (and per worker), so
/// the lock is process-global and keyed by path alone: serving separate
/// storages from one process at worst over-serialises, never under-serialises.
pub(crate) async fn lock_path(key: &str) -> tokio::sync::OwnedMutexGuard<()> {
    type Locks = std::collections::HashMap<String, Arc<tokio::sync::Mutex<()>>>;
    static LOCKS: std::sync::LazyLock<std::sync::Mutex<Locks>> =
        std::sync::LazyLock::new(Default::default);
    let lock = {
        let mut locks = LOCKS.lock().unwrap_or_else(|p| p.into_inner());
        // Drop locks nobody holds or waits on, so the map stays bounded.
        locks.retain(|_, l| Arc::strong_count(l) > 1);
        locks.entry(key.to_string()).or_default().clone()
    };
    lock.lock_owned().await
}

/// Persist a git-mark trail and publish its `blocktrails.json` beside it.
pub async fn save_gitmark_trail(
    storage: &Arc<dyn Storage>,
    stored: &StoredGitmarkTrail,
) -> Result<(), PaymentError> {
    let body = serde_json::to_vec_pretty(stored)
        .map_err(|e| PaymentError::Store(format!("serialise git-mark trail: {e}")))?;
    storage
        .put(
            &gitmark_trail_path(&stored.name),
            Bytes::from(body),
            "application/json",
        )
        .await
        .map_err(|e| PaymentError::Store(format!("save git-mark trail: {e}")))?;
    let public = serde_json::to_vec_pretty(&stored.trail)
        .map_err(|e| PaymentError::Store(format!("serialise blocktrails.json: {e}")))?;
    storage
        .put(
            &gitmark_blocktrails_path(&stored.name),
            Bytes::from(public),
            "application/json",
        )
        .await
        .map_err(|e| PaymentError::Store(format!("save blocktrails.json: {e}")))?;
    Ok(())
}

/// A fault-injecting [`Storage`] for the anchoring tests: it wraps a real
/// backend, fails chosen paths with `Io`, and (optionally) yields at every
/// call so concurrent tasks genuinely interleave.
#[cfg(test)]
pub(crate) mod fault_storage {
    use super::*;
    use solid_pod_rs::storage::{ResourceMeta, StorageEvent};
    use solid_pod_rs::PodError;
    use std::collections::HashSet;
    use std::sync::Mutex;

    pub(crate) struct FaultStorage {
        pub(crate) inner: Arc<dyn Storage>,
        pub(crate) fail_get: Mutex<HashSet<String>>,
        pub(crate) fail_put: Mutex<HashSet<String>>,
        pub(crate) yielding: bool,
    }

    impl FaultStorage {
        pub(crate) fn new(inner: Arc<dyn Storage>, yielding: bool) -> Arc<Self> {
            Arc::new(Self {
                inner,
                fail_get: Mutex::default(),
                fail_put: Mutex::default(),
                yielding,
            })
        }
        pub(crate) fn fail_get(&self, path: &str) {
            self.fail_get.lock().unwrap().insert(path.to_string());
        }
        pub(crate) fn fail_put(&self, path: &str) {
            self.fail_put.lock().unwrap().insert(path.to_string());
        }
        pub(crate) fn heal(&self) {
            self.fail_get.lock().unwrap().clear();
            self.fail_put.lock().unwrap().clear();
        }
        fn io() -> PodError {
            PodError::Io(std::io::Error::other("injected fault"))
        }
    }

    #[async_trait::async_trait]
    impl Storage for FaultStorage {
        async fn get(&self, path: &str) -> Result<(Bytes, ResourceMeta), PodError> {
            if self.yielding {
                tokio::task::yield_now().await;
            }
            if self.fail_get.lock().unwrap().contains(path) {
                return Err(Self::io());
            }
            self.inner.get(path).await
        }
        async fn put(
            &self,
            path: &str,
            body: Bytes,
            content_type: &str,
        ) -> Result<ResourceMeta, PodError> {
            if self.yielding {
                tokio::task::yield_now().await;
            }
            if self.fail_put.lock().unwrap().contains(path) {
                return Err(Self::io());
            }
            self.inner.put(path, body, content_type).await
        }
        async fn delete(&self, path: &str) -> Result<(), PodError> {
            self.inner.delete(path).await
        }
        async fn list(&self, container: &str) -> Result<Vec<String>, PodError> {
            self.inner.list(container).await
        }
        async fn head(&self, path: &str) -> Result<ResourceMeta, PodError> {
            self.inner.head(path).await
        }
        async fn exists(&self, path: &str) -> Result<bool, PodError> {
            self.inner.exists(path).await
        }
        async fn watch(
            &self,
            path: &str,
        ) -> Result<tokio::sync::mpsc::Receiver<StorageEvent>, PodError> {
            self.inner.watch(path).await
        }
    }
}

#[cfg(test)]
mod tests {
    use super::fault_storage::FaultStorage;
    use super::*;
    use solid_pod_rs::mrc20::MRC20_PROFILE;
    use solid_pod_rs::storage::memory::MemoryBackend;

    #[test]
    fn secret_and_prov_paths_compare_whole_segments() {
        for p in [
            "/.well-known/token/x.json",
            ".well-known//token/x.json",
            "/.well-known/token/blocktrails.json",
            "/.WELL-KNOWN/gitmark/prov/intent.json",
            "/.well-known/TOKEN/x.json",
            "/.well-known/to\u{212A}en/x.json",
            "/.well-known/gitmar\u{212A}/prov/intent.json",
            "/.well-known/token/",
        ] {
            assert!(is_secret_trail_path(p), "{p}");
        }
        for p in [
            "/.well-known/gitmark/prov/blocktrails.json",
            "/.well-known/tokens/x.json",
            "/x/.well-known/token/y",
            "/open/y",
        ] {
            assert!(!is_secret_trail_path(p), "{p}");
        }
        assert!(is_prov_state_path("//.well-known/prov/epoch.json"));
        assert!(!is_prov_state_path("/.well-known/provision/x"));
    }

    fn genesis() -> Mrc20State {
        Mrc20State {
            profile: MRC20_PROFILE.into(),
            prev: "0".repeat(64),
            seq: 0,
            ticker: Some("PROV".into()),
            name: Some("Prov".into()),
            decimals: Some(0),
            supply: Some(1000),
            balances: Some(std::collections::BTreeMap::from([("02ab".into(), 1000)])),
            ops: vec![],
            anchor: None,
        }
    }

    fn sample() -> StoredTrail {
        StoredTrail {
            ticker: "PROV".into(),
            name: "Prov".into(),
            supply: 1000,
            privkey: "07".repeat(32),
            pubkey_base: "02".to_string() + &"ab".repeat(32),
            states: vec![genesis()],
            state_strings: vec!["{\"seq\":0}".into()],
            current_txid: "ab".repeat(32),
            current_vout: 0,
            current_amount: 9700,
            network: "testnet4".into(),
            date_created: "2026-06-13T00:00:00Z".into(),
        }
    }

    #[test]
    fn trail_path_lowercases() {
        assert_eq!(trail_path("PROV"), "/.well-known/token/prov.json");
        assert_eq!(trail_path("prov"), "/.well-known/token/prov.json");
    }

    #[test]
    fn to_public_drops_privkey() {
        let t = sample();
        let public = t.to_public();
        // The public type has no privkey field; round-trip its JSON and assert
        // the secret is absent.
        let json = serde_json::to_string(&public).unwrap();
        assert!(
            !json.contains(&t.privkey),
            "privkey must not appear in public trail"
        );
        assert_eq!(public.ticker, "PROV");
        assert_eq!(public.current_amount, 9700);
    }

    #[test]
    fn stored_trail_uses_camelcase_keys() {
        // JSS file-format parity: keys are camelCase (pubkeyBase, stateStrings…).
        let json = serde_json::to_string(&sample()).unwrap();
        assert!(json.contains("\"pubkeyBase\""));
        assert!(json.contains("\"stateStrings\""));
        assert!(json.contains("\"currentTxid\""));
        assert!(json.contains("\"dateCreated\""));
    }

    #[tokio::test]
    async fn load_missing_trail_is_none() {
        let storage: Arc<dyn Storage> = Arc::new(MemoryBackend::new());
        let got = load_trail(&storage, "NOPE").await.unwrap();
        assert!(got.is_none());
    }

    #[tokio::test]
    async fn save_then_load_round_trips() {
        let storage: Arc<dyn Storage> = Arc::new(MemoryBackend::new());
        save_trail(&storage, &sample()).await.unwrap();
        let got = load_trail(&storage, "PROV")
            .await
            .unwrap()
            .expect("trail present");
        assert_eq!(got.ticker, "PROV");
        assert_eq!(got.privkey, "07".repeat(32));
        assert_eq!(got.states.len(), 1);
        // Lower-cased lookup also resolves.
        assert!(load_trail(&storage, "prov").await.unwrap().is_some());
    }

    #[tokio::test]
    async fn merge_public_keeps_secret() {
        let mut t = sample();
        let secret = t.privkey.clone();
        let mut public = t.to_public();
        public.current_txid = "ff".repeat(32);
        public.current_amount = 9400;
        public.states.push(genesis()); // simulate an appended state
        t.merge_public(&public);
        assert_eq!(t.privkey, secret, "secret retained across merge");
        assert_eq!(t.current_txid, "ff".repeat(32));
        assert_eq!(t.current_amount, 9400);
        assert_eq!(t.states.len(), 2);
    }

    #[tokio::test]
    async fn gitmark_trail_round_trips_and_publishes_no_secret() {
        use solid_pod_rs::blocktrail::BlocktrailTxo;
        let storage: Arc<dyn Storage> = Arc::new(MemoryBackend::new());
        let commit = "9adc596cfd1100333393a12f2f41b2d820f16d0b";
        let stored = StoredGitmarkTrail {
            name: "Prov".into(),
            privkey: "07".repeat(32),
            trail: Blocktrail::gitmark(
                "02".to_string() + &"ab".repeat(32),
                "tbtc4",
                vec![commit.into()],
                vec![BlocktrailTxo::new("tbtc4", "cd".repeat(32), 0).with_commit(commit)],
            ),
            date_created: "2026-10-02T00:00:00Z".into(),
        };
        assert_eq!(stored.network(), "testnet4");
        save_gitmark_trail(&storage, &stored).await.unwrap();
        let back = load_gitmark_trail(&storage, "prov").await.unwrap().unwrap();
        assert_eq!(back.trail, stored.trail);
        assert_eq!(back.privkey, stored.privkey);
        let (public, _) = storage
            .get(&gitmark_blocktrails_path("PROV"))
            .await
            .unwrap();
        let public = String::from_utf8(public.to_vec()).unwrap();
        assert!(
            !public.contains(&stored.privkey),
            "the secret is never published"
        );
        let parsed: Blocktrail = serde_json::from_str(&public).unwrap();
        assert_eq!(parsed, stored.trail);
        assert!(load_gitmark_trail(&storage, "none")
            .await
            .unwrap()
            .is_none());
    }

    #[tokio::test]
    async fn loaders_propagate_storage_errors_and_only_not_found_is_absent() {
        let mem: Arc<dyn Storage> = Arc::new(MemoryBackend::new());
        let faulty = FaultStorage::new(mem, false);
        faulty.fail_get(&trail_path("prov"));
        faulty.fail_get(&gitmark_trail_path("prov"));
        let storage: Arc<dyn Storage> = faulty.clone();
        assert!(load_trail(&storage, "prov").await.is_err());
        assert!(load_gitmark_trail(&storage, "prov").await.is_err());
        // a path that is merely absent is still `None`
        assert!(load_trail(&storage, "other").await.unwrap().is_none());
        assert!(load_gitmark_trail(&storage, "other")
            .await
            .unwrap()
            .is_none());
    }
}