1use 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
22const MAX_PASSES: usize = 16;
24
25#[derive(Debug)]
27pub enum Incoming {
28 Transactions(Vec<Vec<u8>>),
30 Cosignatures(Vec<DetachedCosignature>),
32}
33
34impl Incoming {
35 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
67fn 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#[derive(Default)]
81pub struct Handled {
82 pub partial: Vec<u8>,
84 pub cosignatures: Vec<u8>,
86 pub completed: Vec<u8>,
88}
89
90pub 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#[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 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}