-
Notifications
You must be signed in to change notification settings - Fork 48
/
lib.rs
427 lines (373 loc) · 13.2 KB
/
lib.rs
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use anyhow::Error;
use bcs;
use mempool_util::{MempoolBlockOperations, MempoolTransaction, MempoolTransactionOperations};
use movement_types::{Block, Id};
use rocksdb::{ColumnFamilyDescriptor, Options, DB};
use std::fmt::Write;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct RocksdbMempool {
db: Arc<DB>,
}
impl RocksdbMempool {
pub fn try_new(path: &str) -> Result<Self, Error> {
let mut options = Options::default();
options.create_if_missing(true);
options.create_missing_column_families(true);
let mempool_transactions_cf =
ColumnFamilyDescriptor::new("mempool_transactions", Options::default());
let transaction_truths_cf =
ColumnFamilyDescriptor::new("transaction_truths", Options::default());
let blocks_cf = ColumnFamilyDescriptor::new("blocks", Options::default());
let transaction_lookups_cf =
ColumnFamilyDescriptor::new("transaction_lookups", Options::default());
let db = DB::open_cf_descriptors(
&options,
path,
vec![mempool_transactions_cf, transaction_truths_cf, blocks_cf, transaction_lookups_cf],
)
.map_err(|e| Error::new(e))?;
Ok(RocksdbMempool { db: Arc::new(db) })
}
pub fn construct_mempool_transaction_key(transaction: &MempoolTransaction) -> String {
// Pre-allocate a string with the required capacity
let mut key = String::with_capacity(32 + 1 + 32 + 1 + 32);
// Write key components. The numbers are zero-padded to 32 characters.
key.write_fmt(format_args!(
"{:032}:{:032}:{}",
transaction.timestamp,
transaction.transaction.sequence_number,
transaction.transaction.id(),
))
.unwrap();
key
}
fn internal_get_mempool_transaction_key(
db: Arc<DB>,
transaction_id: &Id,
) -> Result<Option<Vec<u8>>, Error> {
let cf_handle = db
.cf_handle("transaction_lookups")
.ok_or_else(|| Error::msg("CF handle not found"))?;
db.get_cf(&cf_handle, transaction_id.to_vec()).map_err(|e| Error::new(e))
}
/// Helper function to retrieve the key for mempool transaction from the lookup table.
async fn get_mempool_transaction_key(
&self,
transaction_id: &Id,
) -> Result<Option<Vec<u8>>, Error> {
let db = self.db.clone();
let transaction_id = transaction_id.clone();
tokio::task::spawn_blocking(move || {
Self::internal_get_mempool_transaction_key(db, &transaction_id)
})
.await?
}
fn internal_has_mempool_transaction(db: Arc<DB>, transaction_id: &Id) -> Result<bool, Error> {
let key = Self::internal_get_mempool_transaction_key(db.clone(), transaction_id)?;
match key {
Some(k) => {
let cf_handle = db
.cf_handle("mempool_transactions")
.ok_or_else(|| Error::msg("CF handle not found"))?;
Ok(db.get_cf(&cf_handle, k)?.is_some())
}
None => Ok(false),
}
}
}
impl MempoolTransactionOperations for RocksdbMempool {
async fn has_mempool_transaction(&self, transaction_id: Id) -> Result<bool, Error> {
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
Self::internal_has_mempool_transaction(db, &transaction_id)
})
.await?
}
async fn add_mempool_transactions(
&self,
transactions: Vec<MempoolTransaction>,
) -> Result<(), anyhow::Error> {
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
let mempool_transactions_cf_handle = db
.cf_handle("mempool_transactions")
.ok_or_else(|| Error::msg("CF handle not found"))?;
let transaction_lookups_cf_handle = db
.cf_handle("transaction_lookups")
.ok_or_else(|| Error::msg("CF handle not found"))?;
for tx in transactions {
if Self::internal_has_mempool_transaction(db.clone(), &tx.transaction.id())? {
continue;
}
let serialized_tx = bcs::to_bytes(&tx)?;
let key = Self::construct_mempool_transaction_key(&tx);
db.put_cf(&mempool_transactions_cf_handle, &key, &serialized_tx)?;
db.put_cf(&transaction_lookups_cf_handle, tx.transaction.id().to_vec(), &key)?;
}
Ok::<(), Error>(())
})
.await??;
Ok(())
}
async fn add_mempool_transaction(&self, tx: MempoolTransaction) -> Result<(), Error> {
let serialized_tx = bcs::to_bytes(&tx)?;
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
let mempool_transactions_cf_handle = db
.cf_handle("mempool_transactions")
.ok_or_else(|| Error::msg("CF handle not found"))?;
let transaction_lookups_cf_handle = db
.cf_handle("transaction_lookups")
.ok_or_else(|| Error::msg("CF handle not found"))?;
let key = Self::construct_mempool_transaction_key(&tx);
db.put_cf(&mempool_transactions_cf_handle, &key, &serialized_tx)?;
db.put_cf(&transaction_lookups_cf_handle, tx.transaction.id().to_vec(), &key)?;
Ok::<(), Error>(())
})
.await??;
Ok(())
}
async fn remove_mempool_transaction(&self, transaction_id: Id) -> Result<(), Error> {
let key = self.get_mempool_transaction_key(&transaction_id).await?;
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
match key {
Some(k) => {
let cf_handle = db
.cf_handle("mempool_transactions")
.ok_or_else(|| Error::msg("CF handle not found"))?;
db.delete_cf(&cf_handle, k)?;
let lookups_cf_handle = db
.cf_handle("transaction_lookups")
.ok_or_else(|| Error::msg("CF handle not found"))?;
db.delete_cf(&lookups_cf_handle, transaction_id.to_vec())?;
}
None => (),
}
Ok::<(), Error>(())
})
.await??;
Ok(())
}
// Updated method signatures and implementations go here
async fn get_mempool_transaction(
&self,
transaction_id: Id,
) -> Result<Option<MempoolTransaction>, Error> {
let key = match self.get_mempool_transaction_key(&transaction_id).await? {
Some(k) => k,
None => return Ok(None), // If no key found in lookup, return None
};
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
let cf_handle = db
.cf_handle("mempool_transactions")
.ok_or_else(|| Error::msg("CF handle not found"))?;
match db.get_cf(&cf_handle, &key)? {
Some(serialized_tx) => {
let tx: MempoolTransaction = bcs::from_bytes(&serialized_tx)?;
Ok(Some(tx))
}
None => Ok(None),
}
})
.await?
}
async fn pop_mempool_transaction(&self) -> Result<Option<MempoolTransaction>, Error> {
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
let cf_handle = db
.cf_handle("mempool_transactions")
.ok_or_else(|| Error::msg("CF handle not found"))?;
let mut iter = db.iterator_cf(&cf_handle, rocksdb::IteratorMode::Start);
match iter.next() {
None => return Ok(None), // No transactions to pop
Some(res) => {
let (key, value) = res?;
let tx: MempoolTransaction = bcs::from_bytes(&value)?;
db.delete_cf(&cf_handle, &key)?;
// Optionally, remove from the lookup table as well
let lookups_cf_handle = db
.cf_handle("transaction_lookups")
.ok_or_else(|| Error::msg("CF handle not found"))?;
db.delete_cf(&lookups_cf_handle, tx.transaction.id().to_vec())?;
Ok(Some(tx))
}
}
})
.await?
}
async fn pop_mempool_transactions(
&self,
n: usize,
) -> Result<Vec<MempoolTransaction>, anyhow::Error> {
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
let cf_handle = db
.cf_handle("mempool_transactions")
.ok_or_else(|| Error::msg("CF handle not found"))?;
let mut iter = db.iterator_cf(&cf_handle, rocksdb::IteratorMode::Start);
let mut mempool_transactions = Vec::with_capacity(n as usize);
while let Some(res) = iter.next() {
let (key, value) = res?;
let tx: MempoolTransaction = bcs::from_bytes(&value)?;
db.delete_cf(&cf_handle, &key)?;
// Optionally, remove from the lookup table as well
let lookups_cf_handle = db
.cf_handle("transaction_lookups")
.ok_or_else(|| Error::msg("CF handle not found"))?;
db.delete_cf(&lookups_cf_handle, tx.transaction.id().to_vec())?;
mempool_transactions.push(tx);
if mempool_transactions.len() > n - 1 {
break;
}
}
Ok(mempool_transactions)
})
.await?
}
}
impl MempoolBlockOperations for RocksdbMempool {
async fn has_block(&self, block_id: Id) -> Result<bool, Error> {
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
let cf_handle =
db.cf_handle("blocks").ok_or_else(|| Error::msg("CF handle not found"))?;
Ok(db.get_cf(&cf_handle, block_id.to_vec())?.is_some())
})
.await?
}
async fn add_block(&self, block: Block) -> Result<(), Error> {
let serialized_block = bcs::to_bytes(&block)?;
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
let cf_handle =
db.cf_handle("blocks").ok_or_else(|| Error::msg("CF handle not found"))?;
db.put_cf(&cf_handle, block.id().to_vec(), &serialized_block)?;
Ok(())
})
.await?
}
async fn remove_block(&self, block_id: Id) -> Result<(), Error> {
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
let cf_handle =
db.cf_handle("blocks").ok_or_else(|| Error::msg("CF handle not found"))?;
db.delete_cf(&cf_handle, block_id.to_vec())?;
Ok(())
})
.await?
}
async fn get_block(&self, block_id: Id) -> Result<Option<Block>, Error> {
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
let cf_handle =
db.cf_handle("blocks").ok_or_else(|| Error::msg("CF handle not found"))?;
let serialized_block = db.get_cf(&cf_handle, block_id.to_vec())?;
match serialized_block {
Some(serialized_block) => {
let block: Block = bcs::from_bytes(&serialized_block)?;
Ok(Some(block))
}
None => Ok(None),
}
})
.await?
}
}
#[cfg(test)]
pub mod test {
use super::*;
use movement_types::Transaction;
use tempfile::tempdir;
#[tokio::test]
async fn test_rocksdb_mempool_basic_operations() -> Result<(), Error> {
let temp_dir = tempdir().unwrap();
let path = temp_dir.path().to_str().unwrap();
let mempool = RocksdbMempool::try_new(path)?;
let tx = MempoolTransaction::test();
let tx_id = tx.id();
mempool.add_mempool_transaction(tx.clone()).await?;
assert!(mempool.has_mempool_transaction(tx_id.clone()).await?);
let tx2 = mempool.get_mempool_transaction(tx_id.clone()).await?;
assert_eq!(Some(tx), tx2);
mempool.remove_mempool_transaction(tx_id.clone()).await?;
assert!(!mempool.has_mempool_transaction(tx_id.clone()).await?);
let block = Block::test();
let block_id = block.id();
mempool.add_block(block.clone()).await?;
assert!(mempool.has_block(block_id.clone()).await?);
let block2 = mempool.get_block(block_id.clone()).await?;
assert_eq!(Some(block), block2);
mempool.remove_block(block_id.clone()).await?;
assert!(!mempool.has_block(block_id.clone()).await?);
Ok(())
}
#[tokio::test]
async fn test_rocksdb_transaction_operations() -> Result<(), Error> {
let temp_dir = tempdir().unwrap();
let path = temp_dir.path().to_str().unwrap();
let mempool = RocksdbMempool::try_new(path)?;
let tx = Transaction::test();
let tx_id = tx.id();
mempool.add_transaction(tx.clone()).await?;
assert!(mempool.has_transaction(tx_id.clone()).await?);
let tx2 = mempool.get_transaction(tx_id.clone()).await?;
assert_eq!(Some(tx), tx2);
mempool.remove_transaction(tx_id.clone()).await?;
assert!(!mempool.has_transaction(tx_id.clone()).await?);
Ok(())
}
#[tokio::test]
async fn test_transaction_slot_based_ordering() -> Result<(), Error> {
let temp_dir = tempdir().unwrap();
let path = temp_dir.path().to_str().unwrap();
let mempool = RocksdbMempool::try_new(path)?;
let tx1 = MempoolTransaction::at_time(Transaction::new(vec![1], 0), 2);
let tx2 = MempoolTransaction::at_time(Transaction::new(vec![2], 0), 64);
let tx3 = MempoolTransaction::at_time(Transaction::new(vec![3], 0), 128);
mempool.add_mempool_transaction(tx2.clone()).await?;
mempool.add_mempool_transaction(tx1.clone()).await?;
mempool.add_mempool_transaction(tx3.clone()).await?;
let txs = mempool.pop_mempool_transactions(3).await?;
assert_eq!(txs[0], tx1);
assert_eq!(txs[1], tx2);
assert_eq!(txs[2], tx3);
Ok(())
}
#[tokio::test]
async fn test_transaction_sequence_number_based_ordering() -> Result<(), Error> {
let temp_dir = tempdir().unwrap();
let path = temp_dir.path().to_str().unwrap();
let mempool = RocksdbMempool::try_new(path)?;
let tx1 = MempoolTransaction::at_time(Transaction::new(vec![1], 0), 2);
let tx2 = MempoolTransaction::at_time(Transaction::new(vec![2], 1), 2);
let tx3 = MempoolTransaction::at_time(Transaction::new(vec![3], 0), 64);
mempool.add_mempool_transaction(tx2.clone()).await?;
mempool.add_mempool_transaction(tx1.clone()).await?;
mempool.add_mempool_transaction(tx3.clone()).await?;
let txs = mempool.pop_mempool_transactions(3).await?;
assert_eq!(txs[0], tx1);
assert_eq!(txs[1], tx2);
assert_eq!(txs[2], tx3);
Ok(())
}
#[tokio::test]
async fn test_slot_and_transaction_based_ordering() -> Result<(), Error> {
let temp_dir = tempdir().unwrap();
let path = temp_dir.path().to_str().unwrap();
let mempool = RocksdbMempool::try_new(path)?;
let tx1 = MempoolTransaction::at_time(Transaction::new(vec![1], 0), 0);
let tx2 = MempoolTransaction::at_time(Transaction::new(vec![2], 1), 0);
let tx3 = MempoolTransaction::at_time(Transaction::new(vec![3], 2), 0);
mempool.add_mempool_transaction(tx2.clone()).await?;
mempool.add_mempool_transaction(tx1.clone()).await?;
mempool.add_mempool_transaction(tx3.clone()).await?;
let txs = mempool.pop_mempool_transactions(3).await?;
assert_eq!(txs[0], tx1);
assert_eq!(txs[1], tx2);
assert_eq!(txs[2], tx3);
Ok(())
}
}