Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ resolver = "2"

[workspace.dependencies]
bitcoin = { git = "https://github.com/rust-bitcoin/rust-bitcoin", default-features = false, rev = "16cc257c3695dea0e7301a5fa9cab44b8ed60598" }
hintsfile = { version = "0.1.0" }
kernel = { package = "bitcoinkernel", git = "https://github.com/alexanderwiederin/rust-bitcoinkernel.git", rev = "353533221e3ba91d672418eab1ae7b83a61214f9" }
hintsfile = "0.2.0"
kernel = { package = "bitcoinkernel", version = "0.3.2" }
p2p = { package = "bitcoin-p2p", git = "https://github.com/2140-dev/bitcoin-p2p.git", rev = "a8b3af8dfc32a06eadb867b07afd537ebf347104" }
15 changes: 10 additions & 5 deletions node/src/bin/ibd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::{

use bitcoin::Network;
use hintsfile::Hintsfile;
use kernel::{ChainstateManager, ChainstateManagerOptions, ContextBuilder};
use kernel::{ChainstateManager, ContextBuilder};

use node::{
bootstrap_dns, elapsed_time, get_blocks_for_range, hashes_from_chain, sync_block_headers,
Expand Down Expand Up @@ -61,10 +61,12 @@ fn main() {
.chain_type(network.chain_type())
.build()
.unwrap();
let options = ChainstateManagerOptions::new(&ctx, ".", "./blocks").unwrap();
let chainman = ChainstateManager::new(options).unwrap();
let chainman = ChainstateManager::new(&ctx, ".", "./blocks").unwrap();
elapsed_time(kernel_start_time);
let tip = chainman.best_header().height();
let tip = chainman
.best_entry()
.expect("best entry must exist")
.height();
tracing::info!("Kernel best header: {tip}");
let chain = Arc::new(chainman);
sync_block_headers(
Expand All @@ -74,7 +76,10 @@ fn main() {
network,
timeout_conf,
);
tracing::info!("Assume valid height: {}", chain.best_header().height());
tracing::info!(
"Assume valid height: {}",
chain.best_entry().expect("best entry must exist").height()
);
let (tx, rx) = channel();
let main_routine_time = Instant::now();
let mut accumulator_state = AggregateState::new(rx);
Expand Down
96 changes: 69 additions & 27 deletions node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::{
net::{IpAddr, Ipv4Addr, SocketAddr},
path::PathBuf,
sync::{
mpsc::{Receiver, Sender},
mpsc::{channel, Receiver, Sender},
Arc, Mutex,
},
time::{Duration, Instant},
Expand All @@ -20,7 +20,8 @@ use bitcoin::{
BlockChecked, BlockHash, Network, OutPoint,
};
use hintsfile::Hintsfile;
use kernel::{ChainType, ChainstateManager};
use kernel::prelude::*;
use kernel::{ChainType, ChainstateManager, ProcessBlockHeaderResult};
use p2p::{
dns::DnsQueryExt,
handshake::ConnectionConfig,
Expand Down Expand Up @@ -64,13 +65,34 @@ impl AggregateState {
}
}

const DNS_RESOLVERS: [Ipv4Addr; 3] = [
Ipv4Addr::new(1, 1, 1, 1),
Ipv4Addr::new(8, 8, 8, 8),
Ipv4Addr::new(9, 9, 9, 9),
];
const DNS_TIMEOUT: Duration = Duration::from_secs(15);

pub fn bootstrap_dns(network: Network) -> Vec<SocketAddr> {
let cloudflare = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)), 53);
network
.query_dns_seeds(cloudflare)
.into_iter()
.map(|ip| SocketAddr::new(ip, network.default_p2p_port()))
.collect()
for resolver in DNS_RESOLVERS {
tracing::info!("Querying DNS seeds with resolver {resolver}");
// The UDP socket used for DNS queries has no read timeout, so an unreachable resolver
// blocks forever. Run the query on its own thread and move on if it takes too long.
let (tx, rx) = channel();
std::thread::spawn(move || {
let _ = tx.send(network.query_dns_seeds(SocketAddr::new(IpAddr::V4(resolver), 53)));
});
match rx.recv_timeout(DNS_TIMEOUT) {
Ok(ips) if !ips.is_empty() => {
return ips
.into_iter()
.map(|ip| SocketAddr::new(ip, network.default_p2p_port()))
.collect();
}
Ok(_) => tracing::warn!("Resolver {resolver} returned no peers"),
Err(_) => tracing::warn!("Resolver {resolver} timed out"),
}
}
Vec::new()
}

pub fn sync_block_headers(
Expand Down Expand Up @@ -99,8 +121,8 @@ pub fn sync_block_headers(
Err(_) => continue,
};
tracing::info!("Connection established");
let curr = chainman.best_header();
let locator = BlockHash::from_byte_array(curr.block_hash().hash);
let curr = chainman.best_entry().expect("best entry must exist");
let locator = BlockHash::from_byte_array(curr.block_hash().to_bytes());
let curr_height = curr.height() as u32;
if curr_height.eq(&stop_height) {
tracing::info!("Using existing header state");
Expand All @@ -122,10 +144,22 @@ pub fn sync_block_headers(
match message {
NetworkMessage::Headers(message) => {
for header in message.0 {
chainman
.process_new_block_headers(&consensus::serialize(&header), true)
.expect("process headers failed");
let curr_height = chainman.best_header().height() as u32;
let kernel_header =
kernel::BlockHeader::new(&consensus::serialize(&header))
.expect("valid header serialization");
match chainman
.process_block_header(&kernel_header)
.expect("process headers failed")
{
ProcessBlockHeaderResult::Valid => (),
ProcessBlockHeaderResult::Invalid(state) => {
panic!("invalid block header: {state:?}")
}
}
let curr_height = chainman
.best_entry()
.expect("best entry must exist")
.height() as u32;
if curr_height.eq(&stop_height) {
tracing::info!("Done syncing block headers");
if let Some(message_rate) =
Expand All @@ -139,8 +173,18 @@ pub fn sync_block_headers(
return;
}
}
tracing::info!("Update chain tip: {}", chainman.best_header().height());
let curr = chainman.best_header().block_hash().hash;
tracing::info!(
"Update chain tip: {}",
chainman
.best_entry()
.expect("best entry must exist")
.height()
);
let curr = chainman
.best_entry()
.expect("best entry must exist")
.block_hash()
.to_bytes();
let locator = BlockHash::from_byte_array(curr);
let getheaders = GetHeadersMessage {
version: PROTOCOL_VERSION,
Expand Down Expand Up @@ -227,11 +271,9 @@ pub fn get_blocks_for_range(
let hash = block.block_hash();
// tracing::info!("[thread {task_id:2}]: {hash}");
batch.retain(|b| hash.ne(b));
let kernal_hash: kernel::BlockHash = kernel::BlockHash {
hash: hash.to_byte_array(),
};
let kernel_hash = kernel::BlockHash::from(hash.to_byte_array());
let block_index = chain
.block_index_by_hash(kernal_hash)
.get_block_tree_entry(&kernel_hash)
.expect("header is in best chain.");
let block_height = block_index.height().unsigned_abs();
let unspent_indexes: HashSet<u32> = {
Expand Down Expand Up @@ -357,16 +399,16 @@ pub fn get_blocks_for_range(
}

pub fn hashes_from_chain(chain: Arc<ChainstateManager>) -> Vec<Vec<BlockHash>> {
let height = chain.best_header().height();
let height = chain.best_entry().expect("best entry must exist").height();
let mut hashes = Vec::with_capacity(height as usize);
let mut curr = chain.best_header();
let tip_hash = BlockHash::from_byte_array(curr.block_hash().hash);
let mut curr = chain.best_entry().expect("best entry must exist");
let tip_hash = BlockHash::from_byte_array(curr.block_hash().to_bytes());
hashes.push(tip_hash);
while let Ok(next) = curr.prev() {
while let Some(next) = curr.prev() {
if next.height() == 0 {
break;
}
let hash = BlockHash::from_byte_array(next.block_hash().hash);
let hash = BlockHash::from_byte_array(next.block_hash().to_bytes());
hashes.push(hash);
curr = next;
}
Expand All @@ -384,8 +426,8 @@ pub trait ChainExt {
impl ChainExt for Network {
fn chain_type(&self) -> ChainType {
match self {
Network::Bitcoin => ChainType::MAINNET,
Network::Signet => ChainType::SIGNET,
Network::Bitcoin => ChainType::Mainnet,
Network::Signet => ChainType::Signet,
_ => unimplemented!("choose bitcoin or signet"),
}
}
Expand Down
Loading