Skip to main content

heika_node/
recent.rs

1//! 直近のブロックに入ったトランザクションの索引。ハッシュから、入ったブロックの高さと、ブロックの中で何番目かを引く。
2//!
3//! 送ったばかりのトランザクションは、期限(`maxTransactionLifetime`)のうちにブロックに入るか、二度と入らないかの
4//! どちらかなので、その長さの分だけ持てば、送金のあとの確かめに足りる。ディスクには何も書かず、起動したら DB の
5//! 直近のブロックを読んで作り直す。ライトの残し方でも、ブロックは期限より長く(2エポック)残っている。
6//! 先端が進んだら足し、枝を取り替えたら分かれ目より上を外す([`crate::delegated::Delegated`] と同じ流れ)。
7
8use std::collections::{BTreeMap, HashMap};
9use std::sync::{Arc, RwLock};
10
11use heika_block::Block;
12use heika_core::hash::Hash256;
13use heika_core::network::GenerationHashSeed;
14use heika_store_redb::Db;
15use heika_transaction::Transaction;
16
17use crate::driver::NodeError;
18
19/// 駆動役が書き、API の読み役が読む
20pub type SharedRecent = Arc<RwLock<RecentTransactions>>;
21
22pub struct RecentTransactions {
23    seed: GenerationHashSeed,
24    /// 持つ長さ(ミリ秒)。先端のブロックの時刻からこれより前のブロックは外す
25    lifetime: u64,
26    /// ハッシュから、高さとブロックの中の番号
27    by_hash: HashMap<Hash256, (u64, u32)>,
28    /// 高さごとの、ブロックの時刻と中のハッシュ
29    blocks: BTreeMap<u64, (u64, Vec<Hash256>)>,
30    /// 読み終えた高さ
31    through: u64,
32}
33
34impl RecentTransactions {
35    /// DB の先端 `tip` から遡って、`lifetime` の分のブロックを読む
36    pub fn open(
37        db: &Db,
38        seed: GenerationHashSeed,
39        lifetime: u64,
40        tip: u64,
41    ) -> Result<Self, NodeError> {
42        let mut recent = Self {
43            seed,
44            lifetime,
45            by_hash: HashMap::new(),
46            blocks: BTreeMap::new(),
47            through: tip,
48        };
49        let mut newest = None;
50        for height in (1..=tip).rev() {
51            let Some(block) = read_block(db, height)? else {
52                break;
53            };
54            let newest = *newest.get_or_insert(block.timestamp);
55            if block.timestamp + lifetime < newest {
56                break;
57            }
58            recent.insert(&block);
59        }
60        Ok(recent)
61    }
62
63    /// `hash` のトランザクションが入った高さと、ブロックの中の番号
64    pub fn find(&self, hash: &Hash256) -> Option<(u64, u32)> {
65        self.by_hash.get(hash).copied()
66    }
67
68    /// 枝を取り替えた。分かれ目 `common` より上は、新しい枝で読み直す
69    pub fn rewind(&mut self, common: u64) {
70        for (_, (_, hashes)) in self.blocks.split_off(&(common + 1)) {
71            for hash in hashes {
72                self.by_hash.remove(&hash);
73            }
74        }
75        self.through = self.through.min(common);
76    }
77
78    /// 先端が `tip` まで進んだ。まだ読んでいないブロックを足し、古くなったものを外す
79    pub fn advance(&mut self, db: &Db, tip: u64) -> Result<(), NodeError> {
80        for height in self.through + 1..=tip {
81            if let Some(block) = read_block(db, height)? {
82                self.insert(&block);
83            }
84        }
85        self.through = self.through.max(tip);
86        let Some(newest) = self.blocks.values().next_back().map(|(time, _)| *time) else {
87            return Ok(());
88        };
89        while let Some(entry) = self.blocks.first_entry() {
90            if entry.get().0 + self.lifetime >= newest {
91                break;
92            }
93            for hash in entry.remove().1 {
94                self.by_hash.remove(&hash);
95            }
96        }
97        Ok(())
98    }
99
100    fn insert(&mut self, block: &Block) {
101        // チェーンが認めたブロックなので、読めないトランザクションはない。読めなければ飛ばす
102        let hashes: Vec<Hash256> = block
103            .transactions()
104            .filter_map(|bytes| Transaction::from_bytes(bytes).ok())
105            .map(|transaction| transaction.hash(&self.seed))
106            .collect();
107        for (index, hash) in hashes.iter().enumerate() {
108            self.by_hash.insert(*hash, (block.height, index as u32));
109        }
110        self.blocks.insert(block.height, (block.timestamp, hashes));
111    }
112}
113
114fn read_block(db: &Db, height: u64) -> Result<Option<Block>, NodeError> {
115    let Some(bytes) = db.block(height)? else {
116        return Ok(None);
117    };
118    Block::from_bytes(&bytes)
119        .map(Some)
120        .map_err(|error| format!("高さ {height} のブロックが読めません: {error}").into())
121}