1use std::collections::BTreeSet;
12
13use heika_block::Block;
14use heika_core::address::Address;
15use heika_core::key::PublicKey;
16use heika_core::patricia::SubCache;
17use heika_transaction::{Body, EmbeddedTransaction, MetadataKey, MetadataType, Transaction};
18
19use heika_core::patricia::TreeNode;
20
21use super::persist::row_key;
22use super::source::StateSource;
23use super::{ExecError, Executor, HashLockInfo};
24use crate::account::AccountType;
25use crate::config::ChainConfig;
26use crate::table::Table;
27use crate::tree::LazyTree;
28use crate::tree::StateTree;
29use crate::tree::{Position, ROOT, node_key};
30
31#[derive(Clone, Debug, Default, PartialEq, Eq)]
33pub struct Wanted {
34 pub accounts: BTreeSet<[u8; 24]>,
35 pub multisigs: BTreeSet<[u8; 24]>,
36 pub hash_locks: BTreeSet<[u8; 32]>,
37 pub metadata: BTreeSet<[u8; 32]>,
38 pub nodes: BTreeSet<(u8, Position)>,
40}
41
42impl Wanted {
43 pub fn is_empty(&self) -> bool {
44 self.len() == 0
45 }
46
47 pub fn len(&self) -> usize {
48 self.accounts.len()
49 + self.multisigs.len()
50 + self.hash_locks.len()
51 + self.metadata.len()
52 + self.nodes.len()
53 }
54
55 pub fn extend(&mut self, other: Wanted) {
56 self.accounts.extend(other.accounts);
57 self.multisigs.extend(other.multisigs);
58 self.hash_locks.extend(other.hash_locks);
59 self.metadata.extend(other.metadata);
60 self.nodes.extend(other.nodes);
61 }
62
63 fn row_keys(&self) -> impl Iterator<Item = Vec<u8>> + '_ {
65 let accounts = self
66 .accounts
67 .iter()
68 .map(|key| row_key(SubCache::AccountState, key));
69 let multisigs = self
70 .multisigs
71 .iter()
72 .map(|key| row_key(SubCache::Multisig, key));
73 let hash_locks = self
74 .hash_locks
75 .iter()
76 .map(|key| row_key(SubCache::HashLockInfo, key));
77 let metadata = self
78 .metadata
79 .iter()
80 .map(|key| row_key(SubCache::Metadata, key));
81 accounts.chain(multisigs).chain(hash_locks).chain(metadata)
82 }
83}
84
85const PARTIAL: [SubCache; 4] = [
87 SubCache::AccountState,
88 SubCache::Multisig,
89 SubCache::HashLockInfo,
90 SubCache::Metadata,
91];
92
93pub fn is_partial_row(key: &[u8]) -> bool {
95 key.first().is_some_and(|cache| {
96 PARTIAL
97 .iter()
98 .any(|partial| partial.index() == usize::from(*cache))
99 })
100}
101
102impl Executor {
103 pub fn restore_partial(
107 config: ChainConfig,
108 network: heika_core::network::NetworkIdentifier,
109 generation_hash_seed: heika_core::network::GenerationHashSeed,
110 rows: impl IntoIterator<Item = (Vec<u8>, Vec<u8>)>,
111 meta: &[u8],
112 ) -> Result<Self, ExecError> {
113 if config.finalization.min_voter_balance < config.min_harvester_balance {
115 return Err(ExecError::Unsupported(
116 "投票者の下限が大口の下限より低いネットワークでは、アカウントを全部メモリに持ちます"
117 .to_owned(),
118 ));
119 }
120 let mut executor = Self::new(config, network, generation_hash_seed);
121 executor.accounts = Table::partial();
122 executor.multisigs = Table::partial();
123 executor.hash_locks = Table::partial();
124 executor.metadata = Table::partial();
125 for cache in PARTIAL {
126 executor.trees[cache.index()] = StateTree::Lazy(LazyTree::new());
127 }
128 executor.decode_meta(meta)?;
129 let hash_lock = SubCache::HashLockInfo.index() as u8;
130 for (key, value) in rows {
131 if key.first() == Some(&hash_lock) {
132 executor.load_row(&key, Some(&value))?;
133 let id = <[u8; 32]>::try_from(&key[1..])
134 .map_err(|_| ExecError::Source("ハッシュロックのキー".to_owned()))?;
135 if !executor.hash_lock_pending(&id) {
136 executor.hash_locks.forget(&id);
138 }
139 } else if is_partial_row(&key) {
140 return Err(ExecError::Invalid(
141 "全部はメモリに持たない表の行は渡さないでください".to_owned(),
142 ));
143 } else {
144 executor.set_row(&key, Some(&value))?;
145 }
146 }
147 executor.dirty_rows.clear();
149 executor.schedule_expiries();
150 Ok(executor)
151 }
152
153 pub fn is_partial(&self) -> bool {
155 !self.accounts.is_complete()
156 }
157
158 fn hash_lock_pending(&self, key: &[u8; 32]) -> bool {
160 let height = self.height;
161 self.hash_locks
162 .peek(key)
163 .is_some_and(|history: &Vec<HashLockInfo>| {
164 history.iter().any(|lock| lock.end_height > height)
165 })
166 }
167
168 pub fn load_tree_roots(&mut self, source: &dyn StateSource) -> Result<(), ExecError> {
170 for cache in PARTIAL {
171 self.load_node(source, cache, ROOT)?;
172 }
173 Ok(())
174 }
175
176 fn load_node(
177 &mut self,
178 source: &dyn StateSource,
179 cache: SubCache,
180 position: Position,
181 ) -> Result<(), ExecError> {
182 let Some(tree) = self.trees[cache.index()].as_lazy_mut() else {
183 return Ok(());
184 };
185 if tree.is_loaded(&position) {
186 return Ok(());
187 }
188 let node = source
189 .node(&node_key(cache.index() as u8, &position))?
190 .map(|bytes| {
191 TreeNode::decode_all(&bytes)
192 .ok()
193 .and_then(|nodes| nodes.into_iter().next())
194 .ok_or_else(|| ExecError::Source("しまった木のノードが読めません".to_owned()))
195 })
196 .transpose()?;
197 tree.load(position, node);
198 Ok(())
199 }
200
201 pub fn load_wanted(
203 &mut self,
204 source: &dyn StateSource,
205 wanted: &Wanted,
206 ) -> Result<usize, ExecError> {
207 let generation = self.height + 1;
208 for cache in PARTIAL {
209 if let Some(tree) = self.trees[cache.index()].as_lazy_mut() {
210 tree.set_generation(generation);
211 }
212 }
213 let mut loaded = 0;
214 for key in wanted.row_keys() {
215 let (cache, tree_key) = super::tree_key_of_row(&key);
216 while let Some(next) = self.trees[cache.index()]
217 .as_lazy_mut()
218 .and_then(|tree| tree.next_on_path(&tree_key.0))
219 {
220 self.load_node(source, cache, next)?;
221 }
222 if self.is_row_loaded(&key) {
223 continue;
224 }
225 let value = source.row(&key)?;
226 self.load_row(&key, value.as_deref())?;
227 loaded += 1;
228 }
229 for (cache, position) in &wanted.nodes {
230 self.load_node(source, SubCache::ALL[usize::from(*cache)], *position)?;
231 }
232 let linked: BTreeSet<[u8; 24]> = wanted
234 .accounts
235 .iter()
236 .filter_map(|address| self.accounts.peek(address))
237 .filter(|account| account.account_type == AccountType::Remote)
238 .filter_map(|account| account.linked)
239 .map(|main| self.address_of(&PublicKey(main)))
240 .filter(|address| !self.accounts.is_loaded(address))
241 .collect();
242 if !linked.is_empty() {
243 let linked = Wanted {
244 accounts: linked,
245 ..Wanted::default()
246 };
247 loaded += self.load_wanted(source, &linked)?;
248 }
249 Ok(loaded)
250 }
251
252 fn is_row_loaded(&self, key: &[u8]) -> bool {
253 let id = &key[1..];
254 match SubCache::ALL.get(usize::from(key[0])) {
255 Some(SubCache::AccountState) => {
256 id.try_into().is_ok_and(|id| self.accounts.is_loaded(&id))
257 }
258 Some(SubCache::Multisig) => id.try_into().is_ok_and(|id| self.multisigs.is_loaded(&id)),
259 Some(SubCache::HashLockInfo) => {
260 id.try_into().is_ok_and(|id| self.hash_locks.is_loaded(&id))
261 }
262 Some(SubCache::Metadata) => id.try_into().is_ok_and(|id| self.metadata.is_loaded(&id)),
263 _ => true,
264 }
265 }
266
267 pub fn take_missed(&mut self) -> Wanted {
269 let mut nodes = BTreeSet::new();
270 for cache in PARTIAL {
271 if let Some(tree) = self.trees[cache.index()].as_lazy_mut() {
272 nodes.extend(
273 tree.take_missed()
274 .into_iter()
275 .map(|position| (cache.index() as u8, position)),
276 );
277 }
278 }
279 Wanted {
280 accounts: self.accounts.take_missed(),
281 multisigs: self.multisigs.take_missed(),
282 hash_locks: self.hash_locks.take_missed(),
283 metadata: self.metadata.take_missed(),
284 nodes,
285 }
286 }
287
288 pub fn wanted_for(&self, block: &Block) -> Wanted {
291 let height = block.height;
292 let mut wanted = Wanted::default();
293 wanted.accounts.extend([
294 self.address_of(&block.signer_public_key),
295 block.beneficiary_address.0,
296 self.config.harvest_network_fee_sink.at(height).0,
297 self.config.mosaic_rental_fee_sink.at(height).0,
298 self.config.namespace_rental_fee_sink.at(height).0,
299 ]);
300 let grouping = self.config.importance_grouping;
302 if height % grouping <= 1 {
303 wanted.accounts.extend(self.high_value.iter().copied());
304 wanted.accounts.extend(self.removed.iter().copied());
305 }
306 wanted
308 .hash_locks
309 .extend(self.locks_due(height, SubCache::HashLockInfo));
310 for bytes in block.transactions() {
311 let Ok(transaction) = Transaction::from_bytes(bytes) else {
312 continue;
313 };
314 self.want_transaction(&transaction, &mut wanted);
315 }
316 wanted
317 }
318
319 pub fn wanted_for_transaction(&self, transaction: &Transaction) -> Wanted {
322 let mut wanted = Wanted::default();
323 self.want_transaction(transaction, &mut wanted);
324 wanted
325 }
326
327 fn want_transaction(&self, transaction: &Transaction, wanted: &mut Wanted) {
328 let signer = self.address_of(&transaction.signer_public_key);
329 wanted.accounts.insert(signer);
330 wanted.multisigs.insert(signer);
331 match &transaction.body {
332 Body::AggregateComplete(aggregate) | Body::AggregateBonded(aggregate) => {
333 if matches!(transaction.body, Body::AggregateBonded(_)) {
334 wanted
335 .hash_locks
336 .insert(transaction.hash(&self.generation_hash_seed).0);
337 }
338 for cosignature in aggregate.cosignatures() {
339 let cosigner = self.address_of(&cosignature.signer_public_key);
340 wanted.accounts.insert(cosigner);
341 wanted.multisigs.insert(cosigner);
342 }
343 for inner in aggregate.transactions() {
344 self.want_body(inner, wanted);
345 }
346 }
347 _ => self.want_inner_body(signer, &transaction.body, wanted),
348 }
349 }
350
351 fn want_body(&self, inner: &EmbeddedTransaction, wanted: &mut Wanted) {
352 let signer = self.address_of(&inner.signer_public_key);
353 wanted.accounts.insert(signer);
354 wanted.multisigs.insert(signer);
355 self.want_inner_body(signer, &inner.body, wanted);
356 }
357
358 fn want_inner_body(&self, signer: [u8; 24], body: &Body, wanted: &mut Wanted) {
359 let metadata = |target, scoped, target_id, metadata_type| {
360 MetadataKey {
361 source_address: Address(signer),
362 target_address: Address(target),
363 scoped_metadata_key: scoped,
364 target_id,
365 metadata_type,
366 }
367 .unique_key()
368 .0
369 };
370 match body {
371 Body::Transfer(transfer) => {
372 wanted
373 .accounts
374 .insert(self.peek_address(transfer.recipient_address()));
375 }
376 Body::HashLock(lock) => {
377 wanted.hash_locks.insert(lock.hash.0);
378 }
379 Body::AccountKeyLink(link) => {
381 wanted
382 .accounts
383 .insert(self.address_of(&link.linked_public_key));
384 }
385 Body::MultisigAccountModification(modification) => {
386 for address in modification
387 .address_additions
388 .iter()
389 .chain(modification.address_deletions.iter())
390 {
391 let address = self.peek_address(address);
392 wanted.accounts.insert(address);
393 wanted.multisigs.insert(address);
394 }
395 }
396 Body::AccountMetadata(entry) => {
397 let target = self.peek_address(&entry.target_address);
398 wanted.accounts.insert(target);
399 wanted.metadata.insert(metadata(
400 target,
401 entry.scoped_metadata_key,
402 0,
403 MetadataType::Account,
404 ));
405 }
406 Body::MosaicMetadata(entry) => {
407 let target = self.peek_address(&entry.metadata.target_address);
408 wanted.accounts.insert(target);
409 wanted.metadata.insert(metadata(
410 target,
411 entry.metadata.scoped_metadata_key,
412 self.peek_mosaic(entry.target_mosaic_id.0),
413 MetadataType::Mosaic,
414 ));
415 }
416 Body::NamespaceMetadata(entry) => {
417 let target = self.peek_address(&entry.metadata.target_address);
418 wanted.accounts.insert(target);
419 wanted.metadata.insert(metadata(
420 target,
421 entry.metadata.scoped_metadata_key,
422 entry.target_namespace_id.0,
423 MetadataType::Namespace,
424 ));
425 }
426 _ => {}
427 }
428 }
429
430 pub fn undo_attempt(
435 &mut self,
436 source: &dyn StateSource,
437 checkpoint: &[u8],
438 ) -> Result<(), ExecError> {
439 for cache in PARTIAL {
441 if let Some(tree) = self.trees[cache.index()].as_lazy_mut() {
442 tree.discard_changes();
443 }
444 }
445 let accounts: BTreeSet<[u8; 24]> = self
446 .touched
447 .iter()
448 .chain(self.unsaved_accounts.iter())
449 .chain(self.dirty_accounts.iter())
450 .copied()
451 .collect();
452 let rows: BTreeSet<Vec<u8>> = self
453 .unsaved_rows
454 .iter()
455 .chain(self.dirty_rows.iter())
456 .cloned()
457 .collect();
458 for key in accounts
459 .iter()
460 .map(|address| row_key(SubCache::AccountState, address))
461 .chain(rows)
462 {
463 let value = source.row(&key)?;
464 self.set_row(&key, value.as_deref())?;
465 }
466 for (deadline, hash) in std::mem::take(&mut self.attempt_hashes) {
467 self.recent_hashes.remove(&hash);
468 if let Some(hashes) = self.hash_deadlines.get_mut(&deadline) {
469 hashes.retain(|kept| *kept != hash);
470 }
471 }
472 self.fee_multipliers.clear();
473 self.high_value.clear();
474 self.removed.clear();
475 self.stale_secret_locks.clear();
476 self.decode_meta(checkpoint)?;
477 self.expiries.clear();
478 self.artifact_expiries.clear();
479 self.schedule_expiries();
480 self.touched.clear();
481 self.unsaved_accounts.clear();
482 self.unsaved_rows.clear();
483 self.statement = super::StatementBuilder::default();
484 self.roots();
485 self.forget_node_changes();
486 self.take_missed();
487 Ok(())
488 }
489
490 pub fn release_loaded(&mut self) -> usize {
495 if !self.is_partial() {
496 return 0;
497 }
498 let (dirty, unsaved) = (&self.dirty_accounts, &self.unsaved_accounts);
499 let mut released = self
500 .accounts
501 .release(|address| dirty.contains(address) || unsaved.contains(address));
502 let changed = |cache: SubCache, key: &[u8]| {
503 let row = row_key(cache, key);
504 self.dirty_rows.contains(&row) || self.unsaved_rows.contains(&row)
505 };
506 let height = self.height;
507 let pending: BTreeSet<[u8; 32]> = self
508 .hash_locks
509 .iter()
510 .filter(|(_, history)| history.iter().any(|lock| lock.end_height > height))
511 .map(|(key, _)| *key)
512 .collect();
513 released += self
514 .multisigs
515 .release(|key| changed(SubCache::Multisig, key));
516 released += self
517 .hash_locks
518 .release(|key| pending.contains(key) || changed(SubCache::HashLockInfo, key));
519 released += self
520 .metadata
521 .release(|key| changed(SubCache::Metadata, key));
522 for cache in PARTIAL {
523 if let Some(tree) = self.trees[cache.index()].as_lazy_mut() {
524 released += tree.evict(0);
525 }
526 }
527 released
528 }
529}
530
531#[cfg(test)]
532mod tests {
533 use heika_core::key::PrivateKey;
534 use heika_core::network::NetworkParameters;
535 use heika_transaction::{Transfer, UnresolvedAddress, UnresolvedMosaicId};
536
537 use super::*;
538
539 struct Empty;
540
541 impl StateSource for Empty {
542 fn row(&self, _: &[u8]) -> Result<Option<Vec<u8>>, ExecError> {
543 Ok(None)
544 }
545
546 fn node(&self, _: &[u8]) -> Result<Option<Vec<u8>>, ExecError> {
547 Ok(None)
548 }
549
550 fn for_each_row(&self, _: &[u8], _: &mut dyn FnMut(&[u8], &[u8])) -> Result<(), ExecError> {
551 Ok(())
552 }
553 }
554
555 fn block(parameters: &NetworkParameters, transactions: &[Vec<u8>]) -> Block {
557 let mut bytes = vec![0u8; 376];
558 bytes[108] = 1;
559 bytes[109] = parameters.identifier.0;
560 bytes[110..112].copy_from_slice(&0x8143u16.to_le_bytes());
561 bytes[112..120].copy_from_slice(&1u64.to_le_bytes());
562 for transaction in transactions {
563 bytes.extend_from_slice(transaction);
564 bytes.resize(bytes.len().next_multiple_of(8), 0);
565 }
566 let size = bytes.len() as u32;
567 bytes[..4].copy_from_slice(&size.to_le_bytes());
568 Block::from_bytes(&bytes).unwrap()
569 }
570
571 #[test]
574 fn wants_the_remote_account_of_an_account_key_link() {
575 let parameters = NetworkParameters::MAINNET;
576 let main = PublicKey::from_private_key(&PrivateKey::from_bytes(&[1; 32]));
577 let remote = PublicKey::from_private_key(&PrivateKey::from_bytes(&[2; 32]));
578 let link = Transaction::new(
579 main,
580 parameters.identifier,
581 0,
582 1,
583 Body::AccountKeyLink(heika_transaction::KeyLink {
584 linked_public_key: remote,
585 link_action: heika_transaction::LinkAction::Link,
586 }),
587 );
588 let executor = Executor::new(
589 ChainConfig::mainnet(),
590 parameters.identifier,
591 parameters.generation_hash_seed,
592 );
593 let wanted = executor.wanted_for(&block(¶meters, &[link.to_bytes()]));
594 assert!(wanted.accounts.contains(&executor.address_of(&remote)));
595 assert!(wanted.accounts.contains(&executor.address_of(&main)));
596 }
597
598 #[test]
601 fn undoing_an_attempt_keeps_hashes_remembered_before_it() {
602 let parameters = NetworkParameters::TESTNET;
603 let key = PrivateKey::from_bytes(&[1; 32]);
604 let mut transaction = Transaction::new(
605 PublicKey::from_private_key(&key),
606 parameters.identifier,
607 0,
608 1,
609 Body::Transfer(
610 Transfer::new(
611 UnresolvedAddress::from(Address([0x98; 24])),
612 [(UnresolvedMosaicId(parameters.currency_mosaic_id), 1)].into(),
613 Vec::new(),
614 )
615 .unwrap(),
616 ),
617 );
618 transaction
619 .sign(&key, ¶meters.generation_hash_seed)
620 .unwrap();
621 let block = block(¶meters, &[transaction.to_bytes()]);
622 let mut executor = Executor::new(
623 ChainConfig::testnet(),
624 parameters.identifier,
625 parameters.generation_hash_seed,
626 );
627 executor.remember_transactions(&block).unwrap();
629 let meta = executor.encode_meta();
630 for _ in 0..2 {
631 let error = executor.apply(&block).unwrap_err().to_string();
632 assert!(error.contains("もう入っています"), "{error}");
633 executor.undo_attempt(&Empty, &meta).unwrap();
634 }
635 }
636}