Skip to content

Commit

Permalink
utxo: Add initial impl.
Browse files Browse the repository at this point in the history
  • Loading branch information
ceyhunsen committed Sep 3, 2024
1 parent 37ba8a6 commit b424308
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
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
75 changes: 75 additions & 0 deletions src/ledger/utxo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
//! # 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::Transaction(format!(
"Couldn't add utxo {:?} to ledger: {}",
utxo, e
)));
};
tracing::trace!("UTXO {utxo:?} saved");

Ok(())
}

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

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::Transaction(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 b424308

Please sign in to comment.