Skip to main content

create_fs_file/
create.rs

1use std::{fs::write, sync::Arc};
2
3use clap::Parser;
4use futures::TryStreamExt;
5use tower::{Service, ServiceExt};
6
7use cuprate_blockchain::{config::Config, service::BlockchainReadHandle, DbResult};
8use cuprate_hex::Hex;
9use cuprate_types::{
10    blockchain::{BlockchainReadRequest, BlockchainResponse},
11    Chain,
12};
13
14use cuprate_fast_sync::FAST_SYNC_BATCH_LEN;
15use cuprate_helper::fs::CUPRATE_DATA_DIR;
16
17async fn read_batch(
18    handle: &mut BlockchainReadHandle,
19    height_from: usize,
20) -> DbResult<Vec<[u8; 32]>> {
21    let request = BlockchainReadRequest::BlockHashInRange(
22        height_from..(height_from + FAST_SYNC_BATCH_LEN),
23        Chain::Main,
24    );
25    let response_channel = handle.ready().await?.call(request);
26    let response = response_channel.await?;
27
28    let BlockchainResponse::BlockHashInRange(block_ids) = response else {
29        unreachable!()
30    };
31
32    Ok(block_ids)
33}
34
35#[derive(Parser)]
36#[command(version, about, long_about = None)]
37struct Args {
38    #[arg(long)]
39    height: usize,
40}
41
42#[tokio::main]
43async fn main() {
44    let args = Args::parse();
45    tracing_subscriber::fmt().init();
46
47    let height_target = args.height;
48
49    // TODO: use the cuprated config here?
50    let config = Config::default();
51
52    let fjall_dir = CUPRATE_DATA_DIR.to_path_buf().join("fjall");
53
54    let fjall = fjall::Database::builder(fjall_dir).open().unwrap();
55
56    let thread_pool = Arc::new(rayon::ThreadPoolBuilder::new().build().unwrap());
57
58    let (read_handle, _, _) =
59        cuprate_blockchain::service::init_with_pool(&config, fjall, thread_pool).unwrap();
60
61    let time = std::time::Instant::now();
62
63    let fut = (0..(height_target / FAST_SYNC_BATCH_LEN) * FAST_SYNC_BATCH_LEN)
64        .step_by(FAST_SYNC_BATCH_LEN)
65        .map(|height| {
66            let mut read_handle = read_handle.clone();
67            async move {
68                println!("height: {height}");
69
70                if let Ok(block_ids) = read_batch(&mut read_handle, height).await {
71                    let hash = hash_of_hashes(block_ids.as_slice());
72                    Ok(Hex(hash))
73                } else {
74                    println!("Failed to read next batch from database");
75                    Err("Failed to read next batch from database")
76                }
77            }
78        })
79        .collect::<futures::stream::FuturesOrdered<_>>();
80
81    let hashes_of_hashes = fut.try_collect::<Vec<_>>().await.unwrap();
82
83    drop(read_handle);
84
85    write(
86        "fast_sync_hashes.json",
87        serde_json::to_string_pretty(&hashes_of_hashes).unwrap(),
88    )
89    .unwrap();
90
91    println!(
92        "Generated hashes up to block height {} in {} milliseconds.",
93        hashes_of_hashes.len() * FAST_SYNC_BATCH_LEN,
94        time.elapsed().as_millis()
95    );
96}
97
98pub fn hash_of_hashes(hashes: &[[u8; 32]]) -> [u8; 32] {
99    blake3::hash(hashes.concat().as_slice()).into()
100}