1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use crate::error::ConsensusError;
use indexmap::{IndexMap, IndexSet};
use snarkos_storage::{Digest, SerialTransaction};
use snarkvm_dpc::BlockHeader;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct MempoolEntry {
pub(crate) size_in_bytes: usize,
pub(crate) transaction: SerialTransaction,
}
#[derive(Debug, Default)]
pub struct MemoryPool {
pub(crate) transactions: IndexMap<Digest, MempoolEntry>,
pub(crate) commitments: IndexSet<Digest>,
pub(crate) serial_numbers: IndexSet<Digest>,
pub(crate) memos: IndexSet<Digest>,
}
const BLOCK_HEADER_SIZE: usize = BlockHeader::size();
const COINBASE_TRANSACTION_SIZE: usize = 1490;
impl MemoryPool {
#[inline]
pub fn new() -> Self {
Self::default()
}
pub fn remove(&mut self, transaction_id: &Digest) -> Result<Option<SerialTransaction>, ConsensusError> {
match self.transactions.remove(transaction_id) {
Some(entry) => {
for commitment in &entry.transaction.new_commitments {
if !self.commitments.remove(commitment) {
panic!("missing commitment from memory pool during removal");
}
}
for serial in &entry.transaction.old_serial_numbers {
if !self.serial_numbers.remove(serial) {
panic!("missing serial from memory pool during removal");
}
}
if !self.memos.remove(&entry.transaction.memorandum) {
panic!("missing memo from memory pool during removal");
}
Ok(Some(entry.transaction))
}
None => Ok(None),
}
}
pub fn get_candidates(&self, max_size: usize) -> Vec<&SerialTransaction> {
let max_size = max_size - (BLOCK_HEADER_SIZE + COINBASE_TRANSACTION_SIZE);
let mut block_size = 0;
let mut transactions = vec![];
for (_, entry) in self.transactions.iter() {
if block_size + entry.size_in_bytes <= max_size {
block_size += entry.size_in_bytes;
transactions.push(&entry.transaction);
}
}
transactions
}
}