Support reloading the mempool from disk

This commit is contained in:
Luke Parker
2023-04-14 15:51:43 -04:00
parent c032f66f8a
commit 2e2bc59703
7 changed files with 127 additions and 41 deletions

View File

@@ -28,22 +28,26 @@ pub struct ProvidedTransactions<D: Db, T: Transaction> {
}
impl<D: Db, T: Transaction> ProvidedTransactions<D, T> {
fn provided_key(&self, hash: &[u8]) -> Vec<u8> {
D::key(b"tributary", b"provided", [self.genesis.as_ref(), hash].concat())
fn transaction_key(&self, hash: &[u8]) -> Vec<u8> {
D::key(b"tributary_provided", b"transaction", [self.genesis.as_ref(), hash].concat())
}
fn currently_provided_key(&self) -> Vec<u8> {
D::key(b"tributary", b"currently_provided", self.genesis)
fn current_provided_key(&self) -> Vec<u8> {
D::key(b"tributary_provided", b"current", self.genesis)
}
pub(crate) fn new(db: D, genesis: [u8; 32]) -> Self {
let mut res = ProvidedTransactions { db, genesis, transactions: VecDeque::new() };
let currently_provided = res.db.get(res.currently_provided_key()).unwrap_or(vec![]);
let currently_provided = res.db.get(res.current_provided_key()).unwrap_or(vec![]);
let mut i = 0;
while i < currently_provided.len() {
res.transactions.push_back(
T::read::<&[u8]>(
&mut res.db.get(res.provided_key(&currently_provided[i .. (i + 32)])).unwrap().as_ref(),
&mut res
.db
.get(res.transaction_key(&currently_provided[i .. (i + 32)]))
.unwrap()
.as_ref(),
)
.unwrap(),
);
@@ -65,18 +69,18 @@ impl<D: Db, T: Transaction> ProvidedTransactions<D, T> {
}
let tx_hash = tx.hash();
let provided_key = self.provided_key(&tx_hash);
let provided_key = self.transaction_key(&tx_hash);
if self.db.get(&provided_key).is_some() {
Err(ProvidedError::AlreadyProvided)?;
}
let currently_provided_key = self.currently_provided_key();
let mut currently_provided = self.db.get(&currently_provided_key).unwrap_or(vec![]);
let current_provided_key = self.current_provided_key();
let mut currently_provided = self.db.get(&current_provided_key).unwrap_or(vec![]);
let mut txn = self.db.txn();
txn.put(provided_key, tx.serialize());
currently_provided.extend(tx_hash);
txn.put(currently_provided_key, currently_provided);
txn.put(current_provided_key, currently_provided);
txn.commit();
self.transactions.push_back(tx);
@@ -87,9 +91,9 @@ impl<D: Db, T: Transaction> ProvidedTransactions<D, T> {
pub(crate) fn complete(&mut self, txn: &mut D::Transaction<'_>, tx: [u8; 32]) {
assert_eq!(self.transactions.pop_front().unwrap().hash(), tx);
let currently_provided_key = self.currently_provided_key();
let mut currently_provided = txn.get(&currently_provided_key).unwrap();
let current_provided_key = self.current_provided_key();
let mut currently_provided = txn.get(&current_provided_key).unwrap();
assert_eq!(&currently_provided.drain(.. 32).collect::<Vec<_>>(), &tx);
txn.put(currently_provided_key, currently_provided);
txn.put(current_provided_key, currently_provided);
}
}