tx.rs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. use std::io;
  2. use darkfi::{
  3. impl_vec, net,
  4. util::serial::{
  5. deserialize, serialize, Decodable, Encodable, SerialDecodable, SerialEncodable, VarInt,
  6. },
  7. Result,
  8. };
  9. const SLED_TX_TREE: &[u8] = b"_transactions";
  10. /// Temporary structure used to represent transactions.
  11. #[derive(Debug, Clone, PartialEq, SerialEncodable, SerialDecodable)]
  12. pub struct Tx {
  13. pub payload: String,
  14. }
  15. impl net::Message for Tx {
  16. fn name() -> &'static str {
  17. "tx"
  18. }
  19. }
  20. impl_vec!(Tx);
  21. #[derive(Debug)]
  22. pub struct TxStore(sled::Tree);
  23. impl TxStore {
  24. pub fn new(db: &sled::Db) -> Result<Self> {
  25. let tree = db.open_tree(SLED_TX_TREE)?;
  26. Ok(Self(tree))
  27. }
  28. /// Insert a tx into the txstore.
  29. /// The tx is hashed with blake3 and this txhash is used as
  30. /// the key, where value is the serialized tx itself.
  31. pub fn insert(&self, tx: &Tx) -> Result<blake3::Hash> {
  32. let serialized = serialize(tx);
  33. let txhash = blake3::hash(&serialized);
  34. self.0.insert(txhash.as_bytes(), serialized)?;
  35. Ok(txhash)
  36. }
  37. /// Fetch given transactions from the txstore.
  38. /// The resulting vector contains `Option` which is `Some` if the tx
  39. /// was found in the txstore, and `None`, if it has not.
  40. pub fn get(&self, txhashes: &[blake3::Hash]) -> Result<Vec<Option<Tx>>> {
  41. let mut ret: Vec<Option<Tx>> = Vec::with_capacity(txhashes.len());
  42. for i in txhashes {
  43. if let Some(found) = self.0.get(i.as_bytes())? {
  44. let tx = deserialize(&found)?;
  45. ret.push(Some(tx));
  46. } else {
  47. ret.push(None);
  48. }
  49. }
  50. Ok(ret)
  51. }
  52. /// Retrieve all transactions.
  53. /// Be carefull as this will try to load everything in memory.
  54. pub fn get_all(&self) -> Result<Vec<Option<(blake3::Hash, Tx)>>> {
  55. let mut txs = Vec::new();
  56. let mut iterator = self.0.into_iter().enumerate();
  57. while let Some((_, r)) = iterator.next() {
  58. let (k, v) = r.unwrap();
  59. let hash_bytes: [u8; 32] = k.as_ref().try_into().unwrap();
  60. let tx = deserialize(&v)?;
  61. txs.push(Some((hash_bytes.into(), tx)));
  62. }
  63. Ok(txs)
  64. }
  65. }