Skip to main content

heika_node/
partials.rs

1//! 連署を待つアグリゲートボンデッドを、駆動役で扱う。置き場([`PartialPool`](heika_mempool::partial::PartialPool))は状態を持たないので、受け付けたら
2//! 中核([`Chain::check_partial`])に今の状態で聞き、結果で分ける。
3//!
4//! - ハッシュロックが確定して使えるようになっていない: 置き場から外す(catapult と同じく、受け付けない)
5//! - 外側の署名者が連署できない人: 置き場から外す
6//! - 連署できない人の連署がある: その連署だけを外して見直す(マルチシグが変わって古くなった連署など)
7//! - 連署が足りない: 待つ。初めて受け付けたか、連署が増えたら、ほかのピアにも流す
8//! - 揃った: 連署を付けて未承認の置き場に移し、ほかのピアに未承認のトランザクションとして流す
9//!
10//! 入ってくる道は、ピアからの押し付け、ピアから取ってきたもの、REST の3つで、どれも [`Incoming`] にして渡す。
11
12use heika_chain::chain::Chain;
13use heika_core::hash::Hash256;
14use heika_mempool::SharedMempool;
15use heika_mempool::partial::SharedPartialPool;
16use heika_peer_protocol::PulledPartial;
17use heika_state_transition::executor::PartialCheck;
18use heika_transaction::{Body, Cosignature, DetachedCosignature, Transaction};
19
20use crate::store::CachedStore;
21
22/// 連署を外して見直す回数の上限。連署はアグリゲート1つに 15 個まで(`maxCosignaturesPerAggregate`)
23const MAX_PASSES: usize = 16;
24
25/// 入ってきた、連署を待つもの
26#[derive(Debug)]
27pub enum Incoming {
28    /// アグリゲートボンデッド(連署が付いていてもよい)
29    Transactions(Vec<Vec<u8>>),
30    /// 切り離した連署
31    Cosignatures(Vec<DetachedCosignature>),
32}
33
34impl Incoming {
35    /// ピアから取ってきたものにする。知らなかったものは連署を付けたトランザクションに、知っていたものは
36    /// 切り離した連署にする
37    pub fn from_pulled(pulled: Vec<PulledPartial>) -> Vec<Self> {
38        let mut transactions = Vec::new();
39        let mut cosignatures = Vec::new();
40        for info in pulled {
41            let parsed: Vec<Cosignature> = info
42                .cosignatures
43                .iter()
44                .filter_map(|bytes| Cosignature::from_bytes(bytes).ok())
45                .collect();
46            match info.transaction {
47                Ok(bytes) => {
48                    if let Some(stitched) = stitch(&bytes, &parsed) {
49                        transactions.push(stitched);
50                    }
51                }
52                Err(parent_hash) => {
53                    cosignatures.extend(parsed.into_iter().map(|cosignature| DetachedCosignature {
54                        cosignature,
55                        parent_hash,
56                    }))
57                }
58            }
59        }
60        vec![
61            Self::Transactions(transactions),
62            Self::Cosignatures(cosignatures),
63        ]
64    }
65}
66
67/// 連署を除いたトランザクション `bytes` に、連署を付ける
68fn stitch(bytes: &[u8], cosignatures: &[Cosignature]) -> Option<Vec<u8>> {
69    let mut transaction = Transaction::from_bytes(bytes).ok()?;
70    let Body::AggregateBonded(aggregate) = &mut transaction.body else {
71        return None;
72    };
73    for cosignature in cosignatures {
74        aggregate.add_cosignature(*cosignature);
75    }
76    Some(transaction.to_bytes())
77}
78
79/// 扱った結果。駆動役が、ほかのピアに流す
80#[derive(Default)]
81pub struct Handled {
82    /// 連署を待つものとして流すもの(`Push_Partial_Transactions` の本体)
83    pub partial: Vec<u8>,
84    /// 流す連署(`Push_Detached_Cosignatures` の本体)
85    pub cosignatures: Vec<u8>,
86    /// 揃って未承認の置き場に移したもの(`Push_Transactions` の本体)
87    pub completed: Vec<u8>,
88}
89
90/// 入ってきたものを、今(Nemesis からのミリ秒 `now`)、次のブロックの高さ `height` のつもりで扱う
91pub fn handle(
92    chain: &mut Chain<'_, CachedStore>,
93    pool: &SharedPartialPool,
94    mempool: &SharedMempool,
95    incoming: Incoming,
96    now: u64,
97    height: u64,
98) -> Handled {
99    let mut handled = Handled::default();
100    match incoming {
101        Incoming::Transactions(transactions) => {
102            for bytes in transactions {
103                let added = match pool.lock().add(&bytes, now, height) {
104                    Ok(added) => added,
105                    Err(error) => {
106                        eprintln!("連署を待つトランザクションを受け付けませんでした: {error}");
107                        continue;
108                    }
109                };
110                if added.new {
111                    println!("連署を待つトランザクション {} を受け付けました", added.hash);
112                }
113                let changed = added.new || !added.cosignatures.is_empty();
114                settle(
115                    chain,
116                    pool,
117                    mempool,
118                    &added.hash,
119                    changed,
120                    now,
121                    height,
122                    &mut handled,
123                );
124            }
125        }
126        Incoming::Cosignatures(cosignatures) => {
127            for detached in cosignatures {
128                if pool.lock().add_cosignature(&detached).is_err() {
129                    continue;
130                }
131                handled.cosignatures.extend_from_slice(&detached.to_bytes());
132                settle(
133                    chain,
134                    pool,
135                    mempool,
136                    &detached.parent_hash,
137                    false,
138                    now,
139                    height,
140                    &mut handled,
141                );
142            }
143        }
144    }
145    handled
146}
147
148/// 置き場の `hash` を、今の状態で確かめて分ける。`changed` なら、待つときにほかのピアに流す
149#[allow(clippy::too_many_arguments)]
150fn settle(
151    chain: &mut Chain<'_, CachedStore>,
152    pool: &SharedPartialPool,
153    mempool: &SharedMempool,
154    hash: &Hash256,
155    changed: bool,
156    now: u64,
157    height: u64,
158    handled: &mut Handled,
159) {
160    // 連署を外したら見直すので、連署の数だけ回れば足りる
161    for _ in 0..MAX_PASSES {
162        let Some(stitched) = pool.lock().stitched(hash) else {
163            return;
164        };
165        let Ok(transaction) = Transaction::from_bytes(&stitched) else {
166            pool.lock().remove(hash);
167            return;
168        };
169        let check = match chain.check_partial(&transaction) {
170            Ok(check) => check,
171            Err(error) => {
172                eprintln!("連署を待つトランザクション {hash} を確かめられません: {error}");
173                return;
174            }
175        };
176        match check {
177            None => {
178                pool.lock().remove(hash);
179                eprintln!(
180                    "連署を待つトランザクション {hash} を外しました: ハッシュロックが確定していないか、もう使えません"
181                );
182                return;
183            }
184            Some(PartialCheck::Ineligible(keys)) => {
185                if keys.contains(&transaction.signer_public_key) {
186                    pool.lock().remove(hash);
187                    eprintln!(
188                        "連署を待つトランザクション {hash} を外しました: 外側の署名者が連署できる人ではありません"
189                    );
190                    return;
191                }
192                let mut pool = pool.lock();
193                for key in &keys {
194                    pool.remove_cosignature(hash, key);
195                }
196            }
197            Some(PartialCheck::Missing) => {
198                if changed {
199                    handled.partial.extend_from_slice(&stitched);
200                }
201                return;
202            }
203            Some(PartialCheck::Complete) => {
204                pool.lock().remove(hash);
205                match mempool.lock().add_completed(stitched.clone(), now, height) {
206                    Ok(_) => {
207                        println!(
208                            "連署を待つトランザクション {hash} の連署が揃ったので、未承認のトランザクションにしました"
209                        );
210                        handled.completed.extend_from_slice(&stitched);
211                    }
212                    Err(error) => eprintln!(
213                        "連署が揃ったトランザクション {hash} を、未承認の置き場が受け付けませんでした: {error}"
214                    ),
215                }
216                return;
217            }
218        }
219    }
220}