Skip to content

Commit

Permalink
Merge pull request #60 from chainwayxyz/utxo_management
Browse files Browse the repository at this point in the history
Simple UTXO management
  • Loading branch information
ceyhunsen authored Sep 3, 2024
2 parents 37ba8a6 + 340c446 commit 25f2f3b
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/client/rpc_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,11 @@ impl RpcApi for Client {
)));
}

let utxo = OutPoint { txid: *txid, vout };
if self.ledger.is_utxo_spent(utxo) {
return Err(LedgerError::Utxo(format!("UTXO {utxo:?} is spent")).into());
}

let bestblock = self.get_best_block_hash()?;

let tx = self.get_raw_transaction(txid, None)?;
Expand Down
8 changes: 8 additions & 0 deletions src/ledger/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub(crate) mod errors;
mod script;
mod spending_requirements;
mod transactions;
mod utxo;

/// Mock Bitcoin ledger.
#[derive(Clone, Debug)]
Expand Down Expand Up @@ -87,6 +88,7 @@ impl Ledger {
DROP TABLE IF EXISTS blocks;
DROP TABLE IF EXISTS mempool;
DROP TABLE IF EXISTS transactions;
DROP TABLE IF EXISTS utxos;
",
)
}
Expand Down Expand Up @@ -125,6 +127,12 @@ impl Ledger {
CONSTRAINT txid PRIMARY KEY
);
CREATE TABLE utxos
(
txid TEXT NOT NULL,
vout INTEGER NOT NULL
);
",
)
}
Expand Down
16 changes: 16 additions & 0 deletions src/ledger/transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ impl Ledger {

self.add_mempool_transaction(txid)?;

self.handle_transaction_utxos(&transaction)?;

Ok(txid)
}

Expand Down Expand Up @@ -267,6 +269,20 @@ impl Ledger {
amount
}

/// Removes inputs from UTXOs and adds outputs to UTXOs.
pub fn handle_transaction_utxos(&self, transaction: &Transaction) -> Result<(), LedgerError> {
for input in &transaction.input {
self.remove_utxo(input.previous_output)?;
}

let txid = transaction.compute_txid();
for vout in 0..(transaction.output.len() as u32) {
self.add_utxo(OutPoint { txid, vout })?;
}

Ok(())
}

/// Creates a `TxIn` with some defaults.
pub fn create_txin(&self, txid: Txid, vout: u32) -> TxIn {
TxIn {
Expand Down
73 changes: 73 additions & 0 deletions src/ledger/utxo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
//! # UTXO Management
use super::{errors::LedgerError, Ledger};
use bitcoin::OutPoint;
use rusqlite::params;

impl Ledger {
pub fn add_utxo(&self, utxo: OutPoint) -> Result<(), LedgerError> {
if let Err(e) = self.database.lock().unwrap().execute(
"INSERT INTO utxos (txid, vout) VALUES (?1, ?2)",
params![utxo.txid.to_string(), utxo.vout],
) {
return Err(LedgerError::Utxo(format!(
"Couldn't add utxo {:?} to ledger: {}",
utxo, e
)));
};
tracing::trace!("UTXO {utxo:?} saved");

Ok(())
}

pub fn is_utxo_spent(&self, utxo: OutPoint) -> bool {
self.database
.lock()
.unwrap()
.query_row(
"SELECT * FROM utxos WHERE txid = ?1 AND vout = ?2",
params![utxo.txid.to_string(), utxo.vout],
|_| Ok(()),
)
.is_err()
}

pub fn remove_utxo(&self, utxo: OutPoint) -> Result<(), LedgerError> {
if let Err(e) = self.database.lock().unwrap().execute(
"DELETE FROM utxos WHERE txid = ?1 AND vout = ?2",
params![utxo.txid.to_string(), utxo.vout],
) {
return Err(LedgerError::Utxo(format!(
"Couldn't remove utxo {:?} from ledger: {}",
utxo, e
)));
};
tracing::trace!("UTXO {utxo:?} marked as spent");

Ok(())
}
}

#[cfg(test)]
mod tests {
use crate::ledger::Ledger;
use bitcoin::{hashes::Hash, OutPoint, Txid};

#[test]
fn basic_add_remove_utxo() {
let ledger = Ledger::new("basic_add_remove_utxo");

let utxo = OutPoint {
txid: Txid::all_zeros(),
vout: 0x45,
};

assert!(ledger.is_utxo_spent(utxo));

ledger.add_utxo(utxo).unwrap();
assert!(!ledger.is_utxo_spent(utxo));

ledger.remove_utxo(utxo).unwrap();
assert!(ledger.is_utxo_spent(utxo));
}
}

0 comments on commit 25f2f3b

Please sign in to comment.