host-chain-core 0.3.8

WASM-compatible DotNS resolution, IPFS fetching, and CAR parsing (async, reqwest + ruzstd)
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
//! Generic chain state machine — shared between WASM and native.
//!
//! Tracks chain connection status, processes JSON-RPC responses, and persists
//! chain databases. The state machine is generic over [`ChainStore`] so the
//! same logic works with localStorage (WASM) and the filesystem (native).

use std::collections::HashMap;

use crate::chain::{
    parse_block_number, ChainExtra, ChainId, ChainState, ChainStatus, REQ_ID_PARA_DB_SAVE,
    REQ_ID_RELAY_DB_SAVE,
};
use crate::store::ChainStore;

/// Starting health subscription ID. Incremented on each health check response.
const INITIAL_HEALTH_ID: u64 = 1000;

/// Per-chain state tracked by the state machine.
struct ChainEntry {
    status: ChainStatus,
    relay_db_key: String,
    para_db_key: String,
    chain_specs: Option<(String, String)>,
    health_id: u64,
}

/// Pure state machine for chain connections — no networking, no async.
///
/// Processes JSON-RPC responses from smoldot (or smoldot-js on WASM),
/// tracks chain status, and persists chain databases via a [`ChainStore`].
pub struct ChainStateMachine<S: ChainStore> {
    chains: HashMap<ChainId, ChainEntry>,
    store: S,
}

impl<S: ChainStore> ChainStateMachine<S> {
    pub fn new(store: S) -> Self {
        Self {
            chains: HashMap::new(),
            store,
        }
    }

    /// Register a chain for tracking. Initial state is `Connecting`.
    pub fn register_chain(&mut self, chain: ChainId) {
        self.chains.insert(
            chain,
            ChainEntry {
                status: ChainStatus {
                    id: chain,
                    name: chain.display_name(),
                    state: ChainState::Connecting,
                    extra: ChainExtra::None,
                },
                relay_db_key: chain.relay_db_key().to_string(),
                para_db_key: chain.para_db_key(),
                chain_specs: chain
                    .chain_specs()
                    .map(|(r, p)| (r.to_string(), p.to_string())),
                health_id: INITIAL_HEALTH_ID,
            },
        );
    }

    /// Register a chain from a [`ChainRegistryEntry`], using the entry's owned
    /// strings for db keys and chain specs instead of the `ChainId` enum methods.
    pub fn register_chain_entry(&mut self, entry: &crate::registry::ChainRegistryEntry) {
        let chain = entry.id;
        self.chains.insert(
            chain,
            ChainEntry {
                status: ChainStatus {
                    id: chain,
                    name: chain.display_name(),
                    state: ChainState::Connecting,
                    extra: ChainExtra::None,
                },
                relay_db_key: entry.relay_db_key.clone(),
                para_db_key: entry.para_db_key.clone(),
                chain_specs: entry.chain_specs.clone(),
                health_id: INITIAL_HEALTH_ID,
            },
        );
    }

    /// Unregister a chain (sets state to Disconnected).
    pub fn unregister_chain(&mut self, chain: ChainId) {
        if let Some(entry) = self.chains.get_mut(&chain) {
            entry.status.state = ChainState::Disconnected;
        }
    }

    /// Set the chain state, preserving existing `extra`.
    pub fn set_state(&mut self, chain: ChainId, state: ChainState) {
        if let Some(entry) = self.chains.get_mut(&chain) {
            entry.status.state = state;
        }
    }

    /// Set both state and extra data.
    pub fn set_state_with_extra(&mut self, chain: ChainId, state: ChainState, extra: ChainExtra) {
        if let Some(entry) = self.chains.get_mut(&chain) {
            entry.status.state = state;
            entry.status.extra = extra;
        }
    }

    /// Access the underlying store.
    pub fn store(&self) -> &S {
        &self.store
    }

    /// Process a JSON-RPC response from smoldot for a given chain.
    pub fn process_response(&mut self, chain: ChainId, text: &str) {
        let v: serde_json::Value = match serde_json::from_str(text) {
            Ok(v) => v,
            Err(_) => return,
        };

        let entry = match self.chains.get_mut(&chain) {
            Some(e) => e,
            None => return,
        };

        // Check for para DB save response.
        if let Some(id) = v.get("id").and_then(|i| i.as_u64()) {
            if id == REQ_ID_PARA_DB_SAVE {
                if let Some(db) = v.get("result").and_then(|r| r.as_str()) {
                    self.store.save(&entry.para_db_key, db);
                    log::info!("{chain:?}: saved para DB ({} bytes)", db.len());
                } else if let Some(err) = v.get("error") {
                    log::warn!("{chain:?}: para DB save returned error: {err}");
                }
                return;
            }
        }

        // Check for system_health response.
        if let Some(result) = v.get("result") {
            if let (Some(peers), Some(is_syncing)) = (
                result.get("peers").and_then(|p| p.as_u64()),
                result.get("isSyncing").and_then(|s| s.as_bool()),
            ) {
                let current_block = match &entry.status.state {
                    ChainState::Live { best_block, .. }
                    | ChainState::Syncing { best_block, .. } => *best_block,
                    _ => 0,
                };

                entry.status.state = if is_syncing {
                    ChainState::Syncing {
                        best_block: current_block,
                        peers: peers as u32,
                    }
                } else {
                    ChainState::Live {
                        best_block: current_block,
                        peers: peers as u32,
                    }
                };
                return;
            }
        }

        // Check for chain_newHead subscription notification.
        if let Some(block) = parse_block_number(text) {
            let (current_peers, current_syncing) = match &entry.status.state {
                ChainState::Live { peers, .. } => (*peers, false),
                ChainState::Syncing { peers, .. } => (*peers, true),
                ChainState::Connecting => (0, true),
                _ => (0, false),
            };

            entry.status.state = if current_syncing && current_peers > 0 {
                ChainState::Syncing {
                    best_block: block,
                    peers: current_peers,
                }
            } else {
                ChainState::Live {
                    best_block: block,
                    peers: current_peers,
                }
            };
        }
    }

    /// Process a JSON-RPC response for a relay chain DB save.
    pub fn process_relay_response(&mut self, chain: ChainId, text: &str) {
        if let Ok(v) = serde_json::from_str::<serde_json::Value>(text) {
            if v.get("id").and_then(|i| i.as_u64()) == Some(REQ_ID_RELAY_DB_SAVE) {
                if let Some(db) = v.get("result").and_then(|r| r.as_str()) {
                    let key = self
                        .chains
                        .get(&chain)
                        .map(|e| e.relay_db_key.as_str())
                        .unwrap_or_else(|| chain.relay_db_key());
                    self.store.save(key, db);
                    log::info!("{chain:?}: saved relay DB ({} bytes)", db.len());
                } else if let Some(err) = v.get("error") {
                    log::warn!("{chain:?}: relay DB save returned error: {err}");
                }
            }
        }
    }

    /// Set the chain state to Error.
    pub fn set_error(&mut self, chain: ChainId, msg: String) {
        if let Some(entry) = self.chains.get_mut(&chain) {
            entry.status.state = ChainState::Error(msg);
        }
    }

    pub fn status(&self, chain: ChainId) -> ChainStatus {
        self.chains
            .get(&chain)
            .map(|e| e.status.clone())
            .unwrap_or_else(|| ChainStatus::disconnected(chain))
    }

    pub fn all_statuses(&self) -> Vec<ChainStatus> {
        ChainId::all().iter().map(|&id| self.status(id)).collect()
    }

    /// Generate the chain_subscribeNewHeads JSON-RPC request.
    pub fn subscribe_new_heads_request() -> String {
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "chain_subscribeNewHeads",
            "params": []
        })
        .to_string()
    }

    /// Generate a system_health JSON-RPC request with an incrementing ID.
    /// Returns `None` if the chain is not registered.
    pub fn health_check_request(&mut self, chain: ChainId) -> Option<String> {
        let entry = self.chains.get_mut(&chain)?;
        entry.health_id += 1;
        Some(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": entry.health_id,
                "method": "system_health",
                "params": []
            })
            .to_string(),
        )
    }

    /// Generate a parachain DB save request.
    pub fn para_db_save_request() -> String {
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": REQ_ID_PARA_DB_SAVE,
            "method": "chainHead_unstable_finalizedDatabase",
            "params": []
        })
        .to_string()
    }

    /// Generate a relay chain DB save request.
    pub fn relay_db_save_request() -> String {
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": REQ_ID_RELAY_DB_SAVE,
            "method": "chainHead_unstable_finalizedDatabase",
            "params": []
        })
        .to_string()
    }

    /// Load persisted relay chain DB.
    pub fn load_relay_db(&self, chain: ChainId) -> String {
        match self.chains.get(&chain) {
            Some(e) => self.store.load(&e.relay_db_key),
            None => self.store.load(chain.relay_db_key()),
        }
    }

    /// Load persisted parachain DB.
    pub fn load_para_db(&self, chain: ChainId) -> String {
        match self.chains.get(&chain) {
            Some(e) => self.store.load(&e.para_db_key),
            None => self.store.load(&chain.para_db_key()),
        }
    }

    /// Get chain specs for a smoldot chain. Returns (relay_spec, para_spec).
    pub fn chain_specs(chain: ChainId) -> Option<(&'static str, &'static str)> {
        chain.chain_specs()
    }

    /// Get chain specs from the registered entry as owned strings.
    /// Returns `None` for unregistered chains or chains without specs.
    pub fn chain_specs_owned(&self, chain: ChainId) -> Option<(String, String)> {
        self.chains.get(&chain).and_then(|e| e.chain_specs.clone())
    }

    /// Clear both relay and para chain databases (used after a smoldot panic).
    pub fn clear_chain_dbs(&self, chain: ChainId) {
        let relay_key = self
            .chains
            .get(&chain)
            .map(|e| e.relay_db_key.clone())
            .unwrap_or_else(|| chain.relay_db_key().to_string());
        let para_key = self
            .chains
            .get(&chain)
            .map(|e| e.para_db_key.clone())
            .unwrap_or_else(|| chain.para_db_key());
        self.store.save(&relay_key, "");
        self.store.save(&para_key, "");
    }

    // -- Statement store RPC request generators --

    /// Generate a statement_submit JSON-RPC request.
    pub fn statement_submit_request(encoded_hex: &str, request_id: u64) -> String {
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": request_id,
            "method": "statement_submit",
            "params": [encoded_hex]
        })
        .to_string()
    }

    /// Generate a statement_subscribeStatement JSON-RPC request.
    pub fn statement_subscribe_request(request_id: u64) -> String {
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": request_id,
            "method": "statement_subscribeStatement",
            "params": ["any"]
        })
        .to_string()
    }

    /// Generate a statement_unsubscribeStatement JSON-RPC request.
    pub fn statement_unsubscribe_request(sub_id: &str, request_id: u64) -> String {
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": request_id,
            "method": "statement_unsubscribeStatement",
            "params": [sub_id]
        })
        .to_string()
    }

    /// Generate a statement_broadcastsStatement JSON-RPC request.
    pub fn statement_broadcasts_request(topic_hexes: &[String], request_id: u64) -> String {
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": request_id,
            "method": "statement_broadcastsStatement",
            "params": [topic_hexes]
        })
        .to_string()
    }

    /// Parse a statement_subscribeStatement notification.
    /// Returns hex-encoded statement strings found in the notification,
    /// or an empty vec if this is not a statement notification.
    pub fn parse_statement_notification(text: &str) -> Vec<String> {
        let v: serde_json::Value = match serde_json::from_str(text) {
            Ok(v) => v,
            Err(_) => return Vec::new(),
        };

        if v.get("method").and_then(|m| m.as_str()) != Some("statement_subscribeStatement") {
            return Vec::new();
        }

        let result = match v.pointer("/params/result") {
            Some(r) => r,
            None => return Vec::new(),
        };

        let stmts = result
            .pointer("/data/statements")
            .or_else(|| result.pointer("/newStatements/statements"))
            .or_else(|| result.get("statements"));

        match stmts.and_then(|s| s.as_array()) {
            Some(arr) => arr
                .iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect(),
            None => Vec::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::RefCell;

    struct InMemoryStore {
        data: RefCell<HashMap<String, String>>,
    }

    impl InMemoryStore {
        fn new() -> Self {
            Self {
                data: RefCell::new(HashMap::new()),
            }
        }
    }

    impl ChainStore for InMemoryStore {
        fn load(&self, key: &str) -> String {
            self.data.borrow().get(key).cloned().unwrap_or_default()
        }

        fn save(&self, key: &str, data: &str) {
            self.data
                .borrow_mut()
                .insert(key.to_string(), data.to_string());
        }
    }

    fn make_sm() -> ChainStateMachine<InMemoryStore> {
        let store = InMemoryStore::new();
        let mut sm = ChainStateMachine::new(store);
        sm.register_chain(ChainId::PaseoAssetHub);
        sm
    }

    #[test]
    fn register_sets_connecting() {
        let sm = make_sm();
        let status = sm.status(ChainId::PaseoAssetHub);
        assert!(matches!(status.state, ChainState::Connecting));
    }

    #[test]
    fn unregister_sets_disconnected() {
        let mut sm = make_sm();
        sm.unregister_chain(ChainId::PaseoAssetHub);
        let status = sm.status(ChainId::PaseoAssetHub);
        assert!(matches!(status.state, ChainState::Disconnected));
    }

    #[test]
    fn unregistered_chain_returns_disconnected() {
        let sm = make_sm();
        let status = sm.status(ChainId::Ethereum);
        assert!(matches!(status.state, ChainState::Disconnected));
    }

    #[test]
    fn health_response_sets_live() {
        let mut sm = make_sm();
        let resp = r#"{"jsonrpc":"2.0","id":1001,"result":{"peers":5,"isSyncing":false}}"#;
        sm.process_response(ChainId::PaseoAssetHub, resp);
        let status = sm.status(ChainId::PaseoAssetHub);
        assert!(matches!(status.state, ChainState::Live { peers: 5, .. }));
    }

    #[test]
    fn health_response_sets_syncing() {
        let mut sm = make_sm();
        let resp = r#"{"jsonrpc":"2.0","id":1001,"result":{"peers":3,"isSyncing":true}}"#;
        sm.process_response(ChainId::PaseoAssetHub, resp);
        let status = sm.status(ChainId::PaseoAssetHub);
        assert!(matches!(status.state, ChainState::Syncing { peers: 3, .. }));
    }

    #[test]
    fn new_head_updates_block_number() {
        let mut sm = make_sm();
        // First set to Live via health
        let health = r#"{"jsonrpc":"2.0","id":1001,"result":{"peers":5,"isSyncing":false}}"#;
        sm.process_response(ChainId::PaseoAssetHub, health);
        // Then new head notification
        let head =
            r#"{"jsonrpc":"2.0","method":"chain_newHead","params":{"result":{"number":"0x1a4"}}}"#;
        sm.process_response(ChainId::PaseoAssetHub, head);
        let status = sm.status(ChainId::PaseoAssetHub);
        match status.state {
            ChainState::Live {
                best_block, peers, ..
            } => {
                assert_eq!(best_block, 0x1a4);
                assert_eq!(peers, 5);
            }
            other => panic!("expected Live, got {other:?}"),
        }
    }

    #[test]
    fn para_db_save_stores_to_store() {
        let mut sm = make_sm();
        let resp = format!(
            r#"{{"jsonrpc":"2.0","id":{},"result":"saved-db-content"}}"#,
            REQ_ID_PARA_DB_SAVE,
        );
        sm.process_response(ChainId::PaseoAssetHub, &resp);
        assert_eq!(sm.store().load("PaseoAssetHub"), "saved-db-content");
    }

    #[test]
    fn relay_db_save_stores_to_store() {
        let mut sm = make_sm();
        let resp = format!(
            r#"{{"jsonrpc":"2.0","id":{},"result":"relay-db-content"}}"#,
            REQ_ID_RELAY_DB_SAVE,
        );
        sm.process_relay_response(ChainId::PaseoAssetHub, &resp);
        assert_eq!(
            sm.store().load(ChainId::PaseoAssetHub.relay_db_key()),
            "relay-db-content"
        );
    }

    #[test]
    fn set_state_preserves_extra() {
        let mut sm = make_sm();
        sm.set_state_with_extra(
            ChainId::PaseoAssetHub,
            ChainState::Live {
                best_block: 100,
                peers: 5,
            },
            ChainExtra::Eth {
                finalized_block: 50,
                gas_price_gwei: 20,
            },
        );
        // set_state (without extra) should preserve the Eth extra
        sm.set_state(
            ChainId::PaseoAssetHub,
            ChainState::Live {
                best_block: 200,
                peers: 3,
            },
        );
        let status = sm.status(ChainId::PaseoAssetHub);
        assert!(matches!(
            status.extra,
            ChainExtra::Eth {
                finalized_block: 50,
                gas_price_gwei: 20
            }
        ));
        assert!(matches!(
            status.state,
            ChainState::Live {
                best_block: 200,
                peers: 3
            }
        ));
    }

    #[test]
    fn set_state_with_extra_updates_both() {
        let mut sm = make_sm();
        sm.set_state_with_extra(
            ChainId::PaseoAssetHub,
            ChainState::Live {
                best_block: 100,
                peers: 5,
            },
            ChainExtra::Btc {
                tip_height: 800000,
                fee_rate_sat_vb: 10,
            },
        );
        let status = sm.status(ChainId::PaseoAssetHub);
        assert!(matches!(
            status.state,
            ChainState::Live {
                best_block: 100,
                peers: 5
            }
        ));
        assert!(matches!(
            status.extra,
            ChainExtra::Btc {
                tip_height: 800000,
                fee_rate_sat_vb: 10
            }
        ));
    }

    #[test]
    fn process_response_unregistered_chain_is_noop() {
        let mut sm = make_sm();
        let resp = r#"{"jsonrpc":"2.0","id":1001,"result":{"peers":5,"isSyncing":false}}"#;
        // Ethereum is not registered — should not panic or change anything
        sm.process_response(ChainId::Ethereum, resp);
        let status = sm.status(ChainId::Ethereum);
        assert!(matches!(status.state, ChainState::Disconnected));
    }

    #[test]
    fn health_check_request_unregistered_returns_none() {
        let mut sm = make_sm();
        assert!(sm.health_check_request(ChainId::Ethereum).is_none());
    }

    #[test]
    fn health_check_request_id_starts_above_1000_and_increments() {
        let mut sm = make_sm();
        let req1 = sm.health_check_request(ChainId::PaseoAssetHub).unwrap();
        let req2 = sm.health_check_request(ChainId::PaseoAssetHub).unwrap();

        let v1: serde_json::Value = serde_json::from_str(&req1).unwrap();
        let v2: serde_json::Value = serde_json::from_str(&req2).unwrap();

        let id1 = v1["id"].as_u64().unwrap();
        let id2 = v2["id"].as_u64().unwrap();

        assert!(id1 > 1000);
        assert_eq!(id2, id1 + 1);
    }

    #[test]
    fn all_statuses_includes_registered_chains() {
        let sm = make_sm();
        let statuses = sm.all_statuses();
        let paseo = statuses
            .iter()
            .find(|s| s.id == ChainId::PaseoAssetHub)
            .expect("PaseoAssetHub should be in all_statuses");
        assert!(matches!(paseo.state, ChainState::Connecting));
    }

    #[test]
    fn all_statuses_returns_disconnected_for_unregistered() {
        let sm = make_sm();
        let statuses = sm.all_statuses();
        let eth = statuses
            .iter()
            .find(|s| s.id == ChainId::Ethereum)
            .expect("Ethereum should be in all_statuses (Disconnected)");
        assert!(matches!(eth.state, ChainState::Disconnected));
    }

    #[test]
    fn parse_statement_notification_data_statements_path() {
        let text = r#"{"jsonrpc":"2.0","method":"statement_subscribeStatement","params":{"result":{"data":{"statements":["0xab","0xcd"]}}}}"#;
        let stmts = ChainStateMachine::<InMemoryStore>::parse_statement_notification(text);
        assert_eq!(stmts, vec!["0xab", "0xcd"]);
    }

    #[test]
    fn parse_statement_notification_new_statements_path() {
        let text = r#"{"jsonrpc":"2.0","method":"statement_subscribeStatement","params":{"result":{"newStatements":{"statements":["0xef"]}}}}"#;
        let stmts = ChainStateMachine::<InMemoryStore>::parse_statement_notification(text);
        assert_eq!(stmts, vec!["0xef"]);
    }

    #[test]
    fn parse_statement_notification_plain_statements_path() {
        let text = r#"{"jsonrpc":"2.0","method":"statement_subscribeStatement","params":{"result":{"statements":["0x11","0x22","0x33"]}}}"#;
        let stmts = ChainStateMachine::<InMemoryStore>::parse_statement_notification(text);
        assert_eq!(stmts, vec!["0x11", "0x22", "0x33"]);
    }

    #[test]
    fn parse_statement_notification_wrong_method_returns_empty() {
        let text = r#"{"jsonrpc":"2.0","method":"chain_newHead","params":{"result":{"statements":["0x11"]}}}"#;
        let stmts = ChainStateMachine::<InMemoryStore>::parse_statement_notification(text);
        assert!(stmts.is_empty());
    }

    #[test]
    fn parse_statement_notification_no_statements_returns_empty() {
        let text =
            r#"{"jsonrpc":"2.0","method":"statement_subscribeStatement","params":{"result":{}}}"#;
        let stmts = ChainStateMachine::<InMemoryStore>::parse_statement_notification(text);
        assert!(stmts.is_empty());
    }

    #[test]
    fn para_db_save_error_does_not_change_state() {
        let mut sm = make_sm();
        // Set to Live first
        let health = r#"{"jsonrpc":"2.0","id":1001,"result":{"peers":5,"isSyncing":false}}"#;
        sm.process_response(ChainId::PaseoAssetHub, health);

        // DB save error response — should not trigger health or new-head branches
        let error_resp = format!(
            r#"{{"jsonrpc":"2.0","id":{},"error":{{"code":-32000,"message":"db error"}}}}"#,
            REQ_ID_PARA_DB_SAVE,
        );
        sm.process_response(ChainId::PaseoAssetHub, &error_resp);

        // State should still be Live with peers=5
        let status = sm.status(ChainId::PaseoAssetHub);
        assert!(matches!(status.state, ChainState::Live { peers: 5, .. }));
        // And nothing should have been saved to the store
        assert_eq!(sm.store().load("PaseoAssetHub"), "");
    }

    #[test]
    fn register_chain_entry_sets_connecting() {
        use crate::chain::ConnectionBackend;
        use crate::registry::ChainRegistryEntry;
        let store = InMemoryStore::new();
        let mut sm = ChainStateMachine::new(store);
        sm.register_chain_entry(&ChainRegistryEntry {
            id: ChainId::PaseoAssetHub,
            genesis_hash: [0u8; 32],
            display_name: "Paseo Asset Hub".to_string(),
            endpoint: String::new(),
            backend: ConnectionBackend::Smoldot,
            relay_db_key: "custom-relay".to_string(),
            para_db_key: "custom-para".to_string(),
            chain_specs: None,
        });
        let status = sm.status(ChainId::PaseoAssetHub);
        assert!(matches!(status.state, ChainState::Connecting));
    }

    #[test]
    fn register_chain_entry_uses_entry_db_keys() {
        use crate::chain::ConnectionBackend;
        use crate::registry::ChainRegistryEntry;
        let store = InMemoryStore::new();
        let mut sm = ChainStateMachine::new(store);
        sm.register_chain_entry(&ChainRegistryEntry {
            id: ChainId::PaseoAssetHub,
            genesis_hash: [0u8; 32],
            display_name: "Paseo Asset Hub".to_string(),
            endpoint: String::new(),
            backend: ConnectionBackend::Smoldot,
            relay_db_key: "custom-relay".to_string(),
            para_db_key: "custom-para".to_string(),
            chain_specs: None,
        });

        // Simulate relay DB save — should use the entry's key
        let resp = format!(
            r#"{{"jsonrpc":"2.0","id":{},"result":"relay-data"}}"#,
            REQ_ID_RELAY_DB_SAVE,
        );
        sm.process_relay_response(ChainId::PaseoAssetHub, &resp);
        assert_eq!(sm.store().load("custom-relay"), "relay-data");

        // Simulate para DB save — should use the entry's key
        let resp2 = format!(
            r#"{{"jsonrpc":"2.0","id":{},"result":"para-data"}}"#,
            REQ_ID_PARA_DB_SAVE,
        );
        sm.process_response(ChainId::PaseoAssetHub, &resp2);
        assert_eq!(sm.store().load("custom-para"), "para-data");
    }

    #[test]
    fn chain_specs_owned_returns_entry_specs() {
        use crate::chain::ConnectionBackend;
        use crate::registry::ChainRegistryEntry;
        let store = InMemoryStore::new();
        let mut sm = ChainStateMachine::new(store);
        sm.register_chain_entry(&ChainRegistryEntry {
            id: ChainId::PaseoAssetHub,
            genesis_hash: [0u8; 32],
            display_name: "Paseo Asset Hub".to_string(),
            endpoint: String::new(),
            backend: ConnectionBackend::Rpc,
            relay_db_key: "r".to_string(),
            para_db_key: "p".to_string(),
            chain_specs: Some(("relay-spec".to_string(), "para-spec".to_string())),
        });
        let specs = sm.chain_specs_owned(ChainId::PaseoAssetHub);
        assert_eq!(
            specs,
            Some(("relay-spec".to_string(), "para-spec".to_string()))
        );

        // Unregistered chain returns None
        assert!(sm.chain_specs_owned(ChainId::Ethereum).is_none());
    }

    #[test]
    fn register_chain_entry_backward_compat_with_register_chain() {
        // register_chain (enum path) and register_chain_entry (registry path)
        // should produce identical observable behavior when entry values match.
        use crate::chain::ConnectionBackend;
        use crate::registry::ChainRegistryEntry;

        let store1 = InMemoryStore::new();
        let mut sm1 = ChainStateMachine::new(store1);
        sm1.register_chain(ChainId::PaseoAssetHub);

        let store2 = InMemoryStore::new();
        let mut sm2 = ChainStateMachine::new(store2);
        sm2.register_chain_entry(&ChainRegistryEntry {
            id: ChainId::PaseoAssetHub,
            genesis_hash: [0u8; 32],
            display_name: ChainId::PaseoAssetHub.display_name().to_string(),
            endpoint: ChainId::PaseoAssetHub.endpoint().to_string(),
            backend: ConnectionBackend::Smoldot,
            relay_db_key: ChainId::PaseoAssetHub.relay_db_key().to_string(),
            para_db_key: ChainId::PaseoAssetHub.para_db_key(),
            chain_specs: ChainId::PaseoAssetHub
                .chain_specs()
                .map(|(r, p)| (r.to_string(), p.to_string())),
        });

        // Both should produce same status
        let s1 = sm1.status(ChainId::PaseoAssetHub);
        let s2 = sm2.status(ChainId::PaseoAssetHub);
        assert_eq!(s1.name, s2.name);
        assert!(matches!(s1.state, ChainState::Connecting));
        assert!(matches!(s2.state, ChainState::Connecting));

        // Both should save para DB to the same key
        let resp = format!(
            r#"{{"jsonrpc":"2.0","id":{},"result":"db-content"}}"#,
            REQ_ID_PARA_DB_SAVE,
        );
        sm1.process_response(ChainId::PaseoAssetHub, &resp);
        sm2.process_response(ChainId::PaseoAssetHub, &resp);
        assert_eq!(
            sm1.store().load(&ChainId::PaseoAssetHub.para_db_key()),
            sm2.store().load(&ChainId::PaseoAssetHub.para_db_key()),
        );
    }
}