Skip to content

Commit 6ff1a9c

Browse files
committed
clean up code comments
1 parent 9c2df7f commit 6ff1a9c

File tree

9 files changed

+9
-67
lines changed

9 files changed

+9
-67
lines changed

src/lib.rs

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,15 +35,10 @@ impl std::fmt::Display for BlockHeightRange {
3535
}
3636
}
3737

38-
/// Holds all available user arguments
3938
pub struct ParserOptions {
40-
// Holds the relevant coin parameters we need for parsing
4139
pub coin: CoinType,
42-
// Enable this if you want to check the chain index integrity and merkle root for each block.
4340
pub verify: bool,
44-
// Path to directory where blk.dat files are stored
4541
pub blockchain_dir: std::path::PathBuf,
46-
// Range which is considered for parsing
4742
pub range: BlockHeightRange,
4843
}
4944

@@ -52,7 +47,6 @@ pub fn command() -> Command {
5247
let coins = ["bitcoin", "testnet3"];
5348
Command::new("bitcoin-blockparser")
5449
.version(clap::crate_version!())
55-
// Add flags
5650
.arg(Arg::new("verify")
5751
.long("verify")
5852
.action(clap::ArgAction::SetTrue)
@@ -62,7 +56,6 @@ pub fn command() -> Command {
6256
.short('v')
6357
.action(clap::ArgAction::Count)
6458
.help("Increases verbosity level. Info=0, Debug=1, Trace=2 (default: 0)"))
65-
// Add options
6659
.arg(Arg::new("coin")
6760
.short('c')
6861
.long("coin")
@@ -87,14 +80,12 @@ pub fn command() -> Command {
8780
.help("Specify last block for parsing (inclusive) (default: all known blocks)"))
8881
}
8982

90-
/// Returns default directory. TODO: test on windows
9183
fn get_absolute_blockchain_dir(coin: &CoinType) -> std::path::PathBuf {
9284
dirs::home_dir()
9385
.expect("Unable to get home path from env!")
9486
.join(&coin.default_folder)
9587
}
9688

97-
/// Parses args or panics if some requirements are not met.
9889
pub fn parse_args(matches: &clap::ArgMatches) -> anyhow::Result<ParserOptions> {
9990
let verify = matches.get_flag("verify");
10091

src/main.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ fn main() {
2020
}
2121
};
2222

23-
// Apply log filter based on verbosity
2423
tracing::info!(target: "main", "Starting bitcoin-blockparser v{} ...", env!("CARGO_PKG_VERSION"));
2524
if options.verify {
2625
tracing::info!(target: "main", "Configured to verify merkle roots and block hashes");

src/parser/blkfile.rs

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ use anyhow::Context;
77

88
use crate::parser::reader::BlockchainRead;
99

10-
/// Holds all necessary data about a raw blk file
1110
#[derive(Debug)]
1211
pub struct BlkFile {
1312
pub path: PathBuf,
@@ -24,7 +23,6 @@ impl BlkFile {
2423
}
2524
}
2625

27-
/// Opens the file handle (does nothing if the file has been opened already)
2826
fn open(&mut self) -> anyhow::Result<&mut std::io::BufReader<File>> {
2927
if self.reader.is_none() {
3028
tracing::debug!(target: "blkfile", "Opening {} ...", &self.path.display());
@@ -33,7 +31,6 @@ impl BlkFile {
3331
Ok(self.reader.as_mut().unwrap())
3432
}
3533

36-
/// Closes the file handle
3734
pub fn close(&mut self) {
3835
tracing::debug!(target: "blkfile", "Closing {} ...", &self.path.display());
3936
if self.reader.is_some() {
@@ -56,7 +53,6 @@ impl BlkFile {
5653
reader.read_block()
5754
}
5855

59-
/// Collects all blk*.dat paths in the given directory
6056
pub fn from_path(path: &Path) -> anyhow::Result<HashMap<u64, BlkFile>> {
6157
tracing::info!(target: "blkfile", "Reading files from {} ...", path.display());
6258
let mut collected = HashMap::with_capacity(4000);
@@ -76,9 +72,7 @@ impl BlkFile {
7672
.to_str()
7773
.context("invalid path")?,
7874
);
79-
// Check if it's a valid blk file
8075
if let Some(index) = BlkFile::parse_blk_index(&file_name, "blk", ".dat") {
81-
// Build BlkFile structures
8276
let size = std::fs::metadata(path.as_path())?.len();
8377
tracing::trace!(target: "blkfile", "Adding {} ... (index: {}, size: {})", path.display(), index, size);
8478
collected.insert(index, BlkFile::new(path, size));
@@ -98,8 +92,6 @@ impl BlkFile {
9892
}
9993
}
10094

101-
/// Resolves a PathBuf for the given entry.
102-
/// Also resolves symlinks if present.
10395
fn resolve_path(entry: &DirEntry) -> std::io::Result<PathBuf> {
10496
if entry.file_type()?.is_symlink() {
10597
std::fs::read_link(entry.path())
@@ -108,11 +100,8 @@ impl BlkFile {
108100
}
109101
}
110102

111-
/// Identifies blk file and parses index
112-
/// Returns None if this is no blk file
113103
fn parse_blk_index(file_name: &str, prefix: &str, ext: &str) -> Option<u64> {
114104
if file_name.starts_with(prefix) && file_name.ends_with(ext) {
115-
// Parse blk_index, this means we extract 42 from blk000042.dat
116105
file_name[prefix.len()..(file_name.len() - ext.len())]
117106
.parse::<u64>()
118107
.ok()

src/parser/chain.rs

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,9 @@ use crate::parser::index::ChainIndex;
33
use crate::parser::types::CoinType;
44
use crate::ParserOptions;
55

6-
/// Manages the index and data of longest valid chain
76
pub struct ChainStorage {
87
chain_index: ChainIndex,
9-
blk_files: std::collections::HashMap<u64, BlkFile>, // maps blk_index to BlkFile
8+
blk_files: std::collections::HashMap<u64, BlkFile>,
109
coin: CoinType,
1110
verify: bool,
1211
}
@@ -21,30 +20,24 @@ impl ChainStorage {
2120
})
2221
}
2322

24-
/// Returns the header of a given height.
2523
#[must_use]
2624
pub fn get_header(&mut self, height: u64) -> Option<bitcoin::blockdata::block::Header> {
27-
// Read block
2825
let block_meta = self.chain_index.get(height)?;
2926
let blk_file = self.blk_files.get_mut(&block_meta.blk_index)?;
3027
let header = blk_file.read_header(block_meta.data_offset).ok()?;
3128

32-
// Check if blk file can be closed
3329
if height == self.chain_index.max_height_by_blk(block_meta.blk_index) {
3430
blk_file.close();
3531
}
3632
Some(header)
3733
}
3834

39-
/// Returns the block of a given height.
4035
#[must_use]
4136
pub fn get_block(&mut self, height: u64) -> Option<bitcoin::Block> {
42-
// Read block
4337
let block_meta = self.chain_index.get(height)?;
4438
let blk_file = self.blk_files.get_mut(&block_meta.blk_index)?;
4539
let block = blk_file.read_block(block_meta.data_offset).ok()?;
4640

47-
// Check if blk file can be closed
4841
if height == self.chain_index.max_height_by_blk(block_meta.blk_index) {
4942
blk_file.close();
5043
}
@@ -56,8 +49,6 @@ impl ChainStorage {
5649
Some(block)
5750
}
5851

59-
/// Verifies the given block in a chain.
60-
/// Panics if not valid
6152
fn verify(&self, block: &bitcoin::Block, height: u64) -> anyhow::Result<()> {
6253
assert!(block.check_merkle_root());
6354
if height == 0 {

src/parser/index.rs

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,10 @@ use crate::ParserOptions;
99
const BLOCK_VALID_CHAIN: u64 = 4;
1010
const BLOCK_HAVE_DATA: u64 = 8;
1111

12-
/// Holds the index of longest valid chain
1312
pub struct ChainIndex {
1413
max_height: u64,
1514
block_index: std::collections::HashMap<u64, BlockIndexRecord>,
16-
max_height_blk_index: std::collections::HashMap<u64, u64>, // Maps blk_index to max_height found in the file
15+
max_height_blk_index: std::collections::HashMap<u64, u64>,
1716
}
1817

1918
impl ChainIndex {
@@ -41,7 +40,6 @@ impl ChainIndex {
4140
Some(_) | None => max_known_height,
4241
};
4342

44-
// Filter to only keep relevant block index
4543
if !options.range.is_default() {
4644
tracing::info!(target: "index", "Trimming block index from height {} to {} ...", min_height, max_height);
4745
block_index.retain(|height, _| {
@@ -56,28 +54,23 @@ impl ChainIndex {
5654
})
5755
}
5856

59-
/// Returns the `BlockIndexRecord` for the given height
6057
pub fn get(&self, height: u64) -> Option<&BlockIndexRecord> {
6158
self.block_index.get(&height)
6259
}
6360

64-
/// Returns the maximum height known
6561
pub fn max_height(&self) -> u64 {
6662
self.max_height
6763
}
6864

69-
/// Returns the maximum height that can be found in the given blk_index
7065
pub fn max_height_by_blk(&self, blk_index: u64) -> u64 {
7166
*self.max_height_blk_index.get(&blk_index).unwrap()
7267
}
7368
}
7469

75-
/// Holds the metadata where the block data is stored,
76-
/// See https://bitcoin.stackexchange.com/questions/28168/what-are-the-keys-used-in-the-blockchain-leveldb-ie-what-are-the-keyvalue-pair
7770
pub struct BlockIndexRecord {
7871
pub block_hash: sha256d::Hash,
7972
pub blk_index: u64,
80-
pub data_offset: u64, // offset within the blk file
73+
pub data_offset: u64,
8174
version: u64,
8275
height: u64,
8376
status: u64,

src/parser/mod.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ mod index;
99
pub mod reader;
1010
pub mod types;
1111

12-
/// Small struct to hold statistics together
1312
struct WorkerStats {
1413
pub started_at: Instant,
1514
pub last_log: Instant,
@@ -27,13 +26,12 @@ impl WorkerStats {
2726
}
2827

2928
pub struct BlockchainParser {
30-
chain_storage: ChainStorage, // Hash storage with the longest chain
31-
stats: WorkerStats, // struct for thread management & statistics
29+
chain_storage: ChainStorage,
30+
stats: WorkerStats,
3231
cur_height: u64,
3332
}
3433

3534
impl BlockchainParser {
36-
/// Instantiates a new Parser.
3735
#[must_use]
3836
pub fn new(options: &ParserOptions, chain_storage: ChainStorage) -> Self {
3937
tracing::info!(target: "parser", "Parsing {} blockchain ...", options.coin.name);
@@ -58,7 +56,6 @@ impl BlockchainParser {
5856
self.on_complete(self.cur_height.saturating_sub(1));
5957
}
6058

61-
/// Returns number of remaining blocks
6259
#[must_use]
6360
pub fn remaining(&self) -> u64 {
6461
self.chain_storage

src/parser/reader.rs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,13 @@
11
use bitcoin::consensus::Decodable;
22

3-
/// Trait for structured reading of blockchain data
43
pub trait BlockchainRead: std::io::Read {
5-
/// Reads a block as specified here: https://en.bitcoin.it/wiki/Protocol_specification#block
64
fn read_block(&mut self) -> anyhow::Result<bitcoin::Block> {
75
Ok(bitcoin::Block::consensus_decode(self).unwrap())
86
}
97

10-
/// Reads a block as specified here: https://en.bitcoin.it/wiki/Protocol_specification#block
118
fn read_header(&mut self) -> anyhow::Result<bitcoin::blockdata::block::Header> {
129
Ok(bitcoin::blockdata::block::Header::consensus_decode(self).unwrap())
1310
}
1411
}
1512

16-
/// All types that implement `Read` get methods defined in `BlockchainRead`
17-
/// for free.
1813
impl<R: std::io::Read + ?Sized> BlockchainRead for R {}

src/parser/types.rs

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,18 @@ use bitcoin::hashes::sha256d;
22
use std::path::{Path, PathBuf};
33
use std::str::FromStr;
44

5-
/// Trait to specify the underlying coin of a blockchain
6-
/// Needs a proper magic value and a network id for address prefixes
75
pub trait Coin {
8-
// Human readable coin name
96
fn name(&self) -> String;
10-
// Magic value to identify blocks
7+
118
fn magic(&self) -> u32;
12-
// https://en.bitcoin.it/wiki/List_of_address_prefixes
9+
1310
fn version_id(&self) -> u8;
14-
// Returns genesis hash
11+
1512
fn genesis(&self) -> sha256d::Hash;
16-
// Default working directory to look for datadir, for example .bitcoin
13+
1714
fn default_folder(&self) -> PathBuf;
1815
}
1916

20-
// Implemented blockchain types.
21-
// If you want to add you own coin, create a struct with a Coin implementation
22-
// and add the coin name to from_str() below
2317
pub struct Bitcoin;
2418
pub struct TestNet3;
2519

@@ -42,7 +36,6 @@ impl Coin for Bitcoin {
4236
}
4337
}
4438

45-
/// Bitcoin testnet3
4639
impl Coin for TestNet3 {
4740
fn name(&self) -> String {
4841
String::from("TestNet3")
@@ -63,7 +56,6 @@ impl Coin for TestNet3 {
6356
}
6457

6558
#[derive(Clone)]
66-
// Holds the selected coin type information
6759
pub struct CoinType {
6860
pub name: String,
6961
pub magic: u32,

tests/bitcoin.rs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ fn test_bitcoin_genesis() {
1414

1515
assert_eq!(285, genesis.size());
1616

17-
// Block Header
1817
assert_eq!(0x0000_0001, genesis.header.version.to_consensus());
1918
assert_eq!(
2019
"0000000000000000000000000000000000000000000000000000000000000000",
@@ -29,7 +28,6 @@ fn test_bitcoin_genesis() {
2928
format!("{}", &genesis.header.block_hash())
3029
);
3130

32-
// Check against computed merkle root
3331
assert_eq!(
3432
&genesis.header.merkle_root,
3533
&genesis.compute_merkle_root().unwrap()
@@ -38,11 +36,9 @@ fn test_bitcoin_genesis() {
3836
assert_eq!(0x1d00_ffff, genesis.header.bits.to_consensus());
3937
assert_eq!(2_083_236_893, genesis.header.nonce);
4038

41-
// Tx
4239
assert_eq!(0x01, genesis.txdata.len());
4340
assert_eq!(0x0000_0001, genesis.txdata[0].version);
4441

45-
// Tx Inputs
4642
assert_eq!(0x01, genesis.txdata[0].input.len());
4743
assert_eq!(
4844
"0000000000000000000000000000000000000000000000000000000000000000",
@@ -66,7 +62,6 @@ fn test_bitcoin_genesis() {
6662
genesis.txdata[0].input[0].sequence.to_consensus_u32()
6763
);
6864

69-
// Tx Outputs
7065
assert_eq!(0x01, genesis.txdata[0].output.len());
7166
assert_eq!(
7267
u64::from_be(0x00f2_052a_0100_0000),

0 commit comments

Comments
 (0)