Skip to content

Commit 5692426

Browse files
authored
fix: only create brc-20 db connection and cache if required (#357)
* fix: unify db create * fix: test * fix: create on drop * fix: build * chore: remove warnings * fix: add some logs * fix: blocking thread
1 parent 7a65fdf commit 5692426

File tree

8 files changed

+111
-136
lines changed

8 files changed

+111
-136
lines changed

components/ordhook-cli/src/cli/mod.rs

+5-19
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use ordhook::chainhook_sdk::utils::BlockHeights;
1717
use ordhook::chainhook_sdk::utils::Context;
1818
use ordhook::config::Config;
1919
use ordhook::core::meta_protocols::brc20::db::{
20-
get_brc20_operations_on_block, open_readwrite_brc20_db_conn,
20+
brc20_new_rw_db_conn, get_brc20_operations_on_block,
2121
};
2222
use ordhook::core::new_traversals_lazy_cache;
2323
use ordhook::core::pipeline::download_and_pipeline_blocks;
@@ -42,10 +42,10 @@ use reqwest::Client as HttpClient;
4242
use std::collections::HashSet;
4343
use std::io::{BufReader, Read};
4444
use std::path::PathBuf;
45-
use std::process;
4645
use std::sync::Arc;
4746
use std::thread::sleep;
4847
use std::time::Duration;
48+
use std::{process, u64};
4949

5050
#[derive(Parser, Debug)]
5151
#[clap(author, version, about, long_about = None)]
@@ -729,8 +729,8 @@ async fn handle_command(opts: Opts, ctx: &Context) -> Result<(), String> {
729729
let maintenance_enabled =
730730
std::env::var("ORDHOOK_MAINTENANCE").unwrap_or("0".into());
731731
if maintenance_enabled.eq("1") {
732-
info!(ctx.expect_logger(), "Entering maintenance mode (default duration = 7 days). Unset ORDHOOK_MAINTENANCE and reboot to resume operations");
733-
sleep(Duration::from_secs(3600 * 24 * 7))
732+
try_info!(ctx, "Entering maintenance mode. Unset ORDHOOK_MAINTENANCE and reboot to resume operations");
733+
sleep(Duration::from_secs(u64::MAX))
734734
}
735735

736736
let config = ConfigFile::default(
@@ -745,7 +745,6 @@ async fn handle_command(opts: Opts, ctx: &Context) -> Result<(), String> {
745745
let last_known_block =
746746
find_latest_inscription_block_height(&db_connections.ordhook, ctx)?;
747747
if last_known_block.is_none() {
748-
// Create rocksdb
749748
open_ordhook_db_conn_rocks_db_loop(
750749
true,
751750
&config.expected_cache_path(),
@@ -756,12 +755,6 @@ async fn handle_command(opts: Opts, ctx: &Context) -> Result<(), String> {
756755
}
757756

758757
let ordhook_config = config.get_ordhook_config();
759-
let version = env!("GIT_COMMIT");
760-
info!(
761-
ctx.expect_logger(),
762-
"Starting service (git_commit = {})...", version
763-
);
764-
765758
let start_block = match cmd.start_at_block {
766759
Some(entry) => entry,
767760
None => match last_known_block {
@@ -961,14 +954,7 @@ async fn handle_command(opts: Opts, ctx: &Context) -> Result<(), String> {
961954
config.resources.memory_available,
962955
&ctx,
963956
)?;
964-
let brc_20_db_conn_rw = if config.meta_protocols.brc20 {
965-
Some(open_readwrite_brc20_db_conn(
966-
&config.expected_cache_path(),
967-
ctx,
968-
)?)
969-
} else {
970-
None
971-
};
957+
let brc_20_db_conn_rw = brc20_new_rw_db_conn(&config, ctx);
972958

973959
delete_data_in_ordhook_db(
974960
cmd.start_block,

components/ordhook-core/src/core/meta_protocols/brc20/cache.rs

+10-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use chainhook_sdk::{
77
use lru::LruCache;
88
use rusqlite::{Connection, Transaction};
99

10-
use crate::core::meta_protocols::brc20::db::get_unsent_token_transfer;
10+
use crate::{config::Config, core::meta_protocols::brc20::db::get_unsent_token_transfer};
1111

1212
use super::{
1313
db::{
@@ -17,6 +17,15 @@ use super::{
1717
verifier::{VerifiedBrc20BalanceData, VerifiedBrc20TokenDeployData, VerifiedBrc20TransferData},
1818
};
1919

20+
/// If the given `config` has BRC-20 enabled, returns a BRC-20 memory cache.
21+
pub fn brc20_new_cache(config: &Config) -> Option<Brc20MemoryCache> {
22+
if config.meta_protocols.brc20 {
23+
Some(Brc20MemoryCache::new(config.resources.brc20_lru_cache_size))
24+
} else {
25+
None
26+
}
27+
}
28+
2029
/// Keeps BRC20 DB rows before they're inserted into SQLite. Use `flush` to insert.
2130
pub struct Brc20DbCache {
2231
ledger_rows: Vec<Brc20DbLedgerRow>,

components/ordhook-core/src/core/meta_protocols/brc20/db.rs

+19-18
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
use std::{collections::HashMap, path::PathBuf};
22

33
use crate::{
4-
db::{
5-
create_or_open_readwrite_db, open_existing_readonly_db, perform_query_one,
6-
perform_query_set,
7-
},
8-
try_warn,
4+
config::Config,
5+
db::{create_or_open_readwrite_db, perform_query_one, perform_query_set},
6+
try_error, try_warn,
97
};
108
use chainhook_sdk::{
119
types::{
@@ -44,6 +42,21 @@ pub struct Brc20DbLedgerRow {
4442
pub operation: String,
4543
}
4644

45+
/// If the given `config` has BRC-20 enabled, returns a read/write DB connection for BRC-20.
46+
pub fn brc20_new_rw_db_conn(config: &Config, ctx: &Context) -> Option<Connection> {
47+
if config.meta_protocols.brc20 {
48+
match open_readwrite_brc20_db_conn(&config.expected_cache_path(), &ctx) {
49+
Ok(db) => Some(db),
50+
Err(e) => {
51+
try_error!(ctx, "Unable to open readwrite brc20 connection: {e}");
52+
None
53+
}
54+
}
55+
} else {
56+
None
57+
}
58+
}
59+
4760
pub fn get_default_brc20_db_file_path(base_dir: &PathBuf) -> PathBuf {
4861
let mut destination_path = base_dir.clone();
4962
destination_path.push("brc20.sqlite");
@@ -132,24 +145,12 @@ pub fn initialize_brc20_db(base_dir: Option<&PathBuf>, ctx: &Context) -> Connect
132145
conn
133146
}
134147

135-
pub fn open_readwrite_brc20_db_conn(
136-
base_dir: &PathBuf,
137-
ctx: &Context,
138-
) -> Result<Connection, String> {
148+
fn open_readwrite_brc20_db_conn(base_dir: &PathBuf, ctx: &Context) -> Result<Connection, String> {
139149
let db_path = get_default_brc20_db_file_path(&base_dir);
140150
let conn = create_or_open_readwrite_db(Some(&db_path), ctx);
141151
Ok(conn)
142152
}
143153

144-
pub fn open_readonly_brc20_db_conn(
145-
base_dir: &PathBuf,
146-
ctx: &Context,
147-
) -> Result<Connection, String> {
148-
let db_path = get_default_brc20_db_file_path(&base_dir);
149-
let conn = open_existing_readonly_db(&db_path, ctx);
150-
Ok(conn)
151-
}
152-
153154
pub fn delete_activity_in_block_range(
154155
start_block: u32,
155156
end_block: u32,

components/ordhook-core/src/core/pipeline/processors/inscription_indexing.rs

+32-32
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,10 @@ use std::hash::BuildHasherDefault;
1919

2020
use crate::{
2121
core::{
22-
meta_protocols::brc20::{cache::Brc20MemoryCache, db::open_readwrite_brc20_db_conn},
22+
meta_protocols::brc20::{
23+
cache::{brc20_new_cache, Brc20MemoryCache},
24+
db::brc20_new_rw_db_conn,
25+
},
2326
pipeline::processors::block_archiving::store_compacted_blocks,
2427
protocol::{
2528
inscription_parsing::{
@@ -79,6 +82,9 @@ pub fn start_inscription_indexing_processor(
7982
open_readonly_ordhook_db_conn(&config.expected_cache_path(), &ctx).unwrap();
8083
let mut sequence_cursor = SequenceCursor::new(&inscriptions_db_conn);
8184

85+
let mut brc20_cache = brc20_new_cache(&config);
86+
let mut brc20_db_conn_rw = brc20_new_rw_db_conn(&config, &ctx);
87+
8288
loop {
8389
let (compacted_blocks, mut blocks) = match commands_rx.try_recv() {
8490
Ok(PostProcessorCommand::ProcessBlocks(compacted_blocks, blocks)) => {
@@ -133,6 +139,8 @@ pub fn start_inscription_indexing_processor(
133139
&mut sequence_cursor,
134140
&cache_l2,
135141
&mut inscriptions_db_conn_rw,
142+
&mut brc20_cache,
143+
&mut brc20_db_conn_rw,
136144
&ordhook_config,
137145
&post_processor,
138146
&ctx,
@@ -169,26 +177,18 @@ pub fn process_blocks(
169177
sequence_cursor: &mut SequenceCursor,
170178
cache_l2: &Arc<DashMap<(u32, [u8; 8]), TransactionBytesCursor, BuildHasherDefault<FxHasher>>>,
171179
inscriptions_db_conn_rw: &mut Connection,
180+
brc20_cache: &mut Option<Brc20MemoryCache>,
181+
brc20_db_conn_rw: &mut Option<Connection>,
172182
ordhook_config: &OrdhookConfig,
173183
post_processor: &Option<Sender<BitcoinBlockData>>,
174184
ctx: &Context,
175185
) -> Vec<BitcoinBlockData> {
176186
let mut cache_l1 = BTreeMap::new();
177-
178187
let mut updated_blocks = vec![];
179188

180-
let mut brc20_db_conn_rw = match open_readwrite_brc20_db_conn(&ordhook_config.db_path, &ctx) {
181-
Ok(dbs) => dbs,
182-
Err(e) => {
183-
panic!("Unable to open readwrite connection: {e}");
184-
}
185-
};
186-
let mut brc20_cache = Brc20MemoryCache::new(ordhook_config.resources.brc20_lru_cache_size);
187-
188189
for _cursor in 0..next_blocks.len() {
189-
let inscriptions_db_tx: rusqlite::Transaction<'_> =
190-
inscriptions_db_conn_rw.transaction().unwrap();
191-
let brc20_db_tx = brc20_db_conn_rw.transaction().unwrap();
190+
let inscriptions_db_tx = inscriptions_db_conn_rw.transaction().unwrap();
191+
let brc20_db_tx = brc20_db_conn_rw.as_mut().map(|c| c.transaction().unwrap());
192192

193193
let mut block = next_blocks.remove(0);
194194

@@ -214,8 +214,8 @@ pub fn process_blocks(
214214
&mut cache_l1,
215215
cache_l2,
216216
&inscriptions_db_tx,
217-
Some(&brc20_db_tx),
218-
&mut brc20_cache,
217+
brc20_db_tx.as_ref(),
218+
brc20_cache.as_mut(),
219219
ordhook_config,
220220
ctx,
221221
);
@@ -242,21 +242,20 @@ pub fn process_blocks(
242242
block.block_identifier.index,
243243
);
244244
let _ = inscriptions_db_tx.rollback();
245-
let _ = brc20_db_tx.rollback();
245+
let _ = brc20_db_tx.map(|t| t.rollback());
246246
} else {
247247
match inscriptions_db_tx.commit() {
248-
Ok(_) => match brc20_db_tx.commit() {
249-
Ok(_) => {}
250-
Err(_) => {
251-
// delete_data_in_ordhook_db(
252-
// block.block_identifier.index,
253-
// block.block_identifier.index,
254-
// ordhook_config,
255-
// ctx,
256-
// );
257-
todo!()
248+
Ok(_) => {
249+
if let Some(brc20_db_tx) = brc20_db_tx {
250+
match brc20_db_tx.commit() {
251+
Ok(_) => {}
252+
Err(_) => {
253+
// TODO: Synchronize rollbacks and commits between BRC-20 and inscription DBs.
254+
todo!()
255+
}
256+
}
258257
}
259-
},
258+
}
260259
Err(e) => {
261260
try_error!(
262261
ctx,
@@ -284,7 +283,7 @@ pub fn process_block(
284283
cache_l2: &Arc<DashMap<(u32, [u8; 8]), TransactionBytesCursor, BuildHasherDefault<FxHasher>>>,
285284
inscriptions_db_tx: &Transaction,
286285
brc20_db_tx: Option<&Transaction>,
287-
brc20_cache: &mut Brc20MemoryCache,
286+
brc20_cache: Option<&mut Brc20MemoryCache>,
288287
ordhook_config: &OrdhookConfig,
289288
ctx: &Context,
290289
) -> Result<(), String> {
@@ -322,14 +321,15 @@ pub fn process_block(
322321
// Handle transfers
323322
let _ = augment_block_with_ordinals_transfer_data(block, inscriptions_db_tx, true, &inner_ctx);
324323

325-
if let Some(brc20_db_tx) = brc20_db_tx {
326-
write_brc20_block_operations(
324+
match (brc20_db_tx, brc20_cache) {
325+
(Some(brc20_db_tx), Some(brc20_cache)) => write_brc20_block_operations(
327326
block,
328327
&mut brc20_operation_map,
329328
brc20_cache,
330-
&brc20_db_tx,
329+
brc20_db_tx,
331330
&ctx,
332-
);
331+
),
332+
_ => {}
333333
}
334334

335335
Ok(())

components/ordhook-core/src/db/mod.rs

+2-18
Original file line numberDiff line numberDiff line change
@@ -560,44 +560,28 @@ pub fn update_ordinals_db_with_block(
560560
let (tx, output_index, offset) =
561561
parse_satpoint_to_watch(&inscription_data.satpoint_post_inscription);
562562
let outpoint_to_watch = format_outpoint_to_watch(&tx, output_index);
563-
let insertion_res = locations_to_insert.insert(
563+
let _ = locations_to_insert.insert(
564564
(inscription_data.ordinal_number, outpoint_to_watch),
565565
OrdinalLocation {
566566
offset,
567567
block_height: block.block_identifier.index,
568568
tx_index: inscription_data.tx_index,
569569
},
570570
);
571-
if let Some(prev_location) = insertion_res {
572-
try_warn!(
573-
ctx,
574-
"Ignoring location insertion from inscriptions: {}, {:?}",
575-
inscription_data.ordinal_number,
576-
prev_location
577-
);
578-
}
579571
}
580572

581573
for transfer_data in get_inscriptions_transferred_in_block(&block).iter() {
582574
let (tx, output_index, offset) =
583575
parse_satpoint_to_watch(&transfer_data.satpoint_post_transfer);
584576
let outpoint_to_watch = format_outpoint_to_watch(&tx, output_index);
585-
let insertion_res = locations_to_insert.insert(
577+
let _ = locations_to_insert.insert(
586578
(transfer_data.ordinal_number, outpoint_to_watch),
587579
OrdinalLocation {
588580
offset,
589581
block_height: block.block_identifier.index,
590582
tx_index: transfer_data.tx_index,
591583
},
592584
);
593-
if let Some(prev_location) = insertion_res {
594-
try_warn!(
595-
ctx,
596-
"Ignoring location insertion from transfers: {}, {:?}",
597-
transfer_data.ordinal_number,
598-
prev_location
599-
);
600-
}
601585
}
602586

603587
for ((ordinal_number, outpoint_to_watch), location_data) in locations_to_insert {

components/ordhook-core/src/service/http_api.rs

+2-8
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,7 @@ pub async fn start_observers_http_server(
5454
let _ = hiro_system_kit::thread_named("observers_api-events").spawn(move || loop {
5555
let event = match observer_event_rx.recv() {
5656
Ok(cmd) => cmd,
57-
Err(e) => {
58-
try_error!(&moved_ctx, "Error: broken channel {}", e.to_string());
59-
break;
60-
}
57+
Err(_) => break
6158
};
6259
match event {
6360
ObserverEvent::PredicateRegistered(spec) => {
@@ -136,10 +133,6 @@ pub async fn start_observers_http_server(
136133
)
137134
}
138135
}
139-
ObserverEvent::Terminate => {
140-
try_info!(&moved_ctx, "Terminating runloop");
141-
break;
142-
}
143136
_ => {}
144137
}
145138
});
@@ -155,6 +148,7 @@ async fn build_server(
155148
let PredicatesApi::On(ref api_config) = config.http_api else {
156149
unreachable!();
157150
};
151+
try_info!(ctx, "Listening on port {} for chainhook predicate registrations", api_config.http_port);
158152
let moved_config = config.clone();
159153
let moved_ctx = ctx.clone();
160154
let moved_observer_commands_tx = observer_command_tx.clone();

0 commit comments

Comments
 (0)