Skip to content

Commit

Permalink
Merge pull request #2 from rustaceanrob/btree-conv
Browse files Browse the repository at this point in the history
chain: stronger height type
  • Loading branch information
rustaceanrob authored Jun 2, 2024
2 parents b2cccc3 + 88f9de4 commit b0fc106
Show file tree
Hide file tree
Showing 13 changed files with 48 additions and 48 deletions.
20 changes: 10 additions & 10 deletions src/chain/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ impl Chain {
}

// The canoncial height of the chain, one less than the length
pub(crate) fn height(&self) -> usize {
pub(crate) fn height(&self) -> u32 {
self.header_chain.height()
}

Expand All @@ -126,12 +126,12 @@ impl Chain {
}

// This header chain contains a block hash
pub(crate) async fn height_of_hash(&self, blockhash: BlockHash) -> Option<usize> {
pub(crate) async fn height_of_hash(&self, blockhash: BlockHash) -> Option<u32> {
self.header_chain.height_of_hash(blockhash).await
}

// This header chain contains a block hash
pub(crate) async fn header_at_height(&self, height: usize) -> Option<&Header> {
pub(crate) async fn header_at_height(&self, height: u32) -> Option<&Header> {
self.header_chain.header_at_height(height)
}

Expand All @@ -146,7 +146,7 @@ impl Chain {
}

// Calculate the chainwork after a fork height to evalutate the fork
pub(crate) fn chainwork_after_height(&self, height: usize) -> Work {
pub(crate) fn chainwork_after_height(&self, height: u32) -> Work {
self.header_chain.chainwork_after_height(height)
}

Expand All @@ -171,7 +171,7 @@ impl Chain {
// Do we have best known height and is our height equal to it
pub(crate) fn is_synced(&self) -> bool {
if let Some(height) = self.best_known_height {
(self.height() as u32).ge(&height)
(self.height()).ge(&height)
} else {
false
}
Expand Down Expand Up @@ -377,7 +377,7 @@ impl Chain {
self.cf_header_chain.height(),
self.filter_chain.height(),
self.best_known_height
.unwrap_or(self.height() as u32)
.unwrap_or(self.height())
.try_into()
.unwrap(),
)
Expand Down Expand Up @@ -407,7 +407,7 @@ impl Chain {
}
// Did they send us the right amount of headers
let expected_stop_header = self
.header_at_height(self.cf_header_chain.height() + batch.len())
.header_at_height(self.cf_header_chain.height() + batch.len() as u32)
.await;
if let Some(stop_header) = expected_stop_header {
if stop_header.block_hash().ne(batch.stop_hash()) {
Expand Down Expand Up @@ -445,7 +445,7 @@ impl Chain {
if !self.is_cf_headers_synced() {
Some(GetCFHeaders {
filter_type: 0x00,
start_height: (self.cf_header_chain.height() + 1) as u32,
start_height: (self.cf_header_chain.height() + 1),
stop_hash,
})
} else {
Expand Down Expand Up @@ -515,7 +515,7 @@ impl Chain {
self.cf_header_chain.height(),
self.filter_chain.height(),
self.best_known_height
.unwrap_or(self.height() as u32)
.unwrap_or(self.height())
.try_into()
.unwrap(),
)
Expand All @@ -524,7 +524,7 @@ impl Chain {
if !self.is_filters_synced() {
Some(GetCFilters {
filter_type: 0x00,
start_height: (self.filter_chain.height() + 1) as u32,
start_height: self.filter_chain.height() + 1,
stop_hash,
})
} else {
Expand Down
10 changes: 5 additions & 5 deletions src/chain/checkpoints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ use std::{collections::VecDeque, str::FromStr};

use bitcoin::{BlockHash, Network};

pub const TESTNET_HEADER_CP: &[(usize, &str)] = &[(
pub const TESTNET_HEADER_CP: &[(u32, &str)] = &[(
546,
"000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70",
)];

pub const REGTEST_HEADER_CP: &[(usize, &str)] = &[(
pub const REGTEST_HEADER_CP: &[(u32, &str)] = &[(
0,
"0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206",
)];

pub const SIGNET_HEADER_CP: &[(usize, &str)] = &[
pub const SIGNET_HEADER_CP: &[(u32, &str)] = &[
(
0,
"00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6",
Expand Down Expand Up @@ -98,12 +98,12 @@ pub const SIGNET_HEADER_CP: &[(usize, &str)] = &[
#[derive(Debug, Clone, Copy)]

pub struct HeaderCheckpoint {
pub height: usize,
pub height: u32,
pub hash: BlockHash,
}

impl HeaderCheckpoint {
pub fn new(height: usize, hash: BlockHash) -> Self {
pub fn new(height: u32, hash: BlockHash) -> Self {
HeaderCheckpoint { height, hash }
}
}
Expand Down
18 changes: 9 additions & 9 deletions src/chain/header_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,15 @@ impl HeaderChain {
}

// The canoncial height of the chain, one less than the length
pub(crate) fn height(&self) -> usize {
self.headers.len() + self.anchor_checkpoint.height
pub(crate) fn height(&self) -> u32 {
self.headers.len() as u32 + self.anchor_checkpoint.height
}

// The adjusted height with respect to the indexes of the underlying vector.
// We do not actually have the header at the anchor height, so we need to offset
// the height by 1 to reflect that requesting height 0, for instance, will not
// yield a valid height.
fn adjusted_height(&self, height: usize) -> Option<usize> {
fn adjusted_height(&self, height: u32) -> Option<u32> {
height.checked_sub(self.anchor_checkpoint.height + 1)
}

Expand All @@ -70,19 +70,19 @@ impl HeaderChain {
}

// The height of the blockhash in the chain, accounting for the chain offset
pub(crate) async fn height_of_hash(&self, blockhash: BlockHash) -> Option<usize> {
pub(crate) async fn height_of_hash(&self, blockhash: BlockHash) -> Option<u32> {
let offset_pos = self
.headers
.iter()
.position(|header| header.block_hash().eq(&blockhash));
offset_pos.map(|index| self.anchor_checkpoint.height + index + 1)
offset_pos.map(|index| self.anchor_checkpoint.height + index as u32 + 1)
}

// This header chain contains a block hash
pub(crate) fn header_at_height(&self, height: usize) -> Option<&Header> {
pub(crate) fn header_at_height(&self, height: u32) -> Option<&Header> {
let offset = self.adjusted_height(height);
match offset {
Some(index) => self.headers.get(index),
Some(index) => self.headers.get(index as usize),
None => None,
}
}
Expand Down Expand Up @@ -110,15 +110,15 @@ impl HeaderChain {
}

// Calculate the chainwork after a fork height to evalutate the fork
pub(crate) fn chainwork_after_height(&self, height: usize) -> Work {
pub(crate) fn chainwork_after_height(&self, height: u32) -> Work {
let offset_height = height.checked_sub(self.anchor_checkpoint.height);
match offset_height {
Some(index) => {
let work = self
.headers
.iter()
.enumerate()
.filter(|(h, _)| h.ge(&index))
.filter(|(h, _)| (*h as u32).ge(&index))
.map(|(_, header)| header.work())
.reduce(|acc, next| acc + next);
match work {
Expand Down
4 changes: 2 additions & 2 deletions src/db/sqlite/header_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ impl SqliteHeaderDb {
impl HeaderStore for SqliteHeaderDb {
// load all the known headers from storage
async fn load(&mut self) -> Result<Vec<Header>, HeaderDatabaseError> {
let mut headers: Vec<Header> = Vec::with_capacity(self.last_checkpoint.height);
let mut headers: Vec<Header> = Vec::with_capacity(self.last_checkpoint.height as usize);
let stmt = "SELECT * FROM headers ORDER BY height";
let write_lock = self.conn.lock().await;
let mut query = write_lock
Expand Down Expand Up @@ -139,7 +139,7 @@ impl HeaderStore for SqliteHeaderDb {
let bits: u32 = header.bits.to_consensus();
let nonce: u32 = header.nonce;
// Do not allow rewrites before a checkpoint. if they were written to the db they were correct
let stmt = if height.le(&self.last_checkpoint.height) {
let stmt = if height.le(&(self.last_checkpoint.height as usize)) {
"INSERT OR IGNORE INTO headers (height, block_hash, version, prev_hash, merkle_root, time, bits, nonce) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)"
} else {
"INSERT OR REPLACE INTO headers (height, block_hash, version, prev_hash, merkle_root, time, bits, nonce) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)"
Expand Down
14 changes: 7 additions & 7 deletions src/filters/cfheader_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub(crate) enum AppendAttempt {
// We sucessfully extended the current chain and should broadcast the next round of CF header messages
Extended,
// We found a conflict in the peers CF header messages at this index
Conflict(usize),
Conflict(u32),
}

// Mapping from an append attempt to a message the node can handle
Expand Down Expand Up @@ -84,7 +84,7 @@ impl CFHeaderChain {
// Compare it to the other peer
if let Some(comparitor) = peer.get(index) {
if header.ne(&comparitor.0) {
return Ok(AppendAttempt::Conflict(self.height() + index + 1));
return Ok(AppendAttempt::Conflict(self.height() + index as u32 + 1));
}
}
}
Expand All @@ -96,8 +96,8 @@ impl CFHeaderChain {
Ok(AppendAttempt::Extended)
}

pub(crate) fn height(&self) -> usize {
self.anchor_checkpoint.height + self.header_chain.len()
pub(crate) fn height(&self) -> u32 {
self.anchor_checkpoint.height + self.header_chain.len() as u32
}

pub(crate) fn prev_header(&self) -> Option<FilterHeader> {
Expand All @@ -116,15 +116,15 @@ impl CFHeaderChain {
&self.prev_stophash_request
}

fn adjusted_height(&self, height: usize) -> Option<usize> {
fn adjusted_height(&self, height: u32) -> Option<u32> {
height.checked_sub(self.anchor_checkpoint.height + 1)
}

pub(crate) fn filter_hash_at_height(&self, height: usize) -> Option<FilterHash> {
pub(crate) fn filter_hash_at_height(&self, height: u32) -> Option<FilterHash> {
let adjusted_height = self.adjusted_height(height);
match adjusted_height {
Some(height) => {
if let Some((_, hash)) = self.header_chain.get(height) {
if let Some((_, hash)) = self.header_chain.get(height as usize) {
Some(*hash)
} else {
None
Expand Down
6 changes: 3 additions & 3 deletions src/filters/filter_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ impl FilterChain {
self.chain.clear()
}

pub(crate) fn height(&self) -> usize {
self.anchor_checkpoint.height + self.chain.len()
pub(crate) fn height(&self) -> u32 {
self.anchor_checkpoint.height + self.chain.len() as u32
}

pub(crate) fn set_last_stop_hash(&mut self, stop_hash: BlockHash) {
Expand All @@ -44,7 +44,7 @@ impl FilterChain {
&self.prev_stophash_request
}

fn adjusted_height(&self, height: usize) -> Option<usize> {
fn adjusted_height(&self, height: u32) -> Option<u32> {
height.checked_sub(self.anchor_checkpoint.height + 1)
}

Expand Down
4 changes: 2 additions & 2 deletions src/filters/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
pub const CF_HEADER_BATCH_SIZE: usize = 1_999;
pub const FILTER_BATCH_SIZE: usize = 99;
pub const CF_HEADER_BATCH_SIZE: u32 = 1_999;
pub const FILTER_BATCH_SIZE: u32 = 99;

pub(crate) mod cfheader_batch;
pub(crate) mod cfheader_chain;
Expand Down
6 changes: 3 additions & 3 deletions src/node/dialog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ impl Dialog {

pub(crate) async fn chain_update(
&mut self,
num_headers: usize,
num_cf_headers: usize,
num_filters: usize,
num_headers: u32,
num_cf_headers: u32,
num_filters: u32,
best_height: usize,
) {
let message = format!(
Expand Down
4 changes: 2 additions & 2 deletions src/node/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ impl Node {
}
}
let mut chain = self.chain.lock().await;
if chain.height().le(&(best_height as usize)) {
if chain.height().le(&best_height) {
chain.set_best_known_height(best_height).await;
}
// Even if we start the node as caught up in terms of height, we need to check for reorgs. So we can send this unconditionally.
Expand Down Expand Up @@ -545,7 +545,7 @@ impl Node {
locators: chain.locators(),
stop_hash: None,
};
if chain.height().le(&(new_height as usize)) {
if chain.height().le(&new_height) {
chain.set_best_known_height(new_height).await;
}
chain.clear_filter_header_queue();
Expand Down
2 changes: 1 addition & 1 deletion src/peers/dns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ impl Dns {
for host in seeds {
if let Ok(addrs) = dns_lookup::getaddrinfo(Some(host), None, None) {
for addr in addrs.filter_map(Result::ok) {
ip_addrs.push(addr.sockaddr.ip().into());
ip_addrs.push(addr.sockaddr.ip());
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/tx/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl TransactionStore for MemoryTransactionCache {
async fn add_transaction(
&mut self,
transaction: &Transaction,
height: Option<usize>,
height: Option<u32>,
hash: &BlockHash,
) -> Result<(), TransactionStoreError> {
self.transactions.push(IndexedTransaction {
Expand Down
2 changes: 1 addition & 1 deletion src/tx/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub trait TransactionStore {
async fn add_transaction(
&mut self,
transaction: &Transaction,
height: Option<usize>,
height: Option<u32>,
hash: &BlockHash,
) -> Result<(), TransactionStoreError>;

Expand Down
4 changes: 2 additions & 2 deletions src/tx/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ use bitcoin::{BlockHash, Transaction};
#[derive(Debug, Clone)]
pub struct IndexedTransaction {
pub transaction: Transaction,
pub height: Option<usize>,
pub height: Option<u32>,
pub hash: BlockHash,
}

impl IndexedTransaction {
pub fn new(transaction: Transaction, height: Option<usize>, hash: BlockHash) -> Self {
pub fn new(transaction: Transaction, height: Option<u32>, hash: BlockHash) -> Self {
Self {
transaction,
height,
Expand Down

0 comments on commit b0fc106

Please sign in to comment.