-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
83 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | ||
} | ||
} |