1use std::collections::{BTreeMap, BTreeSet, HashMap};
11use std::fmt;
12use std::sync::{Mutex, MutexGuard};
13
14use heika_chain::verify::{VerifyError, verify_transaction};
15use heika_core::hash::Hash256;
16use heika_core::key::PublicKey;
17use heika_core::network::NetworkParameters;
18use heika_packet::partial::{COSIGNATURE_SIZE, CosignedInfo, PartialInfo, ShortHashPair};
19use heika_packet::short_hash;
20use heika_transaction::{Body, Cosignature, DetachedCosignature, Transaction};
21use sha3::{Digest, Sha3_256};
22
23#[derive(Clone, Debug)]
25pub struct PartialConfig {
26 pub max_bytes: usize,
28 pub max_response_bytes: usize,
30 pub max_lifetime: u64,
32}
33
34impl Default for PartialConfig {
35 fn default() -> Self {
37 Self {
38 max_bytes: 60 * 1024 * 1024,
39 max_response_bytes: 20 * 1024 * 1024,
40 max_lifetime: 48 * 60 * 60 * 1000,
41 }
42 }
43}
44
45#[derive(Debug)]
47pub enum PartialRejected {
48 Malformed(String),
50 NotBonded,
52 Expired,
54 TooFarAhead,
56 Invalid(VerifyError),
58 Full,
60}
61
62impl fmt::Display for PartialRejected {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 match self {
65 Self::Malformed(error) => write!(f, "トランザクションとして読めません: {error}"),
66 Self::NotBonded => write!(f, "アグリゲートボンデッドではありません"),
67 Self::Expired => write!(f, "期限が過ぎています"),
68 Self::TooFarAhead => write!(f, "期限が先すぎます"),
69 Self::Invalid(error) => write!(f, "確かめが通りません: {error}"),
70 Self::Full => write!(f, "いっぱいです"),
71 }
72 }
73}
74
75#[derive(Clone, Copy, PartialEq, Eq, Debug)]
77pub enum CosignRejected {
78 UnknownParent,
80 InvalidSignature,
82 Redundant,
84}
85
86impl fmt::Display for CosignRejected {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 match self {
89 Self::UnknownParent => write!(f, "連署したアグリゲートを持っていません"),
90 Self::InvalidSignature => write!(f, "連署の署名が正しくありません"),
91 Self::Redundant => write!(f, "もう連署しています"),
92 }
93 }
94}
95
96#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct Added {
99 pub hash: Hash256,
100 pub new: bool,
102 pub cosignatures: Vec<Cosignature>,
104}
105
106struct Entry {
107 transaction: Vec<u8>,
109 signer: PublicKey,
110 deadline: u64,
111 cosignatures: BTreeMap<[u8; 32], [u8; COSIGNATURE_SIZE]>,
113}
114
115impl Entry {
116 fn cosignatures_hash(&self) -> Hash256 {
118 let mut hasher = Sha3_256::new();
119 for bytes in self.cosignatures.values() {
120 hasher.update(bytes);
121 }
122 Hash256(hasher.finalize().into())
123 }
124}
125
126pub struct PartialPool {
127 parameters: &'static NetworkParameters,
128 config: PartialConfig,
129 entries: HashMap<Hash256, Entry>,
130 by_deadline: BTreeSet<(u64, [u8; 32])>,
132 bytes: usize,
133}
134
135impl PartialPool {
136 pub fn new(parameters: &'static NetworkParameters, config: PartialConfig) -> Self {
137 Self {
138 parameters,
139 config,
140 entries: HashMap::new(),
141 by_deadline: BTreeSet::new(),
142 bytes: 0,
143 }
144 }
145
146 pub fn len(&self) -> usize {
147 self.entries.len()
148 }
149
150 pub fn is_empty(&self) -> bool {
151 self.entries.is_empty()
152 }
153
154 pub fn contains(&self, hash: &Hash256) -> bool {
155 self.entries.contains_key(hash)
156 }
157
158 pub fn add(&mut self, bytes: &[u8], now: u64, height: u64) -> Result<Added, PartialRejected> {
161 let mut transaction = Transaction::from_bytes(bytes)
162 .map_err(|error| PartialRejected::Malformed(error.to_string()))?;
163 if !matches!(transaction.body, Body::AggregateBonded(_)) {
164 return Err(PartialRejected::NotBonded);
165 }
166 let hash = transaction.hash(&self.parameters.generation_hash_seed);
167 let cosignatures = transaction.take_cosignatures();
168 let new = !self.entries.contains_key(&hash);
169 if new {
170 if transaction.deadline < now {
171 return Err(PartialRejected::Expired);
172 }
173 if transaction.deadline > now.saturating_add(self.config.max_lifetime) {
174 return Err(PartialRejected::TooFarAhead);
175 }
176 let stripped = transaction.to_bytes();
177 if self.bytes + stripped.len() > self.config.max_bytes {
178 return Err(PartialRejected::Full);
179 }
180 verify_transaction(self.parameters, height, 0, &stripped)
181 .map_err(PartialRejected::Invalid)?;
182 self.bytes += stripped.len();
183 self.by_deadline.insert((transaction.deadline, hash.0));
184 self.entries.insert(
185 hash,
186 Entry {
187 transaction: stripped,
188 signer: transaction.signer_public_key,
189 deadline: transaction.deadline,
190 cosignatures: BTreeMap::new(),
191 },
192 );
193 }
194 let cosignatures = cosignatures
195 .into_iter()
196 .filter(|cosignature| {
197 let detached = DetachedCosignature {
198 cosignature: *cosignature,
199 parent_hash: hash,
200 };
201 self.add_cosignature(&detached).is_ok()
202 })
203 .collect();
204 Ok(Added {
205 hash,
206 new,
207 cosignatures,
208 })
209 }
210
211 pub fn add_cosignature(
213 &mut self,
214 detached: &DetachedCosignature,
215 ) -> Result<(), CosignRejected> {
216 let entry = self
217 .entries
218 .get_mut(&detached.parent_hash)
219 .ok_or(CosignRejected::UnknownParent)?;
220 let signer = detached.cosignature.signer_public_key;
221 if signer == entry.signer || entry.cosignatures.contains_key(&signer.0) {
222 return Err(CosignRejected::Redundant);
223 }
224 if !detached.verify() {
225 return Err(CosignRejected::InvalidSignature);
226 }
227 entry
228 .cosignatures
229 .insert(signer.0, detached.cosignature.to_bytes());
230 Ok(())
231 }
232
233 pub fn remove_cosignature(&mut self, hash: &Hash256, signer: &PublicKey) -> bool {
235 self.entries
236 .get_mut(hash)
237 .is_some_and(|entry| entry.cosignatures.remove(&signer.0).is_some())
238 }
239
240 pub fn hashes(&self) -> Vec<Hash256> {
242 self.by_deadline
243 .iter()
244 .map(|(_, hash)| Hash256(*hash))
245 .collect()
246 }
247
248 pub fn deadline(&self, hash: &Hash256) -> Option<u64> {
250 self.entries.get(hash).map(|entry| entry.deadline)
251 }
252
253 pub fn transaction(&self, hash: &Hash256) -> Option<&[u8]> {
255 self.entries
256 .get(hash)
257 .map(|entry| entry.transaction.as_slice())
258 }
259
260 pub fn cosignatures(&self, hash: &Hash256) -> Vec<Cosignature> {
262 self.entries.get(hash).map_or_else(Vec::new, |entry| {
263 entry
264 .cosignatures
265 .values()
266 .filter_map(|bytes| Cosignature::from_bytes(bytes).ok())
267 .collect()
268 })
269 }
270
271 pub fn stitched(&self, hash: &Hash256) -> Option<Vec<u8>> {
273 let mut transaction = Transaction::from_bytes(self.transaction(hash)?).ok()?;
274 let Body::AggregateBonded(aggregate) = &mut transaction.body else {
275 return None;
276 };
277 for cosignature in self.cosignatures(hash) {
278 aggregate.add_cosignature(cosignature);
279 }
280 Some(transaction.to_bytes())
281 }
282
283 pub fn remove(&mut self, hash: &Hash256) -> bool {
285 let Some(entry) = self.entries.remove(hash) else {
286 return false;
287 };
288 self.bytes -= entry.transaction.len();
289 self.by_deadline.remove(&(entry.deadline, hash.0));
290 true
291 }
292
293 pub fn prune(&mut self, now: u64) -> Vec<Hash256> {
295 let expired: Vec<Hash256> = self
296 .by_deadline
297 .iter()
298 .take_while(|(deadline, _)| *deadline < now)
299 .map(|(_, hash)| Hash256(*hash))
300 .collect();
301 for hash in &expired {
302 self.remove(hash);
303 }
304 expired
305 }
306
307 pub fn short_hash_pairs(&self) -> Vec<ShortHashPair> {
309 self.entries
310 .iter()
311 .map(|(hash, entry)| ShortHashPair {
312 transaction: short_hash(hash),
313 cosignatures: short_hash(&entry.cosignatures_hash()),
314 })
315 .collect()
316 }
317
318 pub fn unknown_to(
322 &self,
323 min_deadline: u64,
324 known: &HashMap<u32, u32>,
325 ) -> Vec<CosignedInfo<'_>> {
326 let mut infos = Vec::new();
327 let mut total = 0;
328 for (deadline, hash) in self.by_deadline.range((min_deadline, [0; 32])..) {
329 let hash = Hash256(*hash);
330 let entry = &self.entries[&hash];
331 let cosignatures_hash = short_hash(&entry.cosignatures_hash());
332 let info = match known.get(&short_hash(&hash)) {
333 Some(&known) if known == cosignatures_hash => continue,
334 Some(_) => PartialInfo::Hash(hash),
335 None => PartialInfo::Transaction(&entry.transaction),
336 };
337 let size = match info {
338 PartialInfo::Transaction(bytes) => bytes.len(),
339 PartialInfo::Hash(_) => 32,
340 } + entry.cosignatures.len() * COSIGNATURE_SIZE;
341 total += size;
342 if total > self.config.max_response_bytes {
343 break;
344 }
345 debug_assert!(*deadline >= min_deadline);
346 infos.push(CosignedInfo {
347 info,
348 cosignatures: entry.cosignatures.values().collect(),
349 });
350 }
351 infos
352 }
353}
354
355pub struct SharedPartialPool(Mutex<PartialPool>);
357
358impl SharedPartialPool {
359 pub fn new(pool: PartialPool) -> Self {
360 Self(Mutex::new(pool))
361 }
362
363 pub fn lock(&self) -> MutexGuard<'_, PartialPool> {
364 self.0
365 .lock()
366 .unwrap_or_else(|poisoned| poisoned.into_inner())
367 }
368}
369
370#[cfg(test)]
371mod tests {
372 use std::collections::BTreeMap;
373
374 use heika_core::address::Address;
375 use heika_core::key::PrivateKey;
376 use heika_transaction::{Aggregate, EmbeddedTransaction, Transfer, UnresolvedMosaicId};
377
378 use super::*;
379
380 const NETWORK: &NetworkParameters = &NetworkParameters::TESTNET;
381 const NOW: u64 = 1_000_000;
382 const HOUR: u64 = 60 * 60 * 1000;
383 const HEIGHT: u64 = 10_000_000;
385
386 fn key(byte: u8) -> PrivateKey {
387 PrivateKey::from_bytes(&[byte; 32])
388 }
389
390 fn bonded(signer: u8, deadline: u64, cosigners: &[u8]) -> (Vec<u8>, Hash256) {
392 let private_key = key(signer);
393 let public_key = PublicKey::from_private_key(&private_key);
394 let recipient = Address::from_public_key(&public_key, NETWORK.identifier).into();
395 let mosaics = BTreeMap::from([(UnresolvedMosaicId(NETWORK.currency_mosaic_id), 1)]);
396 let transfer = Body::Transfer(Transfer::new(recipient, mosaics, Vec::new()).unwrap());
397 let embedded = EmbeddedTransaction::new(public_key, NETWORK.identifier, transfer);
398 let body = Body::AggregateBonded(Aggregate::new(vec![embedded]).unwrap());
399 let mut transaction = Transaction::new(public_key, NETWORK.identifier, 0, deadline, body);
400 transaction
401 .sign(&private_key, &NETWORK.generation_hash_seed)
402 .unwrap();
403 for &cosigner in cosigners {
404 transaction
405 .cosign(&key(cosigner), &NETWORK.generation_hash_seed)
406 .unwrap();
407 }
408 let hash = transaction.hash(&NETWORK.generation_hash_seed);
409 (transaction.to_bytes(), hash)
410 }
411
412 fn pool() -> PartialPool {
413 PartialPool::new(NETWORK, PartialConfig::default())
414 }
415
416 fn signers(pool: &PartialPool, hash: &Hash256) -> Vec<PublicKey> {
417 pool.cosignatures(hash)
418 .iter()
419 .map(|cosignature| cosignature.signer_public_key)
420 .collect()
421 }
422
423 #[test]
424 fn keeps_the_transaction_without_cosignatures_and_adds_them_in_signer_order() {
425 let mut pool = pool();
426 let (bytes, hash) = bonded(1, NOW + HOUR, &[3, 2]);
427 let added = pool.add(&bytes, NOW, HEIGHT).unwrap();
428 assert_eq!(added.hash, hash);
429 assert!(added.new);
430 assert_eq!(added.cosignatures.len(), 2);
431 let (plain, _) = bonded(1, NOW + HOUR, &[]);
432 assert_eq!(pool.transaction(&hash), Some(plain.as_slice()));
433 let mut expected = vec![
434 PublicKey::from_private_key(&key(2)),
435 PublicKey::from_private_key(&key(3)),
436 ];
437 expected.sort_by_key(|key| key.0);
438 assert_eq!(signers(&pool, &hash), expected);
439
440 let (more, _) = bonded(1, NOW + HOUR, &[2, 4]);
442 let added = pool.add(&more, NOW, HEIGHT).unwrap();
443 assert!(!added.new);
444 assert_eq!(
445 added
446 .cosignatures
447 .iter()
448 .map(|c| c.signer_public_key)
449 .collect::<Vec<_>>(),
450 [PublicKey::from_private_key(&key(4))]
451 );
452 assert_eq!(pool.cosignatures(&hash).len(), 3);
453
454 let stitched = Transaction::from_bytes(&pool.stitched(&hash).unwrap()).unwrap();
456 assert_eq!(stitched.hash(&NETWORK.generation_hash_seed), hash);
457 assert!(stitched.verify_cosignatures(&NETWORK.generation_hash_seed));
458 }
459
460 #[test]
461 fn takes_detached_cosignatures_once() {
462 let mut pool = pool();
463 let (bytes, hash) = bonded(1, NOW + HOUR, &[]);
464 pool.add(&bytes, NOW, HEIGHT).unwrap();
465 let cosign = |signer: u8, parent: &Hash256| DetachedCosignature::sign(&key(signer), parent);
466 assert_eq!(pool.add_cosignature(&cosign(2, &hash)), Ok(()));
467 assert_eq!(
468 pool.add_cosignature(&cosign(2, &hash)),
469 Err(CosignRejected::Redundant)
470 );
471 assert_eq!(
473 pool.add_cosignature(&cosign(1, &hash)),
474 Err(CosignRejected::Redundant)
475 );
476 assert_eq!(
477 pool.add_cosignature(&cosign(2, &Hash256([9; 32]))),
478 Err(CosignRejected::UnknownParent)
479 );
480 let mut forged = cosign(3, &hash);
481 forged.cosignature.signature.0[0] ^= 1;
482 assert_eq!(
483 pool.add_cosignature(&forged),
484 Err(CosignRejected::InvalidSignature)
485 );
486 assert!(pool.remove_cosignature(&hash, &PublicKey::from_private_key(&key(2))));
487 assert!(pool.cosignatures(&hash).is_empty());
488 }
489
490 #[test]
491 fn refuses_what_it_cannot_keep() {
492 let mut pool = pool();
493 let (expired, _) = bonded(1, NOW - 1, &[]);
494 assert!(matches!(
495 pool.add(&expired, NOW, HEIGHT),
496 Err(PartialRejected::Expired)
497 ));
498 let (far, _) = bonded(1, NOW + 49 * HOUR, &[]);
499 assert!(matches!(
500 pool.add(&far, NOW, HEIGHT),
501 Err(PartialRejected::TooFarAhead)
502 ));
503 let (mut forged, _) = bonded(1, NOW + HOUR, &[]);
504 forged[10] ^= 1;
505 assert!(matches!(
506 pool.add(&forged, NOW, HEIGHT),
507 Err(PartialRejected::Invalid(_))
508 ));
509 let mut small = PartialPool::new(
510 NETWORK,
511 PartialConfig {
512 max_bytes: 10,
513 ..PartialConfig::default()
514 },
515 );
516 let (bytes, _) = bonded(1, NOW + HOUR, &[]);
517 assert!(matches!(
518 small.add(&bytes, NOW, HEIGHT),
519 Err(PartialRejected::Full)
520 ));
521 }
522
523 #[test]
524 fn answers_peers_with_what_they_lack_and_prunes_expired() {
525 let mut pool = pool();
526 let (first, first_hash) = bonded(1, NOW + HOUR, &[2]);
527 let (second, second_hash) = bonded(3, NOW + 2 * HOUR, &[]);
528 pool.add(&first, NOW, HEIGHT).unwrap();
529 pool.add(&second, NOW, HEIGHT).unwrap();
530
531 let infos = pool.unknown_to(0, &HashMap::new());
533 assert_eq!(infos.len(), 2);
534 assert!(matches!(infos[0].info, PartialInfo::Transaction(_)));
535 assert_eq!(infos[0].cosignatures.len(), 1);
536
537 let pairs = pool.short_hash_pairs();
539 let mut known: HashMap<u32, u32> = pairs
540 .iter()
541 .map(|pair| (pair.transaction, pair.cosignatures))
542 .collect();
543 assert!(pool.unknown_to(0, &known).is_empty());
544 known.insert(short_hash(&first_hash), 0);
545 let infos = pool.unknown_to(0, &known);
546 assert_eq!(infos.len(), 1);
547 assert_eq!(infos[0].info, PartialInfo::Hash(first_hash));
548
549 assert_eq!(pool.unknown_to(NOW + HOUR + 1, &HashMap::new()).len(), 1);
551
552 assert_eq!(pool.prune(NOW + HOUR + 1), vec![first_hash]);
553 assert!(pool.contains(&second_hash));
554 assert!(pool.remove(&second_hash));
555 assert!(pool.is_empty());
556 assert_eq!(pool.bytes, 0);
557 }
558}