// Copyright (C) 2024 Riften Labs AS // // This software is licensed under the GNU Affero General Public License (AGPL), version 3.0 or later. // A copy of the license can be found in the LICENSE file or at https://www.gnu.org/licenses/agpl-3.0.html use std::sync::Arc; use anyhow::Result; use bitcoin_hashes::hex::ToHex; use bitcoincash::BlockHash; use rusqlite::{params, Connection}; pub mod config; pub mod header; pub mod mempool; pub mod pool; pub mod tx; pub mod utxo_funding; pub mod utxo_spending; pub type DBPool = Arc>; pub fn prepare_tables(conn: &Connection) { tx::create_table(conn); utxo_funding::create_table(conn); utxo_spending::create_table(conn); conn.execute( "CREATE TABLE config ( key TEXT PRIMARY KEY, value TEXT )", [], ) .unwrap(); conn.execute( "CREATE TABLE headers ( key TEXT PRIMARY KEY, height INT, header BLOB )", [], ) .unwrap(); // Keep track of what was the initial deployment of a Cauldron pool::create_table(conn); // Indexes for list_by_volume conn.execute( "CREATE INDEX idx_utxo_funding_join ON utxo_funding(new_utxo_hash, sats, token_id);", [], ) .unwrap(); conn.execute("CREATE INDEX idx_utxo_funding_tvl_highest ON utxo_funding(token_id, new_utxo_hash, sats, token_amount);", []).unwrap(); } pub fn delete_entries_for_block(tx: &Connection, blockhash: &BlockHash) -> Result { let mut stmt = tx.prepare( "DELETE FROM utxo_funding WHERE txid IN ( SELECT txid FROM tx WHERE blockhash = ? )", )?; let mut rows_deleted = stmt.execute(params![blockhash.to_hex()])?; let mut stmt = tx.prepare( "DELETE FROM utxo_spending WHERE txid IN ( SELECT txid FROM utxo_funding WHERE txid IN ( SELECT txid FROM tx WHERE blockhash = ? ) )", )?; rows_deleted += stmt.execute(params![blockhash.to_hex()])?; // remaining tables should clear themselves due to foregn keys usage Ok(rows_deleted != 0) }