|
| 1 | +use alloc::sync::Arc; |
| 2 | +use alloc::vec::Vec; |
| 3 | + |
| 4 | +use bitcoin::{OutPoint, Transaction, TxOut, Txid}; |
| 5 | + |
| 6 | +use crate::collections::{BTreeMap, BTreeSet}; |
| 7 | +use crate::Merge; |
| 8 | + |
| 9 | +/// Version 1 [`ChangeSet`] |
| 10 | +pub mod v1 { |
| 11 | + use super::*; |
| 12 | + |
| 13 | + /// The [`ChangeSet`] represents changes to a [`TxGraph`]. |
| 14 | + /// |
| 15 | + /// Since [`TxGraph`] is monotone, the "changeset" can only contain transactions to be added and |
| 16 | + /// not removed. |
| 17 | + /// |
| 18 | + /// Refer to [module-level documentation](crate::tx_graph) for more. |
| 19 | + /// |
| 20 | + /// [`TxGraph`]: crate::TxGraph |
| 21 | + #[derive(Debug, Clone, PartialEq)] |
| 22 | + #[cfg_attr( |
| 23 | + feature = "serde", |
| 24 | + derive(serde::Deserialize, serde::Serialize), |
| 25 | + serde(bound( |
| 26 | + deserialize = "A: Ord + serde::Deserialize<'de>", |
| 27 | + serialize = "A: Ord + serde::Serialize", |
| 28 | + )) |
| 29 | + )] |
| 30 | + pub struct ChangeSet<A = ()> { |
| 31 | + /// Added transactions. |
| 32 | + pub txs: BTreeSet<Arc<Transaction>>, |
| 33 | + /// Added txouts. |
| 34 | + pub txouts: BTreeMap<OutPoint, TxOut>, |
| 35 | + /// Added anchors. |
| 36 | + pub anchors: BTreeSet<(A, Txid)>, |
| 37 | + /// Added last-seen unix timestamps of transactions. |
| 38 | + pub last_seen: BTreeMap<Txid, u64>, |
| 39 | + } |
| 40 | + |
| 41 | + impl<A> Default for ChangeSet<A> { |
| 42 | + fn default() -> Self { |
| 43 | + Self { |
| 44 | + txs: Default::default(), |
| 45 | + txouts: Default::default(), |
| 46 | + anchors: Default::default(), |
| 47 | + last_seen: Default::default(), |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + impl<A: Ord> Merge for ChangeSet<A> { |
| 53 | + fn merge(&mut self, other: Self) { |
| 54 | + // We use `extend` instead of `BTreeMap::append` due to performance issues with `append`. |
| 55 | + // Refer to https://github.com/rust-lang/rust/issues/34666#issuecomment-675658420 |
| 56 | + self.txs.extend(other.txs); |
| 57 | + self.txouts.extend(other.txouts); |
| 58 | + self.anchors.extend(other.anchors); |
| 59 | + |
| 60 | + // last_seen timestamps should only increase |
| 61 | + self.last_seen.extend( |
| 62 | + other |
| 63 | + .last_seen |
| 64 | + .into_iter() |
| 65 | + .filter(|(txid, update_ls)| self.last_seen.get(txid) < Some(update_ls)) |
| 66 | + .collect::<Vec<_>>(), |
| 67 | + ); |
| 68 | + } |
| 69 | + |
| 70 | + fn is_empty(&self) -> bool { |
| 71 | + self.txs.is_empty() |
| 72 | + && self.txouts.is_empty() |
| 73 | + && self.anchors.is_empty() |
| 74 | + && self.last_seen.is_empty() |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments