tx_pool.rs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. use async_std::sync::Mutex;
  2. use std::{io, sync::Arc};
  3. use fxhash::FxHashSet;
  4. use darkfi::{
  5. net,
  6. util::serial::{Decodable, Encodable},
  7. Result,
  8. };
  9. pub type TxHash = u32; // Change this to a proper hash type
  10. #[derive(Debug, Clone, Eq, Hash, PartialEq)]
  11. pub struct Tx {
  12. pub hash: TxHash,
  13. pub payload: String,
  14. }
  15. impl net::Message for Tx {
  16. fn name() -> &'static str {
  17. "tx"
  18. }
  19. }
  20. impl Encodable for Tx {
  21. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  22. let mut len = 0;
  23. len += self.hash.encode(&mut s)?;
  24. len += self.payload.encode(&mut s)?;
  25. Ok(len)
  26. }
  27. }
  28. impl Decodable for Tx {
  29. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  30. Ok(Self { hash: Decodable::decode(&mut d)?, payload: Decodable::decode(&mut d)? })
  31. }
  32. }
  33. #[derive(Debug)]
  34. pub struct TxPool {
  35. tx_pool: Mutex<FxHashSet<Tx>>,
  36. }
  37. pub type TxPoolPtr = Arc<TxPool>;
  38. impl TxPool {
  39. pub fn new() -> Arc<Self> {
  40. Arc::new(Self { tx_pool: Mutex::new(FxHashSet::default()) })
  41. }
  42. pub async fn add_tx(&self, tx: Tx) {
  43. self.tx_pool.lock().await.insert(tx);
  44. }
  45. pub async fn tx_exists(&self, tx: &Tx) -> bool {
  46. self.tx_pool.lock().await.contains(tx)
  47. }
  48. }