Remove transaction-based type parameters and traits

This commit is contained in:
志宇
2023-03-08 11:39:25 +13:00
parent de9457fce6
commit 0505cd7242
12 changed files with 180 additions and 336 deletions

View File

@@ -3,7 +3,7 @@ use crate::{
collections::HashSet,
sparse_chain::{self, ChainPosition, SparseChain},
tx_graph::{self, TxGraph},
AsTransaction, BlockId, ForEachTxOut, FullTxOut, IntoOwned, TxHeight,
BlockId, ForEachTxOut, FullTxOut, TxHeight,
};
use alloc::{string::ToString, vec::Vec};
use bitcoin::{OutPoint, Transaction, TxOut, Txid};
@@ -25,12 +25,12 @@ use core::fmt::Debug;
/// `graph` but not the other way around. Transactions may fall out of the *chain* (via re-org or
/// mempool eviction) but will remain in the *graph*.
#[derive(Clone, Debug, PartialEq)]
pub struct ChainGraph<P = TxHeight, T = Transaction> {
pub struct ChainGraph<P = TxHeight> {
chain: SparseChain<P>,
graph: TxGraph<T>,
graph: TxGraph,
}
impl<P, T> Default for ChainGraph<P, T> {
impl<P> Default for ChainGraph<P> {
fn default() -> Self {
Self {
chain: Default::default(),
@@ -39,40 +39,39 @@ impl<P, T> Default for ChainGraph<P, T> {
}
}
impl<P, T> AsRef<SparseChain<P>> for ChainGraph<P, T> {
impl<P> AsRef<SparseChain<P>> for ChainGraph<P> {
fn as_ref(&self) -> &SparseChain<P> {
&self.chain
}
}
impl<P, T> AsRef<TxGraph<T>> for ChainGraph<P, T> {
fn as_ref(&self) -> &TxGraph<T> {
impl<P> AsRef<TxGraph> for ChainGraph<P> {
fn as_ref(&self) -> &TxGraph {
&self.graph
}
}
impl<P, T> AsRef<ChainGraph<P, T>> for ChainGraph<P, T> {
fn as_ref(&self) -> &ChainGraph<P, T> {
impl<P> AsRef<ChainGraph<P>> for ChainGraph<P> {
fn as_ref(&self) -> &ChainGraph<P> {
self
}
}
impl<P, T> ChainGraph<P, T> {
impl<P> ChainGraph<P> {
/// Returns a reference to the internal [`SparseChain`].
pub fn chain(&self) -> &SparseChain<P> {
&self.chain
}
/// Returns a reference to the internal [`TxGraph`].
pub fn graph(&self) -> &TxGraph<T> {
pub fn graph(&self) -> &TxGraph {
&self.graph
}
}
impl<P, T> ChainGraph<P, T>
impl<P> ChainGraph<P>
where
P: ChainPosition,
T: AsTransaction + Clone + Ord,
{
/// Create a new chain graph from a `chain` and a `graph`.
///
@@ -82,14 +81,12 @@ where
/// transaction in `graph`.
/// 2. The `chain` has two transactions that allegedly in it but they conflict in the `graph`
/// (so could not possibly be in the same chain).
pub fn new(chain: SparseChain<P>, graph: TxGraph<T>) -> Result<Self, NewError<P>> {
pub fn new(chain: SparseChain<P>, graph: TxGraph) -> Result<Self, NewError<P>> {
let mut missing = HashSet::default();
for (pos, txid) in chain.txids() {
if let Some(tx) = graph.get_tx(*txid) {
let conflict = graph
.walk_conflicts(tx.as_tx(), |_, txid| {
Some((chain.tx_position(txid)?.clone(), txid))
})
.walk_conflicts(tx, |_, txid| Some((chain.tx_position(txid)?.clone(), txid)))
.next();
if let Some((conflict_pos, conflict)) = conflict {
return Err(NewError::Conflict {
@@ -128,8 +125,8 @@ where
pub fn inflate_update(
&self,
update: SparseChain<P>,
new_txs: impl IntoIterator<Item = T>,
) -> Result<ChainGraph<P, T>, NewError<P>> {
new_txs: impl IntoIterator<Item = Transaction>,
) -> Result<ChainGraph<P>, NewError<P>> {
let mut inflated_chain = SparseChain::default();
let mut inflated_graph = TxGraph::default();
@@ -188,7 +185,7 @@ where
/// Determines the changes required to invalidate checkpoints `from_height` (inclusive) and
/// above. Displaced transactions will have their positions moved to [`TxHeight::Unconfirmed`].
pub fn invalidate_checkpoints_preview(&self, from_height: u32) -> ChangeSet<P, T> {
pub fn invalidate_checkpoints_preview(&self, from_height: u32) -> ChangeSet<P> {
ChangeSet {
chain: self.chain.invalidate_checkpoints_preview(from_height),
..Default::default()
@@ -200,9 +197,9 @@ where
///
/// This is equivalent to calling [`Self::invalidate_checkpoints_preview`] and
/// [`Self::apply_changeset`] in sequence.
pub fn invalidate_checkpoints(&mut self, from_height: u32) -> ChangeSet<P, T>
pub fn invalidate_checkpoints(&mut self, from_height: u32) -> ChangeSet<P>
where
ChangeSet<P, T>: Clone,
ChangeSet<P>: Clone,
{
let changeset = self.invalidate_checkpoints_preview(from_height);
self.apply_changeset(changeset.clone());
@@ -213,7 +210,7 @@ where
///
/// This does not necessarily mean that it is *confirmed* in the blockchain, it might just be in
/// the unconfirmed transaction list within the [`SparseChain`].
pub fn get_tx_in_chain(&self, txid: Txid) -> Option<(&P, &T)> {
pub fn get_tx_in_chain(&self, txid: Txid) -> Option<(&P, &Transaction)> {
let position = self.chain.tx_position(txid)?;
let full_tx = self.graph.get_tx(txid).expect("must exist");
Some((position, full_tx))
@@ -224,9 +221,13 @@ where
///
/// If inserting it into the chain `position` will result in conflicts, the returned
/// [`ChangeSet`] should evict conflicting transactions.
pub fn insert_tx_preview(&self, tx: T, pos: P) -> Result<ChangeSet<P, T>, InsertTxError<P>> {
pub fn insert_tx_preview(
&self,
tx: Transaction,
pos: P,
) -> Result<ChangeSet<P>, InsertTxError<P>> {
let mut changeset = ChangeSet {
chain: self.chain.insert_tx_preview(tx.as_tx().txid(), pos)?,
chain: self.chain.insert_tx_preview(tx.txid(), pos)?,
graph: self.graph.insert_tx_preview(tx),
};
self.fix_conflicts(&mut changeset)?;
@@ -237,14 +238,14 @@ where
///
/// This is equivalent to calling [`Self::insert_tx_preview`] and [`Self::apply_changeset`] in
/// sequence.
pub fn insert_tx(&mut self, tx: T, pos: P) -> Result<ChangeSet<P, T>, InsertTxError<P>> {
pub fn insert_tx(&mut self, tx: Transaction, pos: P) -> Result<ChangeSet<P>, InsertTxError<P>> {
let changeset = self.insert_tx_preview(tx, pos)?;
self.apply_changeset(changeset.clone());
Ok(changeset)
}
/// Determines the changes required to insert a [`TxOut`] into the internal [`TxGraph`].
pub fn insert_txout_preview(&self, outpoint: OutPoint, txout: TxOut) -> ChangeSet<P, T> {
pub fn insert_txout_preview(&self, outpoint: OutPoint, txout: TxOut) -> ChangeSet<P> {
ChangeSet {
chain: Default::default(),
graph: self.graph.insert_txout_preview(outpoint, txout),
@@ -255,7 +256,7 @@ where
///
/// This is equivalent to calling [`Self::insert_txout_preview`] and [`Self::apply_changeset`]
/// in sequence.
pub fn insert_txout(&mut self, outpoint: OutPoint, txout: TxOut) -> ChangeSet<P, T> {
pub fn insert_txout(&mut self, outpoint: OutPoint, txout: TxOut) -> ChangeSet<P> {
let changeset = self.insert_txout_preview(outpoint, txout);
self.apply_changeset(changeset.clone());
changeset
@@ -269,7 +270,7 @@ where
pub fn insert_checkpoint_preview(
&self,
block_id: BlockId,
) -> Result<ChangeSet<P, T>, InsertCheckpointError> {
) -> Result<ChangeSet<P>, InsertCheckpointError> {
self.chain
.insert_checkpoint_preview(block_id)
.map(|chain_changeset| ChangeSet {
@@ -285,20 +286,17 @@ where
pub fn insert_checkpoint(
&mut self,
block_id: BlockId,
) -> Result<ChangeSet<P, T>, InsertCheckpointError> {
) -> Result<ChangeSet<P>, InsertCheckpointError> {
let changeset = self.insert_checkpoint_preview(block_id)?;
self.apply_changeset(changeset.clone());
Ok(changeset)
}
/// Calculates the difference between self and `update` in the form of a [`ChangeSet`].
pub fn determine_changeset<T2>(
pub fn determine_changeset(
&self,
update: &ChainGraph<P, T2>,
) -> Result<ChangeSet<P, T>, UpdateError<P>>
where
T2: IntoOwned<T> + Clone,
{
update: &ChainGraph<P>,
) -> Result<ChangeSet<P>, UpdateError<P>> {
let chain_changeset = self
.chain
.determine_changeset(&update.chain)
@@ -333,10 +331,7 @@ where
///
/// **WARNING:** If there are any missing full txs, conflict resolution will not be complete. In
/// debug mode, this will result in panic.
fn fix_conflicts(
&self,
changeset: &mut ChangeSet<P, T>,
) -> Result<(), UnresolvableConflict<P>> {
fn fix_conflicts(&self, changeset: &mut ChangeSet<P>) -> Result<(), UnresolvableConflict<P>> {
let mut chain_conflicts = vec![];
for (&txid, pos_change) in &changeset.chain.txids {
@@ -355,11 +350,7 @@ where
let mut full_tx = self.graph.get_tx(txid);
if full_tx.is_none() {
full_tx = changeset
.graph
.tx
.iter()
.find(|tx| tx.as_tx().txid() == txid)
full_tx = changeset.graph.tx.iter().find(|tx| tx.txid() == txid)
}
debug_assert!(full_tx.is_some(), "should have full tx at this point");
@@ -369,7 +360,7 @@ where
None => continue,
};
for (conflict_pos, conflict_txid) in self.tx_conflicts_in_chain(full_tx.as_tx()) {
for (conflict_pos, conflict_txid) in self.tx_conflicts_in_chain(full_tx) {
chain_conflicts.push((pos.clone(), txid, conflict_pos, conflict_txid))
}
}
@@ -416,17 +407,14 @@ where
///
/// **Warning** this method assumes the changeset is assumed to be correctly formed. If it isn't
/// then the chain graph may not behave correctly in the future and may panic unexpectedly.
pub fn apply_changeset(&mut self, changeset: ChangeSet<P, T>) {
pub fn apply_changeset(&mut self, changeset: ChangeSet<P>) {
self.chain.apply_changeset(changeset.chain);
self.graph.apply_additions(changeset.graph);
}
/// Applies the `update` chain graph. Note this is shorthand for calling
/// [`Self::determine_changeset()`] and [`Self::apply_changeset()`] in sequence.
pub fn apply_update<T2: IntoOwned<T> + Clone>(
&mut self,
update: ChainGraph<P, T2>,
) -> Result<ChangeSet<P, T>, UpdateError<P>> {
pub fn apply_update(&mut self, update: ChainGraph<P>) -> Result<ChangeSet<P>, UpdateError<P>> {
let changeset = self.determine_changeset(&update)?;
self.apply_changeset(changeset.clone());
Ok(changeset)
@@ -439,7 +427,7 @@ where
/// Iterate over the full transactions and their position in the chain ordered by their position
/// in ascending order.
pub fn transactions_in_chain(&self) -> impl DoubleEndedIterator<Item = (&P, &T)> {
pub fn transactions_in_chain(&self) -> impl DoubleEndedIterator<Item = (&P, &Transaction)> {
self.chain
.txids()
.map(move |(pos, txid)| (pos, self.graph.get_tx(*txid).expect("must exist")))
@@ -468,18 +456,18 @@ where
serde(
crate = "serde_crate",
bound(
deserialize = "P: serde::Deserialize<'de>, T: Ord + serde::Deserialize<'de>",
serialize = "P: serde::Serialize, T: Ord + serde::Serialize"
deserialize = "P: serde::Deserialize<'de>",
serialize = "P: serde::Serialize"
)
)
)]
#[must_use]
pub struct ChangeSet<P, T> {
pub struct ChangeSet<P> {
pub chain: sparse_chain::ChangeSet<P>,
pub graph: tx_graph::Additions<T>,
pub graph: tx_graph::Additions,
}
impl<P, T> ChangeSet<P, T> {
impl<P> ChangeSet<P> {
/// Returns `true` if this [`ChangeSet`] records no changes.
pub fn is_empty(&self) -> bool {
self.chain.is_empty() && self.graph.is_empty()
@@ -495,17 +483,16 @@ impl<P, T> ChangeSet<P, T> {
/// Appends the changes in `other` into self such that applying `self` afterwards has the same
/// effect as sequentially applying the original `self` and `other`.
pub fn append(&mut self, other: ChangeSet<P, T>)
pub fn append(&mut self, other: ChangeSet<P>)
where
P: ChainPosition,
T: Ord,
{
self.chain.append(other.chain);
self.graph.append(other.graph);
}
}
impl<P, T> Default for ChangeSet<P, T> {
impl<P> Default for ChangeSet<P> {
fn default() -> Self {
Self {
chain: Default::default(),
@@ -514,13 +501,13 @@ impl<P, T> Default for ChangeSet<P, T> {
}
}
impl<P, T: AsTransaction> ForEachTxOut for ChainGraph<P, T> {
impl<P> ForEachTxOut for ChainGraph<P> {
fn for_each_txout(&self, f: impl FnMut((OutPoint, &TxOut))) {
self.graph.for_each_txout(f)
}
}
impl<P, T: AsTransaction> ForEachTxOut for ChangeSet<P, T> {
impl<P> ForEachTxOut for ChangeSet<P> {
fn for_each_txout(&self, f: impl FnMut((OutPoint, &TxOut))) {
self.graph.for_each_txout(f)
}

View File

@@ -19,9 +19,8 @@ use crate::{
collections::BTreeMap,
sparse_chain::ChainPosition,
tx_graph::TxGraph,
AsTransaction, ForEachTxOut,
ForEachTxOut,
};
use bitcoin::Transaction;
#[cfg(feature = "miniscript")]
pub mod persist;
@@ -100,14 +99,14 @@ impl<K> AsRef<BTreeMap<K, u32>> for DerivationAdditions<K> {
#[derive(Clone, Debug, PartialEq)]
/// An update that includes the last active indexes of each keychain.
pub struct KeychainScan<K, P, T = Transaction> {
pub struct KeychainScan<K, P> {
/// The update data in the form of a chain that could be applied
pub update: ChainGraph<P, T>,
pub update: ChainGraph<P>,
/// The last active indexes of each keychain
pub last_active_indices: BTreeMap<K, u32>,
}
impl<K, P, T> Default for KeychainScan<K, P, T> {
impl<K, P> Default for KeychainScan<K, P> {
fn default() -> Self {
Self {
update: Default::default(),
@@ -116,8 +115,8 @@ impl<K, P, T> Default for KeychainScan<K, P, T> {
}
}
impl<K, P, T> From<ChainGraph<P, T>> for KeychainScan<K, P, T> {
fn from(update: ChainGraph<P, T>) -> Self {
impl<K, P> From<ChainGraph<P>> for KeychainScan<K, P> {
fn from(update: ChainGraph<P>) -> Self {
KeychainScan {
update,
last_active_indices: Default::default(),
@@ -135,20 +134,20 @@ impl<K, P, T> From<ChainGraph<P, T>> for KeychainScan<K, P, T> {
serde(
crate = "serde_crate",
bound(
deserialize = "K: Ord + serde::Deserialize<'de>, P: serde::Deserialize<'de>, T: Ord + serde::Deserialize<'de>",
serialize = "K: Ord + serde::Serialize, P: serde::Serialize, T: Ord+ serde::Serialize"
deserialize = "K: Ord + serde::Deserialize<'de>, P: serde::Deserialize<'de>",
serialize = "K: Ord + serde::Serialize, P: serde::Serialize"
)
)
)]
#[must_use]
pub struct KeychainChangeSet<K, P, T = Transaction> {
pub struct KeychainChangeSet<K, P> {
/// The changes in local keychain derivation indices
pub derivation_indices: DerivationAdditions<K>,
/// The changes that have occurred in the blockchain
pub chain_graph: chain_graph::ChangeSet<P, T>,
pub chain_graph: chain_graph::ChangeSet<P>,
}
impl<K, P, T> Default for KeychainChangeSet<K, P, T> {
impl<K, P> Default for KeychainChangeSet<K, P> {
fn default() -> Self {
Self {
chain_graph: Default::default(),
@@ -157,7 +156,7 @@ impl<K, P, T> Default for KeychainChangeSet<K, P, T> {
}
}
impl<K, P, T> KeychainChangeSet<K, P, T> {
impl<K, P> KeychainChangeSet<K, P> {
/// Returns whether the [`KeychainChangeSet`] is empty (no changes recorded).
pub fn is_empty(&self) -> bool {
self.chain_graph.is_empty() && self.derivation_indices.is_empty()
@@ -168,19 +167,18 @@ impl<K, P, T> KeychainChangeSet<K, P, T> {
///
/// Note the derivation indices cannot be decreased so `other` will only change the derivation
/// index for a keychain if it's entry is higher than the one in `self`.
pub fn append(&mut self, other: KeychainChangeSet<K, P, T>)
pub fn append(&mut self, other: KeychainChangeSet<K, P>)
where
K: Ord,
P: ChainPosition,
T: Ord,
{
self.derivation_indices.append(other.derivation_indices);
self.chain_graph.append(other.chain_graph);
}
}
impl<K, P, T> From<chain_graph::ChangeSet<P, T>> for KeychainChangeSet<K, P, T> {
fn from(changeset: chain_graph::ChangeSet<P, T>) -> Self {
impl<K, P> From<chain_graph::ChangeSet<P>> for KeychainChangeSet<K, P> {
fn from(changeset: chain_graph::ChangeSet<P>) -> Self {
Self {
chain_graph: changeset,
..Default::default()
@@ -188,7 +186,7 @@ impl<K, P, T> From<chain_graph::ChangeSet<P, T>> for KeychainChangeSet<K, P, T>
}
}
impl<K, P, T> From<DerivationAdditions<K>> for KeychainChangeSet<K, P, T> {
impl<K, P> From<DerivationAdditions<K>> for KeychainChangeSet<K, P> {
fn from(additions: DerivationAdditions<K>) -> Self {
Self {
derivation_indices: additions,
@@ -197,13 +195,13 @@ impl<K, P, T> From<DerivationAdditions<K>> for KeychainChangeSet<K, P, T> {
}
}
impl<K, P, T> AsRef<TxGraph<T>> for KeychainScan<K, P, T> {
fn as_ref(&self) -> &TxGraph<T> {
impl<K, P> AsRef<TxGraph> for KeychainScan<K, P> {
fn as_ref(&self) -> &TxGraph {
self.update.graph()
}
}
impl<K, P, T: AsTransaction> ForEachTxOut for KeychainChangeSet<K, P, T> {
impl<K, P> ForEachTxOut for KeychainChangeSet<K, P> {
fn for_each_txout(&self, f: impl FnMut((bitcoin::OutPoint, &bitcoin::TxOut))) {
self.chain_graph.for_each_txout(f)
}
@@ -267,8 +265,6 @@ impl core::ops::Add for Balance {
#[cfg(test)]
mod test {
use bitcoin::Transaction;
use crate::TxHeight;
use super::*;
@@ -291,12 +287,12 @@ mod test {
rhs_di.insert(Keychain::Four, 4);
let mut lhs = KeychainChangeSet {
derivation_indices: DerivationAdditions(lhs_di),
chain_graph: chain_graph::ChangeSet::<TxHeight, Transaction>::default(),
chain_graph: chain_graph::ChangeSet::<TxHeight>::default(),
};
let rhs = KeychainChangeSet {
derivation_indices: DerivationAdditions(rhs_di),
chain_graph: chain_graph::ChangeSet::<TxHeight, Transaction>::default(),
chain_graph: chain_graph::ChangeSet::<TxHeight>::default(),
};
lhs.append(rhs);

View File

@@ -7,7 +7,7 @@ use crate::{
keychain::{KeychainChangeSet, KeychainScan, KeychainTxOutIndex},
sparse_chain::{self, SparseChain},
tx_graph::TxGraph,
AsTransaction, BlockId, FullTxOut, IntoOwned, TxHeight,
BlockId, FullTxOut, TxHeight,
};
use super::{Balance, DerivationAdditions};
@@ -17,17 +17,16 @@ use super::{Balance, DerivationAdditions};
/// The [`KeychainTracker`] atomically updates its [`KeychainTxOutIndex`] whenever new chain data is
/// incorporated into its internal [`ChainGraph`].
#[derive(Clone, Debug)]
pub struct KeychainTracker<K, P, T = Transaction> {
pub struct KeychainTracker<K, P> {
/// Index between script pubkeys to transaction outputs
pub txout_index: KeychainTxOutIndex<K>,
chain_graph: ChainGraph<P, T>,
chain_graph: ChainGraph<P>,
}
impl<K, P, T> KeychainTracker<K, P, T>
impl<K, P> KeychainTracker<K, P>
where
P: sparse_chain::ChainPosition,
K: Ord + Clone + core::fmt::Debug,
T: AsTransaction + Clone + Ord,
{
/// Add a keychain to the tracker's `txout_index` with a descriptor to derive addresses for it.
/// This is just shorthand for calling [`KeychainTxOutIndex::add_keychain`] on the internal
@@ -63,13 +62,10 @@ where
///
/// Internally, we call [`ChainGraph::determine_changeset`] and also determine the additions of
/// [`KeychainTxOutIndex`].
pub fn determine_changeset<T2>(
pub fn determine_changeset(
&self,
scan: &KeychainScan<K, P, T2>,
) -> Result<KeychainChangeSet<K, P, T>, chain_graph::UpdateError<P>>
where
T2: IntoOwned<T> + Clone,
{
scan: &KeychainScan<K, P>,
) -> Result<KeychainChangeSet<K, P>, chain_graph::UpdateError<P>> {
// TODO: `KeychainTxOutIndex::determine_additions`
let mut derivation_indices = scan.last_active_indices.clone();
derivation_indices.retain(|keychain, index| {
@@ -91,13 +87,10 @@ where
///
/// [`determine_changeset`]: Self::determine_changeset
/// [`apply_changeset`]: Self::apply_changeset
pub fn apply_update<T2>(
pub fn apply_update(
&mut self,
scan: KeychainScan<K, P, T2>,
) -> Result<KeychainChangeSet<K, P, T>, chain_graph::UpdateError<P>>
where
T2: IntoOwned<T> + Clone,
{
scan: KeychainScan<K, P>,
) -> Result<KeychainChangeSet<K, P>, chain_graph::UpdateError<P>> {
let changeset = self.determine_changeset(&scan)?;
self.apply_changeset(changeset.clone());
Ok(changeset)
@@ -107,7 +100,7 @@ where
///
/// Internally, this calls [`KeychainTxOutIndex::apply_additions`] and
/// [`ChainGraph::apply_changeset`] in sequence.
pub fn apply_changeset(&mut self, changeset: KeychainChangeSet<K, P, T>) {
pub fn apply_changeset(&mut self, changeset: KeychainChangeSet<K, P>) {
let KeychainChangeSet {
derivation_indices,
chain_graph,
@@ -139,12 +132,12 @@ where
}
/// Returns a reference to the internal [`ChainGraph`].
pub fn chain_graph(&self) -> &ChainGraph<P, T> {
pub fn chain_graph(&self) -> &ChainGraph<P> {
&self.chain_graph
}
/// Returns a reference to the internal [`TxGraph`] (which is part of the [`ChainGraph`]).
pub fn graph(&self) -> &TxGraph<T> {
pub fn graph(&self) -> &TxGraph {
self.chain_graph().graph()
}
@@ -166,7 +159,7 @@ where
pub fn insert_checkpoint_preview(
&self,
block_id: BlockId,
) -> Result<KeychainChangeSet<K, P, T>, chain_graph::InsertCheckpointError> {
) -> Result<KeychainChangeSet<K, P>, chain_graph::InsertCheckpointError> {
Ok(KeychainChangeSet {
chain_graph: self.chain_graph.insert_checkpoint_preview(block_id)?,
..Default::default()
@@ -183,7 +176,7 @@ where
pub fn insert_checkpoint(
&mut self,
block_id: BlockId,
) -> Result<KeychainChangeSet<K, P, T>, chain_graph::InsertCheckpointError> {
) -> Result<KeychainChangeSet<K, P>, chain_graph::InsertCheckpointError> {
let changeset = self.insert_checkpoint_preview(block_id)?;
self.apply_changeset(changeset.clone());
Ok(changeset)
@@ -196,9 +189,9 @@ where
/// responsible for persisting these changes to disk if you need to restore them.
pub fn insert_tx_preview(
&self,
tx: T,
tx: Transaction,
pos: P,
) -> Result<KeychainChangeSet<K, P, T>, chain_graph::InsertTxError<P>> {
) -> Result<KeychainChangeSet<K, P>, chain_graph::InsertTxError<P>> {
Ok(KeychainChangeSet {
chain_graph: self.chain_graph.insert_tx_preview(tx, pos)?,
..Default::default()
@@ -214,9 +207,9 @@ where
/// [`apply_changeset`]: Self::apply_changeset
pub fn insert_tx(
&mut self,
tx: T,
tx: Transaction,
pos: P,
) -> Result<KeychainChangeSet<K, P, T>, chain_graph::InsertTxError<P>> {
) -> Result<KeychainChangeSet<K, P>, chain_graph::InsertTxError<P>> {
let changeset = self.insert_tx_preview(tx, pos)?;
self.apply_changeset(changeset.clone());
Ok(changeset)

View File

@@ -311,7 +311,7 @@ use core::{
ops::{Bound, RangeBounds},
};
use crate::{collections::*, tx_graph::TxGraph, AsTransaction, BlockId, FullTxOut, TxHeight};
use crate::{collections::*, tx_graph::TxGraph, BlockId, FullTxOut, TxHeight};
use bitcoin::{hashes::Hash, BlockHash, OutPoint, Txid};
/// This is a non-monotone structure that tracks relevant [`Txid`]s that are ordered by chain
@@ -899,16 +899,12 @@ impl<P: ChainPosition> SparseChain<P> {
/// Attempt to retrieve a [`FullTxOut`] of the given `outpoint`.
///
/// This will return `Some` only if the output's transaction is in both `self` and `graph`.
pub fn full_txout(
&self,
graph: &TxGraph<impl AsTransaction>,
outpoint: OutPoint,
) -> Option<FullTxOut<P>> {
pub fn full_txout(&self, graph: &TxGraph, outpoint: OutPoint) -> Option<FullTxOut<P>> {
let chain_pos = self.tx_position(outpoint.txid)?;
let tx = graph.get_tx(outpoint.txid)?;
let is_on_coinbase = tx.as_tx().is_coin_base();
let txout = tx.as_tx().output.get(outpoint.vout as usize)?.clone();
let is_on_coinbase = tx.is_coin_base();
let txout = tx.output.get(outpoint.vout as usize)?.clone();
let spent_by = self
.spent_by(graph, outpoint)
@@ -976,7 +972,7 @@ impl<P: ChainPosition> SparseChain<P> {
///
/// Note that the transaction including `outpoint` does not need to be in the `graph` or the
/// `chain` for this to return `Some`.
pub fn spent_by<T>(&self, graph: &TxGraph<T>, outpoint: OutPoint) -> Option<(&P, Txid)> {
pub fn spent_by(&self, graph: &TxGraph, outpoint: OutPoint) -> Option<(&P, Txid)> {
graph
.outspends(outpoint)
.iter()

View File

@@ -1,6 +1,3 @@
use core::borrow::Borrow;
use alloc::{borrow::Cow, boxed::Box, rc::Rc, sync::Arc};
use bitcoin::{Block, OutPoint, Transaction, TxOut};
/// Trait to do something with every txout contained in a structure.
@@ -20,58 +17,10 @@ impl ForEachTxOut for Block {
}
}
/// Trait for things that have a single [`Transaction`] in them.
///
/// This alows polymorphism in structures such as [`TxGraph<T>`] where `T` can be anything that
/// implements `AsTransaction`. You might think that we could just use [`core::convert::AsRef`] for
/// this but the problem is that we need to implement it on `Cow<T>` where `T: AsTransaction` which
/// we can't do with a foreign trait like `AsTransaction`.
///
/// [`Transaction`]: bitcoin::Transaction
/// [`TxGraph<T>`]: crate::tx_graph::TxGraph
pub trait AsTransaction {
/// Get a reference to the transaction.
fn as_tx(&self) -> &Transaction;
}
impl AsTransaction for Transaction {
fn as_tx(&self) -> &Transaction {
self
}
}
impl<T: AsTransaction> AsTransaction for Rc<T> {
fn as_tx(&self) -> &Transaction {
self.as_ref().as_tx()
}
}
impl<T: AsTransaction> AsTransaction for Arc<T> {
fn as_tx(&self) -> &Transaction {
self.as_ref().as_tx()
}
}
impl<T: AsTransaction> AsTransaction for Box<T> {
fn as_tx(&self) -> &Transaction {
self.as_ref().as_tx()
}
}
impl<'a, T: AsTransaction + Clone> AsTransaction for Cow<'a, T> {
fn as_tx(&self) -> &Transaction {
<Cow<'_, T> as Borrow<T>>::borrow(self).as_tx()
}
}
impl<T> ForEachTxOut for T
where
T: AsTransaction,
{
impl ForEachTxOut for Transaction {
fn for_each_txout(&self, mut f: impl FnMut((OutPoint, &TxOut))) {
let tx = self.as_tx();
let txid = tx.txid();
for (i, txout) in tx.output.iter().enumerate() {
let txid = self.txid();
for (i, txout) in self.output.iter().enumerate() {
f((
OutPoint {
txid,
@@ -82,34 +31,3 @@ where
}
}
}
/// A trait like [`core::convert::Into`] for converting one thing into another.
///
/// We use it to convert one transaction type into another so that an update for `T2` can be used on
/// a `TxGraph<T1>` as long as `T2: IntoOwned<T1>`.
///
/// We couldn't use `Into` because we needed to implement it for [`Cow<'a, T>`].
///
/// [`Cow<'a, T>`]: std::borrow::Cow
pub trait IntoOwned<T> {
/// Converts the provided type into another (owned) type.
fn into_owned(self) -> T;
}
impl<T> IntoOwned<T> for T {
fn into_owned(self) -> T {
self
}
}
impl<'a, T: Clone> IntoOwned<T> for Cow<'a, T> {
fn into_owned(self) -> T {
Cow::into_owned(self)
}
}
impl<'a, T: Clone> IntoOwned<T> for &'a T {
fn into_owned(self) -> T {
self.clone()
}
}

View File

@@ -20,7 +20,7 @@
//! # use bitcoin::Transaction;
//! # let tx_a = tx_from_hex(RAW_TX_1);
//! # let tx_b = tx_from_hex(RAW_TX_2);
//! let mut graph = TxGraph::<Transaction>::default();
//! let mut graph = TxGraph::default();
//!
//! // preview a transaction insertion (not actually inserted)
//! let additions = graph.insert_tx_preview(tx_a);
@@ -39,8 +39,8 @@
//! # use bitcoin::Transaction;
//! # let tx_a = tx_from_hex(RAW_TX_1);
//! # let tx_b = tx_from_hex(RAW_TX_2);
//! let mut graph = TxGraph::<Transaction>::default();
//! let update = TxGraph::<Transaction>::new(vec![tx_a, tx_b]);
//! let mut graph = TxGraph::default();
//! let update = TxGraph::new(vec![tx_a, tx_b]);
//!
//! // preview additions as result of the update
//! let additions = graph.determine_additions(&update);
@@ -52,7 +52,7 @@
//! let additions = graph.apply_update(update);
//! assert!(additions.is_empty());
//! ```
use crate::{collections::*, AsTransaction, ForEachTxOut, IntoOwned};
use crate::{collections::*, ForEachTxOut};
use alloc::vec::Vec;
use bitcoin::{OutPoint, Transaction, TxOut, Txid};
use core::ops::RangeInclusive;
@@ -63,8 +63,8 @@ use core::ops::RangeInclusive;
///
/// [module-level documentation]: crate::tx_graph
#[derive(Clone, Debug, PartialEq)]
pub struct TxGraph<T = Transaction> {
txs: HashMap<Txid, TxNode<T>>,
pub struct TxGraph {
txs: HashMap<Txid, TxNode>,
spends: BTreeMap<OutPoint, HashSet<Txid>>,
// This atrocity exists so that `TxGraph::outspends()` can return a reference.
@@ -72,7 +72,7 @@ pub struct TxGraph<T = Transaction> {
empty_outspends: HashSet<Txid>,
}
impl<T> Default for TxGraph<T> {
impl Default for TxGraph {
fn default() -> Self {
Self {
txs: Default::default(),
@@ -85,23 +85,22 @@ impl<T> Default for TxGraph<T> {
/// Node of a [`TxGraph`]. This can either be a whole transaction, or a partial transaction (where
/// we only have select outputs).
#[derive(Clone, Debug, PartialEq)]
enum TxNode<T = Transaction> {
Whole(T),
enum TxNode {
Whole(Transaction),
Partial(BTreeMap<u32, TxOut>),
}
impl<T> Default for TxNode<T> {
impl Default for TxNode {
fn default() -> Self {
Self::Partial(BTreeMap::new())
}
}
impl<T: AsTransaction> TxGraph<T> {
impl TxGraph {
/// Iterate over all tx outputs known by [`TxGraph`].
pub fn all_txouts(&self) -> impl Iterator<Item = (OutPoint, &TxOut)> {
self.txs.iter().flat_map(|(txid, tx)| match tx {
TxNode::Whole(tx) => tx
.as_tx()
.output
.iter()
.enumerate()
@@ -115,7 +114,7 @@ impl<T: AsTransaction> TxGraph<T> {
}
/// Iterate over all full transactions in the graph.
pub fn full_transactions(&self) -> impl Iterator<Item = &T> {
pub fn full_transactions(&self) -> impl Iterator<Item = &Transaction> {
self.txs.iter().filter_map(|(_, tx)| match tx {
TxNode::Whole(tx) => Some(tx),
TxNode::Partial(_) => None,
@@ -127,7 +126,7 @@ impl<T: AsTransaction> TxGraph<T> {
/// Refer to [`get_txout`] for getting a specific [`TxOut`].
///
/// [`get_txout`]: Self::get_txout
pub fn get_tx(&self, txid: Txid) -> Option<&T> {
pub fn get_tx(&self, txid: Txid) -> Option<&Transaction> {
match self.txs.get(&txid)? {
TxNode::Whole(tx) => Some(tx),
TxNode::Partial(_) => None,
@@ -137,7 +136,7 @@ impl<T: AsTransaction> TxGraph<T> {
/// Obtains a single tx output (if any) at specified outpoint.
pub fn get_txout(&self, outpoint: OutPoint) -> Option<&TxOut> {
match self.txs.get(&outpoint.txid)? {
TxNode::Whole(tx) => tx.as_tx().output.get(outpoint.vout as usize),
TxNode::Whole(tx) => tx.output.get(outpoint.vout as usize),
TxNode::Partial(txouts) => txouts.get(&outpoint.vout),
}
}
@@ -146,7 +145,6 @@ impl<T: AsTransaction> TxGraph<T> {
pub fn txouts(&self, txid: Txid) -> Option<BTreeMap<u32, &TxOut>> {
Some(match self.txs.get(&txid)? {
TxNode::Whole(tx) => tx
.as_tx()
.output
.iter()
.enumerate()
@@ -190,9 +188,9 @@ impl<T: AsTransaction> TxGraph<T> {
}
}
impl<T: AsTransaction + Ord + Clone> TxGraph<T> {
impl TxGraph {
/// Contruct a new [`TxGraph`] from a list of transaction.
pub fn new(txs: impl IntoIterator<Item = T>) -> Self {
pub fn new(txs: impl IntoIterator<Item = Transaction>) -> Self {
let mut new = Self::default();
for tx in txs.into_iter() {
let _ = new.insert_tx(tx);
@@ -203,7 +201,7 @@ impl<T: AsTransaction + Ord + Clone> TxGraph<T> {
///
/// Note this will ignore the action if we already have the full transaction that the txout is
/// alledged to be on (even if it doesn't match it!).
pub fn insert_txout(&mut self, outpoint: OutPoint, txout: TxOut) -> Additions<T> {
pub fn insert_txout(&mut self, outpoint: OutPoint, txout: TxOut) -> Additions {
let additions = self.insert_txout_preview(outpoint, txout);
self.apply_additions(additions.clone());
additions
@@ -212,7 +210,7 @@ impl<T: AsTransaction + Ord + Clone> TxGraph<T> {
/// Inserts the given transaction into [`TxGraph`].
///
/// The [`Additions`] returned will be empty if `tx` already exists.
pub fn insert_tx(&mut self, tx: T) -> Additions<T> {
pub fn insert_tx(&mut self, tx: Transaction) -> Additions {
let additions = self.insert_tx_preview(tx);
self.apply_additions(additions.clone());
additions
@@ -223,22 +221,18 @@ impl<T: AsTransaction + Ord + Clone> TxGraph<T> {
///
/// The returned [`Additions`] is the set difference of `update` and `self` (transactions that
/// exist in `update` but not in `self`).
pub fn apply_update<T2>(&mut self, update: TxGraph<T2>) -> Additions<T>
where
T2: IntoOwned<T> + Clone,
{
pub fn apply_update(&mut self, update: TxGraph) -> Additions {
let additions = self.determine_additions(&update);
self.apply_additions(additions.clone());
additions
}
/// Applies [`Additions`] to [`TxGraph`].
pub fn apply_additions(&mut self, additions: Additions<T>) {
pub fn apply_additions(&mut self, additions: Additions) {
for tx in additions.tx {
let txid = tx.as_tx().txid();
let txid = tx.txid();
tx.as_tx()
.input
tx.input
.iter()
.map(|txin| txin.previous_output)
// coinbase spends are not to be counted
@@ -250,7 +244,7 @@ impl<T: AsTransaction + Ord + Clone> TxGraph<T> {
if let Some(TxNode::Whole(old_tx)) = self.txs.insert(txid, TxNode::Whole(tx)) {
debug_assert_eq!(
old_tx.as_tx().txid(),
old_tx.txid(),
txid,
"old tx of same txid should not be different"
);
@@ -276,11 +270,8 @@ impl<T: AsTransaction + Ord + Clone> TxGraph<T> {
///
/// The [`Additions`] would be the set difference of `update` and `self` (transactions that
/// exist in `update` but not in `self`).
pub fn determine_additions<T2>(&self, update: &TxGraph<T2>) -> Additions<T>
where
T2: IntoOwned<T> + Clone,
{
let mut additions = Additions::<T>::default();
pub fn determine_additions(&self, update: &TxGraph) -> Additions {
let mut additions = Additions::default();
for (&txid, update_tx) in &update.txs {
if self.get_tx(txid).is_some() {
@@ -290,9 +281,7 @@ impl<T: AsTransaction + Ord + Clone> TxGraph<T> {
match update_tx {
TxNode::Whole(tx) => {
if matches!(self.txs.get(&txid), None | Some(TxNode::Partial(_))) {
additions
.tx
.insert(<T2 as IntoOwned<T>>::into_owned(tx.clone()));
additions.tx.insert(tx.clone());
}
}
TxNode::Partial(partial) => {
@@ -314,9 +303,9 @@ impl<T: AsTransaction + Ord + Clone> TxGraph<T> {
/// mutate [`Self`].
///
/// The [`Additions`] result will be empty if `tx` already existed in `self`.
pub fn insert_tx_preview(&self, tx: T) -> Additions<T> {
pub fn insert_tx_preview(&self, tx: Transaction) -> Additions {
let mut update = Self::default();
update.txs.insert(tx.as_tx().txid(), TxNode::Whole(tx));
update.txs.insert(tx.txid(), TxNode::Whole(tx));
self.determine_additions(&update)
}
@@ -325,7 +314,7 @@ impl<T: AsTransaction + Ord + Clone> TxGraph<T> {
///
/// The [`Additions`] result will be empty if the `outpoint` (or a full transaction containing
/// the `outpoint`) already existed in `self`.
pub fn insert_txout_preview(&self, outpoint: OutPoint, txout: TxOut) -> Additions<T> {
pub fn insert_txout_preview(&self, outpoint: OutPoint, txout: TxOut) -> Additions {
let mut update = Self::default();
update.txs.insert(
outpoint.txid,
@@ -335,7 +324,7 @@ impl<T: AsTransaction + Ord + Clone> TxGraph<T> {
}
}
impl<T> TxGraph<T> {
impl TxGraph {
/// The transactions spending from this output.
///
/// `TxGraph` allows conflicting transactions within the graph. Obviously the transactions in
@@ -382,7 +371,7 @@ impl<T> TxGraph<T> {
///
/// The supplied closure returns an `Option<T>`, allowing the caller to map each node it vists
/// and decide whether to visit descendants.
pub fn walk_descendants<'g, F, O>(&'g self, txid: Txid, walk_map: F) -> TxDescendants<F, T>
pub fn walk_descendants<'g, F, O>(&'g self, txid: Txid, walk_map: F) -> TxDescendants<F>
where
F: FnMut(usize, Txid) -> Option<O> + 'g,
{
@@ -393,11 +382,7 @@ impl<T> TxGraph<T> {
/// descendants of directly-conflicting transactions, which are also considered conflicts).
///
/// Refer to [`Self::walk_descendants`] for `walk_map` usage.
pub fn walk_conflicts<'g, F, O>(
&'g self,
tx: &'g Transaction,
walk_map: F,
) -> TxDescendants<F, T>
pub fn walk_conflicts<'g, F, O>(&'g self, tx: &'g Transaction, walk_map: F) -> TxDescendants<F>
where
F: FnMut(usize, Txid) -> Option<O> + 'g,
{
@@ -442,55 +427,42 @@ impl<T> TxGraph<T> {
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
serde(
crate = "serde_crate",
bound(
deserialize = "T: Ord + serde::Deserialize<'de>",
serialize = "T: Ord + serde::Serialize"
)
)
serde(crate = "serde_crate")
)]
#[must_use]
pub struct Additions<T> {
pub tx: BTreeSet<T>,
pub struct Additions {
pub tx: BTreeSet<Transaction>,
pub txout: BTreeMap<OutPoint, TxOut>,
}
impl<T> Additions<T> {
impl Additions {
/// Returns true if the [`Additions`] is empty (no transactions or txouts).
pub fn is_empty(&self) -> bool {
self.tx.is_empty() && self.txout.is_empty()
}
/// Iterates over all outpoints contained within [`Additions`].
pub fn txouts(&self) -> impl Iterator<Item = (OutPoint, &TxOut)>
where
T: AsTransaction,
{
pub fn txouts(&self) -> impl Iterator<Item = (OutPoint, &TxOut)> {
self.tx
.iter()
.flat_map(|tx| {
tx.as_tx()
.output
tx.output
.iter()
.enumerate()
.map(move |(vout, txout)| (OutPoint::new(tx.as_tx().txid(), vout as _), txout))
.map(move |(vout, txout)| (OutPoint::new(tx.txid(), vout as _), txout))
})
.chain(self.txout.iter().map(|(op, txout)| (*op, txout)))
}
/// Appends the changes in `other` into self such that applying `self` afterwards has the same
/// effect as sequentially applying the original `self` and `other`.
pub fn append(&mut self, mut other: Additions<T>)
where
T: Ord,
{
pub fn append(&mut self, mut other: Additions) {
self.tx.append(&mut other.tx);
self.txout.append(&mut other.txout);
}
}
impl<T> Default for Additions<T> {
impl Default for Additions {
fn default() -> Self {
Self {
tx: Default::default(),
@@ -505,13 +477,13 @@ impl AsRef<TxGraph> for TxGraph {
}
}
impl<T: AsTransaction> ForEachTxOut for Additions<T> {
impl ForEachTxOut for Additions {
fn for_each_txout(&self, f: impl FnMut((OutPoint, &TxOut))) {
self.txouts().for_each(f)
}
}
impl<T: AsTransaction> ForEachTxOut for TxGraph<T> {
impl ForEachTxOut for TxGraph {
fn for_each_txout(&self, f: impl FnMut((OutPoint, &TxOut))) {
self.all_txouts().for_each(f)
}
@@ -522,17 +494,17 @@ impl<T: AsTransaction> ForEachTxOut for TxGraph<T> {
/// This `struct` is created by the [`walk_descendants`] method of [`TxGraph`].
///
/// [`walk_descendants`]: TxGraph::walk_descendants
pub struct TxDescendants<'g, F, T> {
graph: &'g TxGraph<T>,
pub struct TxDescendants<'g, F> {
graph: &'g TxGraph,
visited: HashSet<Txid>,
stack: Vec<(usize, Txid)>,
filter_map: F,
}
impl<'g, F, T> TxDescendants<'g, F, T> {
impl<'g, F> TxDescendants<'g, F> {
/// Creates a `TxDescendants` that includes the starting `txid` when iterating.
#[allow(unused)]
pub(crate) fn new_include_root(graph: &'g TxGraph<T>, txid: Txid, filter_map: F) -> Self {
pub(crate) fn new_include_root(graph: &'g TxGraph, txid: Txid, filter_map: F) -> Self {
Self {
graph,
visited: Default::default(),
@@ -542,7 +514,7 @@ impl<'g, F, T> TxDescendants<'g, F, T> {
}
/// Creates a `TxDescendants` that excludes the starting `txid` when iterating.
pub(crate) fn new_exclude_root(graph: &'g TxGraph<T>, txid: Txid, filter_map: F) -> Self {
pub(crate) fn new_exclude_root(graph: &'g TxGraph, txid: Txid, filter_map: F) -> Self {
let mut descendants = Self {
graph,
visited: Default::default(),
@@ -555,11 +527,7 @@ impl<'g, F, T> TxDescendants<'g, F, T> {
/// Creates a `TxDescendants` from multiple starting transactions that includes the starting
/// `txid`s when iterating.
pub(crate) fn from_multiple_include_root<I>(
graph: &'g TxGraph<T>,
txids: I,
filter_map: F,
) -> Self
pub(crate) fn from_multiple_include_root<I>(graph: &'g TxGraph, txids: I, filter_map: F) -> Self
where
I: IntoIterator<Item = Txid>,
{
@@ -574,11 +542,7 @@ impl<'g, F, T> TxDescendants<'g, F, T> {
/// Creates a `TxDescendants` from multiple starting transactions that excludes the starting
/// `txid`s when iterating.
#[allow(unused)]
pub(crate) fn from_multiple_exclude_root<I>(
graph: &'g TxGraph<T>,
txids: I,
filter_map: F,
) -> Self
pub(crate) fn from_multiple_exclude_root<I>(graph: &'g TxGraph, txids: I, filter_map: F) -> Self
where
I: IntoIterator<Item = Txid>,
{
@@ -595,7 +559,7 @@ impl<'g, F, T> TxDescendants<'g, F, T> {
}
}
impl<'g, F, T> TxDescendants<'g, F, T> {
impl<'g, F> TxDescendants<'g, F> {
fn populate_stack(&mut self, depth: usize, txid: Txid) {
let spend_paths = self
.graph
@@ -607,7 +571,7 @@ impl<'g, F, T> TxDescendants<'g, F, T> {
}
}
impl<'g, F, O, T> Iterator for TxDescendants<'g, F, T>
impl<'g, F, O> Iterator for TxDescendants<'g, F>
where
F: FnMut(usize, Txid) -> Option<O>,
{