Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 11 additions & 11 deletions crates/chain/src/chain_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::{
COINBASE_MATURITY,
};

/// Represents the height in which a transaction is confirmed at.
/// Represents the height at which a transaction is confirmed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(
feature = "serde",
Expand Down Expand Up @@ -70,7 +70,7 @@ impl TxHeight {
}
}

/// Block height and timestamp in which a transaction is confirmed in.
/// Block height and timestamp at which a transaction is confirmed.
#[derive(Debug, Clone, PartialEq, Eq, Copy, PartialOrd, Ord, core::hash::Hash)]
#[cfg_attr(
feature = "serde",
Expand Down Expand Up @@ -117,17 +117,17 @@ impl ConfirmationTime {
}
}

/// A reference to a block in the cannonical chain.
/// A reference to a block in the canonical chain.
#[derive(Debug, Clone, PartialEq, Eq, Copy, PartialOrd, Ord)]
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
serde(crate = "serde_crate")
)]
pub struct BlockId {
/// The height the block was confirmed at
/// The height of the block.
pub height: u32,
/// The hash of the block
/// The hash of the block.
pub hash: BlockHash,
}

Expand Down Expand Up @@ -161,26 +161,26 @@ impl From<(&u32, &BlockHash)> for BlockId {
}
}

/// A `TxOut` with as much data as we can retreive about it
/// A `TxOut` with as much data as we can retrieve about it
#[derive(Debug, Clone, PartialEq)]
pub struct FullTxOut<I> {
/// The location of the `TxOut`
/// The location of the `TxOut`.
pub outpoint: OutPoint,
/// The `TxOut`
/// The `TxOut`.
pub txout: TxOut,
/// The position of the transaction in `outpoint` in the overall chain.
pub chain_position: I,
/// The txid and chain position of the transaction (if any) that has spent this output.
pub spent_by: Option<(I, Txid)>,
/// Whether this output is on a coinbase transaction
/// Whether this output is on a coinbase transaction.
pub is_on_coinbase: bool,
}

impl<I: ChainPosition> FullTxOut<I> {
/// Whether the utxo is/was/will be spendable at `height`.
///
/// It is spendable if it is not an immature coinbase output and no spending tx has been
/// confirmed by that heigt.
/// confirmed by that height.
pub fn is_spendable_at(&self, height: u32) -> bool {
if !self.is_mature(height) {
return false;
Expand Down Expand Up @@ -215,4 +215,4 @@ impl<I: ChainPosition> FullTxOut<I> {
}
}

// TOOD: make test
// TODO: make test
47 changes: 24 additions & 23 deletions crates/chain/src/chain_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ use core::fmt::Debug;

/// A consistent combination of a [`SparseChain<P>`] and a [`TxGraph<T>`].
///
/// `SparseChain` only keeps track of transaction ids and their position in the chain but you often
/// want to store the full transactions as well. Additionally you want to make sure that everything
/// `SparseChain` only keeps track of transaction ids and their position in the chain, but you often
/// want to store the full transactions as well. Additionally, you want to make sure that everything
/// in the chain is consistent with the full transaction data. `ChainGraph` enforces these two
/// invariants:
///
/// 1. Every transaction that is in the chain is also in the graph (you always have the full
/// transaction).
/// 2. No transactions in the chain conflict with each other i.e. they don't double spend each
/// 2. No transactions in the chain conflict with each other, i.e., they don't double spend each
/// other or have ancestors that double spend each other.
///
/// Note that the `ChainGraph` guarantees a 1:1 mapping between transactions in the `chain` and
Expand Down Expand Up @@ -79,7 +79,7 @@ where
///
/// 1. There is a transaction in the `chain` that does not have its corresponding full
/// transaction in `graph`.
/// 2. The `chain` has two transactions that allegedly in it but they conflict in the `graph`
/// 2. The `chain` has two transactions that are 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) -> Result<Self, NewError<P>> {
let mut missing = HashSet::default();
Expand Down Expand Up @@ -112,8 +112,8 @@ where
/// got it from `self`.
///
/// This is useful when interacting with services like an electrum server which returns a list
/// of txids and heights when calling [`script_get_history`] which can easily be inserted into a
/// [`SparseChain<TxHeight>`][`SparseChain`]. From there you need to figure out which full
/// of txids and heights when calling [`script_get_history`], which can easily be inserted into a
/// [`SparseChain<TxHeight>`][`SparseChain`]. From there, you need to figure out which full
/// transactions you are missing in your chain graph and form `new_txs`. You then use
/// `inflate_update` to turn this into an update `ChainGraph<P, Cow<Transaction>>` and finally
/// use [`determine_changeset`] to generate the changeset from it.
Expand All @@ -138,7 +138,7 @@ where

// [TODO] @evanlinjin: These need better comments
// - copy transactions that have changed positions into the graph
// - add new transactions to inflated chain
// - add new transactions to an inflated chain
for (pos, txid) in update.txids() {
match self.chain.tx_position(*txid) {
Some(original_pos) => {
Expand Down Expand Up @@ -169,7 +169,7 @@ where
ChainGraph::new(inflated_chain, inflated_graph)
}

/// Sets the checkpoint limit.
/// Gets the checkpoint limit.
///
/// Refer to [`SparseChain::checkpoint_limit`] for more.
pub fn checkpoint_limit(&self) -> Option<usize> {
Expand Down Expand Up @@ -206,9 +206,9 @@ where
changeset
}

/// Get a transaction that is currently in the underlying [`SparseChain`].
/// Get a transaction currently in the underlying [`SparseChain`].
///
/// This does not necessarily mean that it is *confirmed* in the blockchain, it might just be in
/// 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, &Transaction)> {
let position = self.chain.tx_position(txid)?;
Expand All @@ -234,7 +234,7 @@ where
Ok(changeset)
}

/// Inserts [`Transaction`] at given chain position.
/// Inserts [`Transaction`] at the given chain position.
///
/// This is equivalent to calling [`Self::insert_tx_preview`] and [`Self::apply_changeset`] in
/// sequence.
Expand Down Expand Up @@ -265,8 +265,7 @@ where
/// Determines the changes required to insert a `block_id` (a height and block hash) into the
/// chain.
///
/// If a checkpoint already exists at that height with a different hash this will return
/// an error.
/// If a checkpoint with a different hash already exists at that height, this will return an error.
pub fn insert_checkpoint_preview(
&self,
block_id: BlockId,
Expand Down Expand Up @@ -312,7 +311,7 @@ where
}

/// Given a transaction, return an iterator of `txid`s that conflict with it (spends at least
/// one of the same inputs). This includes all descendants of conflicting transactions.
/// one of the same inputs). This iterator includes all descendants of conflicting transactions.
///
/// This method only returns conflicts that exist in the [`SparseChain`] as transactions that
/// are not included in [`SparseChain`] are already considered as evicted.
Expand Down Expand Up @@ -343,7 +342,7 @@ where
}
pos
}
// Ignore txids that are being delted by the change (they can't conflict)
// Ignore txids that are being deleted by the change (they can't conflict)
None => continue,
};

Expand All @@ -370,7 +369,7 @@ where
// conflicting tx will be positioned as "unconfirmed" after the update is applied.
// If so, we will modify the changeset to evict the conflicting txid.

// determine the position of the conflicting txid after current changeset is applied
// determine the position of the conflicting txid after the current changeset is applied
let conflicting_new_pos = changeset
.chain
.txids
Expand All @@ -384,7 +383,7 @@ where
}
Some(existing_new_pos) => match existing_new_pos.height() {
TxHeight::Confirmed(_) => {
// the new postion of the conflicting tx is "confirmed", therefore cannot be
// the new position of the conflicting tx is "confirmed", therefore cannot be
// evicted, return error
return Err(UnresolvableConflict {
already_confirmed_tx: (conflicting_pos.clone(), conflicting_txid),
Expand All @@ -405,8 +404,8 @@ where

/// Applies `changeset` to `self`.
///
/// **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.
/// **Warning** this method assumes that the changeset is correctly formed. If it is not, the
/// chain graph may behave incorrectly in the future and panic unexpectedly.
pub fn apply_changeset(&mut self, changeset: ChangeSet<P>) {
self.chain.apply_changeset(changeset.chain);
self.graph.apply_additions(changeset.graph);
Expand All @@ -433,9 +432,11 @@ where
.map(move |(pos, txid)| (pos, self.graph.get_tx(*txid).expect("must exist")))
}

/// Finds the transaction in the chain that spends `outpoint` given the input/output
/// relationships in `graph`. Note that the transaction including `outpoint` does not need to be
/// in the `graph` or the `chain` for this to return `Some(_)`.
/// Find the transaction in the chain that spends `outpoint`.
///
/// This uses the input/output relationships in the internal `graph`. Note that the transaction
/// which includes `outpoint` does not need to be in the `graph` or the `chain` for this to
/// return `Some(_)`.
pub fn spent_by(&self, outpoint: OutPoint) -> Option<(&P, Txid)> {
self.chain.spent_by(&self.graph, outpoint)
}
Expand Down Expand Up @@ -481,7 +482,7 @@ impl<P> ChangeSet<P> {
.any(|(_, new_pos)| new_pos.is_none())
}

/// Appends the changes in `other` into self such that applying `self` afterwards has the same
/// Appends the changes in `other` into self such that applying `self` afterward has the same
/// effect as sequentially applying the original `self` and `other`.
pub fn append(&mut self, other: ChangeSet<P>)
where
Expand Down
2 changes: 1 addition & 1 deletion crates/chain/src/descriptor_ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::miniscript::{Descriptor, DescriptorPublicKey};

/// A trait to extend the functionality of a miniscript descriptor.
pub trait DescriptorExt {
/// Returns the minimum value (in satoshis) that an output should have to be broadcastable.
/// Returns the minimum value (in satoshis) at which an output is broadcastable.
fn dust_value(&self) -> u64;
}

Expand Down
28 changes: 14 additions & 14 deletions crates/chain/src/keychain.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
//! Module for keychain based structures.
//! Module for keychain related structures.
//!
//! A keychain here is a set of application defined indexes for a minscript descriptor where we can
//! A keychain here is a set of application-defined indexes for a miniscript descriptor where we can
//! derive script pubkeys at a particular derivation index. The application's index is simply
//! anything that implements `Ord`.
//!
//! [`KeychainTxOutIndex`] indexes script pubkeys of keychains and scans in relevant outpoints (that
//! has a `txout` containing an indexed script pubkey). Internally, this uses [`SpkTxOutIndex`], but
//! also maintains "revealed" and "lookahead" index count per keychain.
//! also maintains "revealed" and "lookahead" index counts per keychain.
//!
//! [`KeychainTracker`] combines [`ChainGraph`] and [`KeychainTxOutIndex`] and enforces atomic
//! changes between both these structures. [`KeychainScan`] is a structure used to update to
Expand Down Expand Up @@ -63,7 +63,7 @@ impl<K> DerivationAdditions<K> {
self.0.is_empty()
}

/// Get the inner map of keychain to its new derivation index.
/// Get the inner map of the keychain to its new derivation index.
pub fn as_inner(&self) -> &BTreeMap<K, u32> {
&self.0
}
Expand All @@ -72,8 +72,8 @@ impl<K> DerivationAdditions<K> {
impl<K: Ord> DerivationAdditions<K> {
/// Append another [`DerivationAdditions`] into self.
///
/// If keychain already exists, increases the index when other's index > self's index.
/// If keychain did not exist, append the new keychain.
/// If the keychain already exists, increase the index when the other's index > self's index.
/// If the keychain did not exist, append the new keychain.
pub fn append(&mut self, mut other: Self) {
self.0.iter_mut().for_each(|(key, index)| {
if let Some(other_index) = other.0.remove(key) {
Expand Down Expand Up @@ -162,11 +162,11 @@ impl<K, P> KeychainChangeSet<K, P> {
self.chain_graph.is_empty() && self.derivation_indices.is_empty()
}

/// Appends the changes in `other` into `self` such that applying `self` afterwards has the same
/// Appends the changes in `other` into `self` such that applying `self` afterward has the same
/// effect as sequentially applying the original `self` and `other`.
///
/// 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`.
/// Note the derivation indices cannot be decreased, so `other` will only change the derivation
/// index for a keychain, if it's value is higher than the one in `self`.
pub fn append(&mut self, other: KeychainChangeSet<K, P>)
where
K: Ord,
Expand Down Expand Up @@ -207,7 +207,7 @@ impl<K, P> ForEachTxOut for KeychainChangeSet<K, P> {
}
}

/// Balance differentiated in various categories.
/// Balance, differentiated into various categories.
#[derive(Debug, PartialEq, Eq, Clone, Default)]
#[cfg_attr(
feature = "serde",
Expand Down Expand Up @@ -297,13 +297,13 @@ mod test {

lhs.append(rhs);

// Exiting index doesn't update if new index in `other` is lower than `self`
// Exiting index doesn't update if the new index in `other` is lower than `self`.
assert_eq!(lhs.derivation_indices.0.get(&Keychain::One), Some(&7));
// Existing index updates if new index in `other` is higher than `self.
// Existing index updates if the new index in `other` is higher than `self`.
assert_eq!(lhs.derivation_indices.0.get(&Keychain::Two), Some(&5));
// Existing index unchanged, if keychain doesn't exist in `other`
// Existing index is unchanged if keychain doesn't exist in `other`.
assert_eq!(lhs.derivation_indices.0.get(&Keychain::Three), Some(&3));
// New keychain gets added if keychain is in `other`, but not in `self`.
// New keychain gets added if the keychain is in `other` but not in `self`.
assert_eq!(lhs.derivation_indices.0.get(&Keychain::Four), Some(&4));
}
}
12 changes: 6 additions & 6 deletions crates/chain/src/keychain/persist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//!
//! BDK's [`KeychainTracker`] needs somewhere to persist changes it makes during operation.
//! Operations like giving out a new address are crucial to persist so that next time the
//! application is loaded it can find transactions related to that address.
//! application is loaded, it can find transactions related to that address.
//!
//! Note that the [`KeychainTracker`] does not read this persisted data during operation since it
//! always has a copy in memory.
Expand All @@ -14,7 +14,7 @@ use crate::{keychain, sparse_chain::ChainPosition};
/// `Persist` wraps a [`PersistBackend`] to create a convenient staging area for changes before they
/// are persisted. Not all changes made to the [`KeychainTracker`] need to be written to disk right
/// away so you can use [`Persist::stage`] to *stage* it first and then [`Persist::commit`] to
/// finally write it to disk.
/// finally, write it to disk.
///
/// [`KeychainTracker`]: keychain::KeychainTracker
#[derive(Debug)]
Expand Down Expand Up @@ -43,14 +43,14 @@ impl<K, P, B> Persist<K, P, B> {
self.stage.append(changeset)
}

/// Get the changes that haven't been commited yet
/// Get the changes that haven't been committed yet
pub fn staged(&self) -> &keychain::KeychainChangeSet<K, P> {
&self.stage
}

/// Commit the staged changes to the underlying persistence backend.
///
/// Retuns a backend defined error if this fails
/// Returns a backend-defined error if this fails.
pub fn commit(&mut self) -> Result<(), B::WriteError>
where
B: PersistBackend<K, P>,
Expand All @@ -69,10 +69,10 @@ pub trait PersistBackend<K, P> {
/// The error the backend returns when it fails to load.
type LoadError: core::fmt::Debug;

/// Appends a new changeset to the persistance backend.
/// Appends a new changeset to the persistent backend.
///
/// It is up to the backend what it does with this. It could store every changeset in a list or
/// it insert the actual changes to a more structured database. All it needs to guarantee is
/// it inserts the actual changes into a more structured database. All it needs to guarantee is
/// that [`load_into_keychain_tracker`] restores a keychain tracker to what it should be if all
/// changesets had been applied sequentially.
///
Expand Down
Loading