chaincraft 0.4.0

A high-performance Rust-based platform for blockchain education and prototyping
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
//! Blockchain protocol example with Memento-aware pipeline state.

use crate::{
    error::{ChaincraftError, Result},
    network::PeerId,
    shared::{MessageType, SharedMessage, SharedObjectId},
    shared_object::ApplicationObject,
    state_memento::{normalize_state_memento, StateMemento},
    storage::MemoryStorage,
    ChaincraftNode,
};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::any::Any;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlockRecord {
    pub height: u64,
    pub digest: String,
    pub previous_digest: String,
    pub miner: String,
    pub transactions: Vec<Value>,
    pub payload: Value,
}

#[derive(Debug, Clone)]
pub struct BlockchainObject {
    id: SharedObjectId,
    pub chain: Vec<BlockRecord>,
    pub balances: HashMap<String, i64>,
    pub mining_reward: i64,
    block_by_digest: HashMap<String, BlockRecord>,
    children_by_digest: HashMap<String, HashSet<String>>,
    tip_digests: HashSet<String>,
    state_by_digest: HashMap<String, HashMap<String, i64>>,
    seen_hashes: HashSet<String>,
}

impl BlockchainObject {
    pub fn new() -> Self {
        Self::with_reward(10)
    }

    pub fn with_reward(mining_reward: i64) -> Self {
        let genesis_digest = Self::compute_digest(&serde_json::json!({
            "height": 0u64,
            "previous_digest": "",
            "miner": "genesis",
            "transactions": [],
            "payload": "genesis"
        }));
        let genesis = BlockRecord {
            height: 0,
            digest: genesis_digest.clone(),
            previous_digest: String::new(),
            miner: "genesis".to_string(),
            transactions: vec![],
            payload: serde_json::json!("genesis"),
        };
        let mut block_by_digest = HashMap::new();
        block_by_digest.insert(genesis_digest.clone(), genesis.clone());
        let mut children_by_digest = HashMap::new();
        children_by_digest.insert(genesis_digest.clone(), HashSet::new());
        let mut tip_digests = HashSet::new();
        tip_digests.insert(genesis_digest.clone());
        let mut balances = HashMap::new();
        balances.insert("genesis".to_string(), 1000);
        let mut state_by_digest = HashMap::new();
        state_by_digest.insert(genesis_digest.clone(), balances.clone());

        Self {
            id: SharedObjectId::new(),
            chain: vec![genesis],
            balances,
            mining_reward,
            block_by_digest,
            children_by_digest,
            tip_digests,
            state_by_digest,
            seen_hashes: HashSet::new(),
        }
    }

    fn canonical_json(value: &Value) -> Value {
        match value {
            Value::Object(map) => {
                let mut keys: Vec<String> = map.keys().cloned().collect();
                keys.sort();
                let mut out = serde_json::Map::new();
                for key in keys {
                    if let Some(v) = map.get(&key) {
                        out.insert(key, Self::canonical_json(v));
                    }
                }
                Value::Object(out)
            },
            Value::Array(arr) => Value::Array(arr.iter().map(Self::canonical_json).collect()),
            _ => value.clone(),
        }
    }

    fn compute_digest(value: &Value) -> String {
        let canonical = Self::canonical_json(value);
        let payload = serde_json::to_string(&canonical).unwrap_or_else(|_| "null".to_string());
        let mut hasher = Sha256::new();
        hasher.update(payload.as_bytes());
        hex::encode(hasher.finalize())
    }

    pub fn latest_block(&self) -> &BlockRecord {
        self.chain
            .last()
            .expect("blockchain always has genesis block")
    }

    fn compute_next_state(
        &self,
        parent_state: &HashMap<String, i64>,
        block: &BlockRecord,
    ) -> Result<HashMap<String, i64>> {
        let mut next = parent_state.clone();
        *next.entry(block.miner.clone()).or_insert(0) += self.mining_reward;
        for tx in &block.transactions {
            let sender = tx
                .get("sender")
                .and_then(|v| v.as_str())
                .ok_or_else(|| ChaincraftError::validation("transaction missing sender"))?
                .to_string();
            let recipient = tx
                .get("recipient")
                .and_then(|v| v.as_str())
                .ok_or_else(|| ChaincraftError::validation("transaction missing recipient"))?
                .to_string();
            let amount = tx
                .get("amount")
                .and_then(|v| v.as_i64())
                .ok_or_else(|| ChaincraftError::validation("transaction missing amount"))?;
            let fee = tx
                .get("fee")
                .and_then(|v| v.as_i64())
                .ok_or_else(|| ChaincraftError::validation("transaction missing fee"))?;
            let sender_balance = *next.get(&sender).unwrap_or(&0);
            if sender_balance < amount + fee {
                return Err(ChaincraftError::validation(
                    "sender has insufficient balance for transaction",
                ));
            }
            next.insert(sender.clone(), sender_balance - amount - fee);
            *next.entry(recipient).or_insert(0) += amount;
            *next.entry(block.miner.clone()).or_insert(0) += fee;
        }
        Ok(next)
    }

    fn build_chain_to_tip(&self, tip_digest: &str) -> Vec<BlockRecord> {
        let mut reversed = vec![];
        let mut cursor = tip_digest.to_string();
        while let Some(block) = self.block_by_digest.get(&cursor) {
            reversed.push(block.clone());
            if block.height == 0 {
                break;
            }
            cursor = block.previous_digest.clone();
        }
        reversed.reverse();
        if reversed.first().map(|b| b.height) == Some(0) {
            reversed
        } else {
            vec![]
        }
    }

    fn is_better_tip(&self, candidate_digest: &str, current_digest: &str) -> bool {
        let Some(candidate) = self.block_by_digest.get(candidate_digest) else {
            return false;
        };
        let Some(current) = self.block_by_digest.get(current_digest) else {
            return true;
        };
        if candidate.height > current.height {
            return true;
        }
        if candidate.height < current.height {
            return false;
        }
        candidate_digest < current_digest
    }

    fn collect_transactions(&self, digests: &[String]) -> Vec<Value> {
        let mut txs = vec![];
        for digest in digests {
            if let Some(block) = self.block_by_digest.get(digest) {
                for tx in &block.transactions {
                    txs.push(tx.clone());
                }
            }
        }
        txs
    }

    fn build_memento(
        &self,
        reorg: bool,
        reorg_from_height: Option<u64>,
        reverted_txs: Vec<Value>,
        applied_tx_ids: Vec<String>,
    ) -> StateMemento {
        let latest = self.latest_block().digest.clone();
        let mut frontier = self
            .chain
            .iter()
            .rev()
            .take(8)
            .map(|b| b.digest.clone())
            .collect::<Vec<_>>();
        let canonical_set: HashSet<String> = frontier.iter().cloned().collect();
        let mut extras = self
            .tip_digests
            .iter()
            .filter(|d| !canonical_set.contains(*d))
            .cloned()
            .collect::<Vec<_>>();
        extras.sort();
        frontier.extend(extras);

        let mut memento = normalize_state_memento(&latest, Some(frontier));
        memento.revision = self.chain.len() as u64;
        let mut metadata = BTreeMap::new();
        metadata.insert("reorg".to_string(), Value::Bool(reorg));
        if let Some(height) = reorg_from_height {
            metadata.insert(
                "reorg_from_height".to_string(),
                Value::Number(serde_json::Number::from(height)),
            );
        }
        metadata.insert("reverted_txs".to_string(), Value::Array(reverted_txs));
        metadata.insert(
            "applied_tx_ids".to_string(),
            Value::Array(applied_tx_ids.into_iter().map(Value::String).collect()),
        );
        metadata.insert(
            "chain_length".to_string(),
            Value::Number(serde_json::Number::from(self.chain.len())),
        );
        memento.metadata = metadata;
        memento
    }
}

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

#[async_trait]
impl ApplicationObject for BlockchainObject {
    fn id(&self) -> &SharedObjectId {
        &self.id
    }

    fn type_name(&self) -> &'static str {
        "BlockchainObject"
    }

    async fn is_valid(&self, message: &SharedMessage) -> Result<bool> {
        let data = &message.data;
        let Some(message_type) = data.get("message_type").and_then(|v| v.as_str()) else {
            return Ok(false);
        };
        match message_type {
            "NEW_TX" => Ok(data.get("tx").and_then(|v| v.get("tx_id")).is_some()),
            "NEW_BLOCK" => {
                let Some(height) = data.get("height").and_then(|v| v.as_u64()) else {
                    return Ok(false);
                };
                let Some(previous_digest) = data.get("previous_digest").and_then(|v| v.as_str())
                else {
                    return Ok(false);
                };
                let Some(miner) = data.get("miner").and_then(|v| v.as_str()) else {
                    return Ok(false);
                };
                if miner.is_empty() {
                    return Ok(false);
                }
                let Some(transactions) = data.get("transactions").and_then(|v| v.as_array()) else {
                    return Ok(false);
                };
                let Some(payload) = data.get("payload") else {
                    return Ok(false);
                };
                let computed = Self::compute_digest(&serde_json::json!({
                    "height": height,
                    "previous_digest": previous_digest,
                    "miner": miner,
                    "transactions": transactions,
                    "payload": payload
                }));
                let provided = data
                    .get("digest")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default();
                if computed != provided {
                    return Ok(false);
                }

                let Some(parent) = self.block_by_digest.get(previous_digest) else {
                    return Ok(false);
                };
                if height != parent.height + 1 {
                    return Ok(false);
                }
                let Some(parent_state) = self.state_by_digest.get(previous_digest) else {
                    return Ok(false);
                };
                let candidate = BlockRecord {
                    height,
                    digest: provided.to_string(),
                    previous_digest: previous_digest.to_string(),
                    miner: miner.to_string(),
                    transactions: transactions.clone(),
                    payload: payload.clone(),
                };
                Ok(self.compute_next_state(parent_state, &candidate).is_ok())
            },
            _ => Ok(false),
        }
    }

    async fn add_message(
        &mut self,
        message: SharedMessage,
        _frontier_state: Option<StateMemento>,
    ) -> Result<Option<StateMemento>> {
        if self.seen_hashes.contains(&message.hash) {
            return Ok(None);
        }
        self.seen_hashes.insert(message.hash.clone());

        let data = message.data;
        let message_type = data
            .get("message_type")
            .and_then(|v| v.as_str())
            .ok_or_else(|| ChaincraftError::validation("missing message_type"))?;

        match message_type {
            "NEW_TX" => Ok(Some(self.build_memento(false, None, vec![], vec![]))),
            "NEW_BLOCK" => {
                let height = data
                    .get("height")
                    .and_then(|v| v.as_u64())
                    .ok_or_else(|| ChaincraftError::validation("missing block height"))?;
                let previous_digest = data
                    .get("previous_digest")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| ChaincraftError::validation("missing previous_digest"))?
                    .to_string();
                let payload = data
                    .get("payload")
                    .cloned()
                    .ok_or_else(|| ChaincraftError::validation("missing payload"))?;
                let miner = data
                    .get("miner")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| ChaincraftError::validation("missing miner"))?
                    .to_string();
                let transactions = data
                    .get("transactions")
                    .and_then(|v| v.as_array())
                    .ok_or_else(|| ChaincraftError::validation("missing transactions"))?
                    .clone();
                let digest = data
                    .get("digest")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| ChaincraftError::validation("missing digest"))?
                    .to_string();

                let block = BlockRecord {
                    height,
                    digest: digest.clone(),
                    previous_digest: previous_digest.clone(),
                    miner,
                    transactions: transactions.clone(),
                    payload,
                };
                if self.block_by_digest.contains_key(&digest) {
                    return Ok(Some(self.build_memento(false, None, vec![], vec![])));
                }
                let parent_state = self
                    .state_by_digest
                    .get(&previous_digest)
                    .ok_or_else(|| ChaincraftError::validation("missing parent state"))?
                    .clone();
                let next_state = self.compute_next_state(&parent_state, &block)?;

                let old_chain_hashes = self
                    .chain
                    .iter()
                    .map(|b| b.digest.clone())
                    .collect::<Vec<_>>();
                let old_tip = self.latest_block().digest.clone();

                self.block_by_digest.insert(digest.clone(), block.clone());
                self.children_by_digest
                    .entry(previous_digest.clone())
                    .or_default()
                    .insert(digest.clone());
                self.children_by_digest.entry(digest.clone()).or_default();
                self.state_by_digest.insert(digest.clone(), next_state);
                self.tip_digests.insert(digest.clone());
                self.tip_digests.remove(&previous_digest);

                let mut reorg = false;
                let mut reorg_from_height = None;
                if self.is_better_tip(&digest, &old_tip) {
                    let new_chain = self.build_chain_to_tip(&digest);
                    if !new_chain.is_empty() {
                        self.chain = new_chain;
                        self.balances = self
                            .state_by_digest
                            .get(&digest)
                            .cloned()
                            .unwrap_or_default();
                    }
                }

                let new_chain_hashes = self
                    .chain
                    .iter()
                    .map(|b| b.digest.clone())
                    .collect::<Vec<_>>();
                let old_set: HashSet<String> = old_chain_hashes.iter().cloned().collect();
                let new_set: HashSet<String> = new_chain_hashes.iter().cloned().collect();
                let removed = old_chain_hashes
                    .into_iter()
                    .filter(|h| !new_set.contains(h))
                    .collect::<Vec<_>>();
                let added = new_chain_hashes
                    .iter()
                    .filter(|h| !old_set.contains(*h))
                    .cloned()
                    .collect::<Vec<_>>();
                if !removed.is_empty() {
                    reorg = true;
                    let min_height = removed
                        .iter()
                        .filter_map(|h| self.block_by_digest.get(h).map(|b| b.height))
                        .min();
                    reorg_from_height = min_height;
                }
                let reverted_txs = self.collect_transactions(&removed);
                let applied_tx_ids = self
                    .collect_transactions(&added)
                    .iter()
                    .filter_map(|tx| tx.get("tx_id").and_then(|v| v.as_str()))
                    .map(|s| s.to_string())
                    .collect::<Vec<_>>();

                Ok(Some(self.build_memento(reorg, reorg_from_height, reverted_txs, applied_tx_ids)))
            },
            _ => Ok(None),
        }
    }

    fn is_merkleized(&self) -> bool {
        true
    }

    async fn get_latest_digest(&self) -> Result<String> {
        Ok(self.latest_block().digest.clone())
    }

    async fn has_digest(&self, digest: &str) -> Result<bool> {
        Ok(self.block_by_digest.contains_key(digest))
    }

    async fn is_valid_digest(&self, digest: &str) -> Result<bool> {
        self.has_digest(digest).await
    }

    async fn add_digest(&mut self, _digest: String) -> Result<bool> {
        Ok(false)
    }

    async fn gossip_messages(&self, _digest: Option<&str>) -> Result<Vec<SharedMessage>> {
        Ok(vec![])
    }

    async fn get_messages_since_digest(&self, _digest: &str) -> Result<Vec<SharedMessage>> {
        Ok(vec![])
    }

    fn get_state_digests(&self) -> Vec<String> {
        let mut canonical = self
            .chain
            .iter()
            .rev()
            .take(8)
            .map(|b| b.digest.clone())
            .collect::<Vec<_>>();
        canonical.reverse();
        let canonical_set: HashSet<String> = canonical.iter().cloned().collect();
        let mut extras = self
            .tip_digests
            .iter()
            .filter(|d| !canonical_set.contains(*d))
            .cloned()
            .collect::<Vec<_>>();
        extras.sort();
        canonical.extend(extras);
        canonical
    }

    async fn emit_state_memento(&self) -> Result<StateMemento> {
        Ok(self.build_memento(false, None, vec![], vec![]))
    }

    async fn get_state(&self) -> Result<Value> {
        Ok(serde_json::json!({
            "chain_length": self.chain.len(),
            "latest_digest": self.latest_block().digest,
            "latest_height": self.latest_block().height,
            "balances": self.balances
        }))
    }

    async fn reset(&mut self) -> Result<()> {
        let genesis = self.chain.first().cloned();
        self.chain.clear();
        if let Some(genesis) = genesis {
            self.chain.push(genesis.clone());
            self.block_by_digest.clear();
            self.block_by_digest
                .insert(genesis.digest.clone(), genesis.clone());
            self.children_by_digest.clear();
            self.children_by_digest
                .insert(genesis.digest.clone(), HashSet::new());
            self.tip_digests.clear();
            self.tip_digests.insert(genesis.digest.clone());
            self.state_by_digest.clear();
            let mut balances = HashMap::new();
            balances.insert("genesis".to_string(), 1000);
            self.balances = balances.clone();
            self.state_by_digest.insert(genesis.digest, balances);
        }
        self.seen_hashes.clear();
        Ok(())
    }

    fn clone_box(&self) -> Box<dyn ApplicationObject> {
        Box::new(self.clone())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

#[derive(Debug, Clone)]
pub struct MempoolObject {
    id: SharedObjectId,
    pub transactions: BTreeMap<String, Value>,
}

impl MempoolObject {
    pub fn new() -> Self {
        Self {
            id: SharedObjectId::new(),
            transactions: BTreeMap::new(),
        }
    }
}

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

#[async_trait]
impl ApplicationObject for MempoolObject {
    fn id(&self) -> &SharedObjectId {
        &self.id
    }

    fn type_name(&self) -> &'static str {
        "MempoolObject"
    }

    async fn is_valid(&self, message: &SharedMessage) -> Result<bool> {
        let msg_type = message
            .data
            .get("message_type")
            .and_then(|v| v.as_str())
            .unwrap_or_default();
        Ok(matches!(msg_type, "NEW_TX" | "NEW_BLOCK"))
    }

    async fn add_message(
        &mut self,
        message: SharedMessage,
        frontier_state: Option<StateMemento>,
    ) -> Result<Option<StateMemento>> {
        let msg_type = message
            .data
            .get("message_type")
            .and_then(|v| v.as_str())
            .unwrap_or_default();
        match msg_type {
            "NEW_TX" => {
                if let Some(tx) = message.data.get("tx").cloned() {
                    if let Some(tx_id) = tx.get("tx_id").and_then(|v| v.as_str()) {
                        self.transactions.insert(tx_id.to_string(), tx);
                    }
                }
            },
            "NEW_BLOCK" => {
                let metadata = frontier_state.map(|m| m.metadata).unwrap_or_default();
                let reverted = metadata
                    .get("reverted_txs")
                    .and_then(|v| v.as_array())
                    .cloned()
                    .unwrap_or_default();
                for tx in reverted {
                    if let Some(tx_id) = tx.get("tx_id").and_then(|v| v.as_str()) {
                        self.transactions.insert(tx_id.to_string(), tx);
                    }
                }
                let applied = metadata
                    .get("applied_tx_ids")
                    .and_then(|v| v.as_array())
                    .cloned()
                    .unwrap_or_default();
                if !applied.is_empty() {
                    for tx_id in applied {
                        if let Some(tx_id) = tx_id.as_str() {
                            self.transactions.remove(tx_id);
                        }
                    }
                } else if let Some(block_txs) = message
                    .data
                    .get("transactions")
                    .and_then(|v| v.as_array())
                    .cloned()
                {
                    for tx in block_txs {
                        if let Some(tx_id) = tx.get("tx_id").and_then(|v| v.as_str()) {
                            self.transactions.remove(tx_id);
                        }
                    }
                }
            },
            _ => {},
        }
        Ok(Some(self.emit_state_memento().await?))
    }

    fn is_merkleized(&self) -> bool {
        false
    }

    async fn get_latest_digest(&self) -> Result<String> {
        Ok(self.transactions.len().to_string())
    }

    async fn has_digest(&self, _digest: &str) -> Result<bool> {
        Ok(false)
    }

    async fn is_valid_digest(&self, _digest: &str) -> Result<bool> {
        Ok(false)
    }

    async fn add_digest(&mut self, _digest: String) -> Result<bool> {
        Ok(false)
    }

    async fn gossip_messages(&self, _digest: Option<&str>) -> Result<Vec<SharedMessage>> {
        Ok(vec![])
    }

    async fn get_messages_since_digest(&self, _digest: &str) -> Result<Vec<SharedMessage>> {
        Ok(vec![])
    }

    async fn get_state(&self) -> Result<Value> {
        Ok(serde_json::json!({
            "mempool_size": self.transactions.len()
        }))
    }

    async fn reset(&mut self) -> Result<()> {
        self.transactions.clear();
        Ok(())
    }

    fn clone_box(&self) -> Box<dyn ApplicationObject> {
        Box::new(self.clone())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

/// Typed node wrapper for Blockchain examples.
pub struct BlockchainNode {
    node: ChaincraftNode,
    ledger_object_id: SharedObjectId,
    mempool_object_id: SharedObjectId,
}

impl BlockchainNode {
    pub async fn new(port: u16) -> Result<Self> {
        let mut node = ChaincraftNode::new(PeerId::new(), Arc::new(MemoryStorage::new()));
        node.set_port(port);
        let ledger_object_id = node
            .add_shared_object(Box::new(BlockchainObject::new()))
            .await?;
        let mempool_object_id = node
            .add_shared_object(Box::new(MempoolObject::new()))
            .await?;
        Ok(Self {
            node,
            ledger_object_id,
            mempool_object_id,
        })
    }

    pub async fn start(&mut self) -> Result<()> {
        self.node.start().await
    }

    pub async fn close(&mut self) -> Result<()> {
        self.node.close().await
    }

    pub async fn connect_to_peer(&mut self, addr: &str) -> Result<()> {
        self.node.connect_to_peer(addr).await
    }

    pub fn host(&self) -> &str {
        self.node.host()
    }

    pub fn port(&self) -> u16 {
        self.node.port()
    }

    pub async fn publish(&mut self, data: Value) -> Result<String> {
        self.node.create_shared_message_with_data(data).await
    }

    pub async fn chain_state(&self) -> Result<Value> {
        let registry = self.node.app_objects.read().await;
        let Some(obj) = registry.get(&self.ledger_object_id) else {
            return Err(ChaincraftError::validation("BlockchainObject not found"));
        };
        obj.get_state().await
    }

    pub async fn mempool_state(&self) -> Result<Value> {
        let registry = self.node.app_objects.read().await;
        let Some(obj) = registry.get(&self.mempool_object_id) else {
            return Err(ChaincraftError::validation("MempoolObject not found"));
        };
        obj.get_state().await
    }
}

pub mod helpers {
    use super::*;

    pub fn create_tx_message(tx: Value) -> Value {
        serde_json::json!({
            "message_type": "NEW_TX",
            "tx": tx
        })
    }

    pub fn create_block_message(height: u64, previous_digest: String, payload: Value) -> Value {
        create_block_message_with_transactions(
            height,
            previous_digest,
            "miner".to_string(),
            vec![],
            payload,
        )
    }

    pub fn create_block_message_with_transactions(
        height: u64,
        previous_digest: String,
        miner: String,
        transactions: Vec<Value>,
        payload: Value,
    ) -> Value {
        let digest = BlockchainObject::compute_digest(&serde_json::json!({
            "height": height,
            "previous_digest": previous_digest,
            "miner": miner,
            "transactions": transactions,
            "payload": payload
        }));
        serde_json::json!({
            "message_type": "NEW_BLOCK",
            "height": height,
            "previous_digest": previous_digest,
            "miner": miner,
            "transactions": transactions,
            "payload": payload,
            "digest": digest
        })
    }

    pub fn create_simple_transfer_tx(
        tx_id: &str,
        sender: &str,
        recipient: &str,
        amount: i64,
        fee: i64,
    ) -> Value {
        serde_json::json!({
            "tx_id": tx_id,
            "sender": sender,
            "recipient": recipient,
            "amount": amount,
            "fee": fee,
        })
    }
}