#![forbid(unsafe_code)]
#![deny(non_upper_case_globals)]
#![deny(non_camel_case_types)]
#![deny(non_snake_case)]
#![deny(unused_mut)]
#![deny(dead_code)]
#![deny(unused_imports)]
#![deny(missing_docs)]
#![deny(unused_must_use)]
use bitcoin::{Block, BlockHash, OutPoint, Transaction, TxOut, Txid};
use log::{info, Level};
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::mpsc::{sync_channel, SyncSender};
use std::thread;
use std::thread::JoinHandle;
use std::time::Instant;
use structopt::StructOpt;
mod fee;
mod parse;
mod read;
mod reorder;
mod truncmap;
#[derive(StructOpt, Debug, Clone)]
pub struct Config {
#[structopt(short, long)]
pub blocks_dir: PathBuf,
#[structopt(short, long)]
pub network: bitcoin::Network,
#[structopt(short, long)]
pub skip_prevout: bool,
#[structopt(short, long, default_value = "6")]
pub max_reorg: u8,
}
#[derive(Debug)]
pub struct BlockExtra {
pub block: Block,
pub block_hash: BlockHash,
pub size: u32,
pub next: Vec<BlockHash>,
pub height: u32,
pub outpoint_values: HashMap<OutPoint, TxOut>,
pub tx_hashes: HashSet<Txid>,
}
impl BlockExtra {
pub fn average_fee(&self) -> Option<f64> {
Some(self.fee()? as f64 / self.block.txdata.len() as f64)
}
pub fn fee(&self) -> Option<u64> {
let mut total = 0u64;
for tx in self.block.txdata.iter() {
total += self.tx_fee(tx)?;
}
Some(total)
}
pub fn tx_fee(&self, tx: &Transaction) -> Option<u64> {
let output_total: u64 = tx.output.iter().map(|el| el.value).sum();
let mut input_total = 0u64;
for input in tx.input.iter() {
input_total += self.outpoint_values.get(&input.previous_output)?.value;
}
Some(input_total - output_total)
}
}
pub fn iterate(config: Config, channel: SyncSender<Option<BlockExtra>>) -> JoinHandle<()> {
thread::spawn(move || {
let now = Instant::now();
let (send_blobs, receive_blobs) = sync_channel(2);
let mut read = read::Read::new(config.blocks_dir.clone(), send_blobs);
let read_handle = thread::spawn(move || {
read.start();
});
let (send_blocks, receive_blocks) = sync_channel(200);
let mut parse = parse::Parse::new(config.network, receive_blobs, send_blocks);
let parse_handle = thread::spawn(move || {
parse.start();
});
let (send_ordered_blocks, receive_ordered_blocks) = sync_channel(200);
let send_ordered_blocks = if config.skip_prevout {
channel.clone()
} else {
send_ordered_blocks
};
let mut reorder = reorder::Reorder::new(
config.network,
config.max_reorg,
receive_blocks,
send_ordered_blocks,
);
let orderer_handle = thread::spawn(move || {
reorder.start();
});
if !config.skip_prevout {
let mut fee = fee::Fee::new(receive_ordered_blocks, channel);
let fee_handle = thread::spawn(move || {
fee.start();
});
fee_handle.join().unwrap();
}
read_handle.join().unwrap();
parse_handle.join().unwrap();
orderer_handle.join().unwrap();
info!("Total time elapsed: {}s", now.elapsed().as_secs());
})
}
pub fn periodic_log_level(i: u32) -> Level {
if i % 10_000 == 0 {
Level::Info
} else {
Level::Debug
}
}