update monero-serai + change height to usize
Some checks are pending
Audit / audit (push) Waiting to run
Deny / audit (push) Waiting to run

This commit is contained in:
Boog900 2024-08-01 15:41:46 +01:00
parent 075e9b15cb
commit b83a06540c
No known key found for this signature in database
GPG key ID: 42AB1287CB0041C2
40 changed files with 266 additions and 247 deletions

48
Cargo.lock generated
View file

@ -404,6 +404,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"
dependencies = [ dependencies = [
"subtle", "subtle",
"zeroize",
] ]
[[package]] [[package]]
@ -465,6 +466,7 @@ dependencies = [
"paste", "paste",
"pretty_assertions", "pretty_assertions",
"rayon", "rayon",
"serde",
"tempfile", "tempfile",
"thread_local", "thread_local",
"tokio", "tokio",
@ -745,8 +747,10 @@ version = "0.0.0"
name = "cuprate-types" name = "cuprate-types"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"borsh",
"curve25519-dalek", "curve25519-dalek",
"monero-serai", "monero-serai",
"serde",
] ]
[[package]] [[package]]
@ -794,7 +798,7 @@ dependencies = [
[[package]] [[package]]
name = "dalek-ff-group" name = "dalek-ff-group"
version = "0.4.1" version = "0.4.1"
source = "git+https://github.com/Cuprate/serai.git?branch=monero-tidy#148137618a72c365b7e846a73292f01f53c0f941" source = "git+https://github.com/Cuprate/serai.git?rev=880565c#880565cb819e8b52883151d3b109713975561078"
dependencies = [ dependencies = [
"crypto-bigint", "crypto-bigint",
"curve25519-dalek", "curve25519-dalek",
@ -939,7 +943,7 @@ checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
[[package]] [[package]]
name = "flexible-transcript" name = "flexible-transcript"
version = "0.3.2" version = "0.3.2"
source = "git+https://github.com/Cuprate/serai.git?branch=monero-tidy#148137618a72c365b7e846a73292f01f53c0f941" source = "git+https://github.com/Cuprate/serai.git?rev=880565c#880565cb819e8b52883151d3b109713975561078"
dependencies = [ dependencies = [
"blake2", "blake2",
"digest", "digest",
@ -1582,10 +1586,23 @@ dependencies = [
"windows-sys 0.48.0", "windows-sys 0.48.0",
] ]
[[package]]
name = "monero-address"
version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?rev=880565c#880565cb819e8b52883151d3b109713975561078"
dependencies = [
"curve25519-dalek",
"monero-io",
"monero-primitives",
"std-shims",
"thiserror",
"zeroize",
]
[[package]] [[package]]
name = "monero-borromean" name = "monero-borromean"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?branch=monero-tidy#148137618a72c365b7e846a73292f01f53c0f941" source = "git+https://github.com/Cuprate/serai.git?rev=880565c#880565cb819e8b52883151d3b109713975561078"
dependencies = [ dependencies = [
"curve25519-dalek", "curve25519-dalek",
"monero-generators", "monero-generators",
@ -1598,7 +1615,7 @@ dependencies = [
[[package]] [[package]]
name = "monero-bulletproofs" name = "monero-bulletproofs"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?branch=monero-tidy#148137618a72c365b7e846a73292f01f53c0f941" source = "git+https://github.com/Cuprate/serai.git?rev=880565c#880565cb819e8b52883151d3b109713975561078"
dependencies = [ dependencies = [
"curve25519-dalek", "curve25519-dalek",
"monero-generators", "monero-generators",
@ -1606,7 +1623,6 @@ dependencies = [
"monero-primitives", "monero-primitives",
"rand_core", "rand_core",
"std-shims", "std-shims",
"subtle",
"thiserror", "thiserror",
"zeroize", "zeroize",
] ]
@ -1614,7 +1630,7 @@ dependencies = [
[[package]] [[package]]
name = "monero-clsag" name = "monero-clsag"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?branch=monero-tidy#148137618a72c365b7e846a73292f01f53c0f941" source = "git+https://github.com/Cuprate/serai.git?rev=880565c#880565cb819e8b52883151d3b109713975561078"
dependencies = [ dependencies = [
"curve25519-dalek", "curve25519-dalek",
"dalek-ff-group", "dalek-ff-group",
@ -1634,7 +1650,7 @@ dependencies = [
[[package]] [[package]]
name = "monero-generators" name = "monero-generators"
version = "0.4.0" version = "0.4.0"
source = "git+https://github.com/Cuprate/serai.git?branch=monero-tidy#148137618a72c365b7e846a73292f01f53c0f941" source = "git+https://github.com/Cuprate/serai.git?rev=880565c#880565cb819e8b52883151d3b109713975561078"
dependencies = [ dependencies = [
"curve25519-dalek", "curve25519-dalek",
"dalek-ff-group", "dalek-ff-group",
@ -1648,7 +1664,7 @@ dependencies = [
[[package]] [[package]]
name = "monero-io" name = "monero-io"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?branch=monero-tidy#148137618a72c365b7e846a73292f01f53c0f941" source = "git+https://github.com/Cuprate/serai.git?rev=880565c#880565cb819e8b52883151d3b109713975561078"
dependencies = [ dependencies = [
"curve25519-dalek", "curve25519-dalek",
"std-shims", "std-shims",
@ -1657,7 +1673,7 @@ dependencies = [
[[package]] [[package]]
name = "monero-mlsag" name = "monero-mlsag"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?branch=monero-tidy#148137618a72c365b7e846a73292f01f53c0f941" source = "git+https://github.com/Cuprate/serai.git?rev=880565c#880565cb819e8b52883151d3b109713975561078"
dependencies = [ dependencies = [
"curve25519-dalek", "curve25519-dalek",
"monero-generators", "monero-generators",
@ -1671,7 +1687,7 @@ dependencies = [
[[package]] [[package]]
name = "monero-primitives" name = "monero-primitives"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?branch=monero-tidy#148137618a72c365b7e846a73292f01f53c0f941" source = "git+https://github.com/Cuprate/serai.git?rev=880565c#880565cb819e8b52883151d3b109713975561078"
dependencies = [ dependencies = [
"curve25519-dalek", "curve25519-dalek",
"monero-generators", "monero-generators",
@ -1684,11 +1700,12 @@ dependencies = [
[[package]] [[package]]
name = "monero-rpc" name = "monero-rpc"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?branch=monero-tidy#148137618a72c365b7e846a73292f01f53c0f941" source = "git+https://github.com/Cuprate/serai.git?rev=880565c#880565cb819e8b52883151d3b109713975561078"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"curve25519-dalek", "curve25519-dalek",
"hex", "hex",
"monero-address",
"monero-serai", "monero-serai",
"serde", "serde",
"serde_json", "serde_json",
@ -1700,7 +1717,7 @@ dependencies = [
[[package]] [[package]]
name = "monero-serai" name = "monero-serai"
version = "0.1.4-alpha" version = "0.1.4-alpha"
source = "git+https://github.com/Cuprate/serai.git?branch=monero-tidy#148137618a72c365b7e846a73292f01f53c0f941" source = "git+https://github.com/Cuprate/serai.git?rev=880565c#880565cb819e8b52883151d3b109713975561078"
dependencies = [ dependencies = [
"curve25519-dalek", "curve25519-dalek",
"hex-literal", "hex-literal",
@ -1711,7 +1728,6 @@ dependencies = [
"monero-io", "monero-io",
"monero-mlsag", "monero-mlsag",
"monero-primitives", "monero-primitives",
"rand_core",
"std-shims", "std-shims",
"zeroize", "zeroize",
] ]
@ -1719,7 +1735,7 @@ dependencies = [
[[package]] [[package]]
name = "monero-simple-request-rpc" name = "monero-simple-request-rpc"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?branch=monero-tidy#148137618a72c365b7e846a73292f01f53c0f941" source = "git+https://github.com/Cuprate/serai.git?rev=880565c#880565cb819e8b52883151d3b109713975561078"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"digest_auth", "digest_auth",
@ -2367,7 +2383,7 @@ dependencies = [
[[package]] [[package]]
name = "simple-request" name = "simple-request"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?branch=monero-tidy#148137618a72c365b7e846a73292f01f53c0f941" source = "git+https://github.com/Cuprate/serai.git?rev=880565c#880565cb819e8b52883151d3b109713975561078"
dependencies = [ dependencies = [
"http-body-util", "http-body-util",
"hyper", "hyper",
@ -2423,7 +2439,7 @@ checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
[[package]] [[package]]
name = "std-shims" name = "std-shims"
version = "0.1.1" version = "0.1.1"
source = "git+https://github.com/Cuprate/serai.git?branch=monero-tidy#148137618a72c365b7e846a73292f01f53c0f941" source = "git+https://github.com/Cuprate/serai.git?rev=880565c#880565cb819e8b52883151d3b109713975561078"
dependencies = [ dependencies = [
"hashbrown 0.14.5", "hashbrown 0.14.5",
"spin", "spin",

View file

@ -63,9 +63,9 @@ futures = { version = "0.3.29", default-features = false }
hex = { version = "0.4.3", default-features = false } hex = { version = "0.4.3", default-features = false }
hex-literal = { version = "0.4", default-features = false } hex-literal = { version = "0.4", default-features = false }
indexmap = { version = "2.2.5", default-features = false } indexmap = { version = "2.2.5", default-features = false }
monero-rpc = { git = "https://github.com/Cuprate/serai.git", branch = "monero-tidy", default-features = false } monero-rpc = { git = "https://github.com/Cuprate/serai.git", rev = "880565c", default-features = false }
monero-simple-request-rpc = { git = "https://github.com/Cuprate/serai.git", branch = "monero-tidy", default-features = false } monero-simple-request-rpc = { git = "https://github.com/Cuprate/serai.git", rev = "880565c", default-features = false }
monero-serai = { git = "https://github.com/Cuprate/serai.git", branch = "monero-tidy", default-features = false } monero-serai = { git = "https://github.com/Cuprate/serai.git", rev = "880565c", default-features = false }
paste = { version = "1.0.14", default-features = false } paste = { version = "1.0.14", default-features = false }
pin-project = { version = "1.1.3", default-features = false } pin-project = { version = "1.1.3", default-features = false }
randomx-rs = { git = "https://github.com/Cuprate/randomx-rs.git", rev = "0028464", default-features = false } randomx-rs = { git = "https://github.com/Cuprate/randomx-rs.git", rev = "0028464", default-features = false }

View file

@ -10,13 +10,13 @@ use cuprate_types::blockchain::{BCReadRequest, BCResponse};
use cuprate_fast_sync::{hash_of_hashes, BlockId, HashOfHashes}; use cuprate_fast_sync::{hash_of_hashes, BlockId, HashOfHashes};
const BATCH_SIZE: u64 = 512; const BATCH_SIZE: usize = 512;
async fn read_batch( async fn read_batch(
handle: &mut DatabaseReadHandle, handle: &mut DatabaseReadHandle,
height_from: u64, height_from: usize,
) -> Result<Vec<BlockId>, RuntimeError> { ) -> Result<Vec<BlockId>, RuntimeError> {
let mut block_ids = Vec::<BlockId>::with_capacity(BATCH_SIZE as usize); let mut block_ids = Vec::<BlockId>::with_capacity(BATCH_SIZE);
for height in height_from..(height_from + BATCH_SIZE) { for height in height_from..(height_from + BATCH_SIZE) {
let request = BCReadRequest::BlockHash(height); let request = BCReadRequest::BlockHash(height);
@ -50,7 +50,7 @@ fn generate_hex(hashes: &[HashOfHashes]) -> String {
#[command(version, about, long_about = None)] #[command(version, about, long_about = None)]
struct Args { struct Args {
#[arg(short, long)] #[arg(short, long)]
height: u64, height: usize,
} }
#[tokio::main] #[tokio::main]
@ -64,7 +64,7 @@ async fn main() {
let mut hashes_of_hashes = Vec::new(); let mut hashes_of_hashes = Vec::new();
let mut height = 0u64; let mut height = 0_usize;
while height < height_target { while height < height_target {
match read_batch(&mut read_handle, height).await { match read_batch(&mut read_handle, height).await {

View file

@ -244,7 +244,7 @@ where
let block_blob = block.serialize(); let block_blob = block.serialize();
let Some(Input::Gen(height)) = block.miner_tx.prefix().inputs.first() else { let Some(Input::Gen(height)) = block.miner_transaction.prefix().inputs.first() else {
return Err(FastSyncError::MinerTx(MinerTxError::InputNotOfTypeGen)); return Err(FastSyncError::MinerTx(MinerTxError::InputNotOfTypeGen));
}; };
if *height != block_chain_ctx.chain_height { if *height != block_chain_ctx.chain_height {
@ -252,7 +252,7 @@ where
} }
let mut verified_txs = Vec::with_capacity(txs.len()); let mut verified_txs = Vec::with_capacity(txs.len());
for tx in &block.txs { for tx in &block.transactions {
let tx = txs let tx = txs
.remove(tx) .remove(tx)
.ok_or(FastSyncError::TxsIncludedWithBlockIncorrect)?; .ok_or(FastSyncError::TxsIncludedWithBlockIncorrect)?;
@ -269,7 +269,7 @@ where
let total_fees = verified_txs.iter().map(|tx| tx.fee).sum::<u64>(); let total_fees = verified_txs.iter().map(|tx| tx.fee).sum::<u64>();
let total_outputs = block let total_outputs = block
.miner_tx .miner_transaction
.prefix() .prefix()
.outputs .outputs
.iter() .iter()
@ -278,8 +278,8 @@ where
let generated_coins = total_outputs - total_fees; let generated_coins = total_outputs - total_fees;
let weight = let weight = block.miner_transaction.weight()
block.miner_tx.weight() + verified_txs.iter().map(|tx| tx.tx_weight).sum::<usize>(); + verified_txs.iter().map(|tx| tx.tx_weight).sum::<usize>();
Ok(FastSyncResponse::ValidateBlock(VerifiedBlockInformation { Ok(FastSyncResponse::ValidateBlock(VerifiedBlockInformation {
block_blob, block_blob,

View file

@ -21,8 +21,8 @@ pub const PENALTY_FREE_ZONE_1: usize = 20000;
pub const PENALTY_FREE_ZONE_2: usize = 60000; pub const PENALTY_FREE_ZONE_2: usize = 60000;
pub const PENALTY_FREE_ZONE_5: usize = 300000; pub const PENALTY_FREE_ZONE_5: usize = 300000;
pub const RX_SEEDHASH_EPOCH_BLOCKS: u64 = 2048; pub const RX_SEEDHASH_EPOCH_BLOCKS: usize = 2048;
pub const RX_SEEDHASH_EPOCH_LAG: u64 = 64; pub const RX_SEEDHASH_EPOCH_LAG: usize = 64;
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum BlockError { pub enum BlockError {
@ -52,14 +52,14 @@ pub trait RandomX {
} }
/// Returns if this height is a RandomX seed height. /// Returns if this height is a RandomX seed height.
pub fn is_randomx_seed_height(height: u64) -> bool { pub fn is_randomx_seed_height(height: usize) -> bool {
height % RX_SEEDHASH_EPOCH_BLOCKS == 0 height % RX_SEEDHASH_EPOCH_BLOCKS == 0
} }
/// Returns the RandomX seed height for this block. /// Returns the RandomX seed height for this block.
/// ///
/// ref: <https://monero-book.cuprate.org/consensus_rules/blocks.html#randomx-seed> /// ref: <https://monero-book.cuprate.org/consensus_rules/blocks.html#randomx-seed>
pub fn randomx_seed_height(height: u64) -> u64 { pub fn randomx_seed_height(height: usize) -> usize {
if height <= RX_SEEDHASH_EPOCH_BLOCKS + RX_SEEDHASH_EPOCH_LAG { if height <= RX_SEEDHASH_EPOCH_BLOCKS + RX_SEEDHASH_EPOCH_LAG {
0 0
} else { } else {
@ -75,7 +75,7 @@ pub fn randomx_seed_height(height: u64) -> u64 {
pub fn calculate_pow_hash<R: RandomX>( pub fn calculate_pow_hash<R: RandomX>(
randomx_vm: Option<&R>, randomx_vm: Option<&R>,
buf: &[u8], buf: &[u8],
height: u64, height: usize,
hf: &HardFork, hf: &HardFork,
) -> Result<[u8; 32], BlockError> { ) -> Result<[u8; 32], BlockError> {
if height == 202612 { if height == 202612 {
@ -89,7 +89,7 @@ pub fn calculate_pow_hash<R: RandomX>(
} else if hf < &HardFork::V10 { } else if hf < &HardFork::V10 {
cryptonight_hash_v2(buf) cryptonight_hash_v2(buf)
} else if hf < &HardFork::V12 { } else if hf < &HardFork::V12 {
cryptonight_hash_r(buf, height) cryptonight_hash_r(buf, height as u64)
} else { } else {
randomx_vm randomx_vm
.expect("RandomX VM needed from hf 12") .expect("RandomX VM needed from hf 12")
@ -220,7 +220,7 @@ pub struct ContextToVerifyBlock {
/// Contains the median timestamp over the last 60 blocks, if there is less than 60 blocks this should be [`None`] /// Contains the median timestamp over the last 60 blocks, if there is less than 60 blocks this should be [`None`]
pub median_block_timestamp: Option<u64>, pub median_block_timestamp: Option<u64>,
/// The current chain height. /// The current chain height.
pub chain_height: u64, pub chain_height: usize,
/// The current hard-fork. /// The current hard-fork.
pub current_hf: HardFork, pub current_hf: HardFork,
/// ref: <https://monero-book.cuprate.org/consensus_rules/blocks/difficulty.html#calculating-difficulty> /// ref: <https://monero-book.cuprate.org/consensus_rules/blocks/difficulty.html#calculating-difficulty>
@ -263,11 +263,11 @@ pub fn check_block(
check_block_weight(block_weight, block_chain_ctx.median_weight_for_block_reward)?; check_block_weight(block_weight, block_chain_ctx.median_weight_for_block_reward)?;
block_size_sanity_check(block_blob_len, block_chain_ctx.effective_median_weight)?; block_size_sanity_check(block_blob_len, block_chain_ctx.effective_median_weight)?;
check_amount_txs(block.txs.len())?; check_amount_txs(block.transactions.len())?;
check_txs_unique(&block.txs)?; check_txs_unique(&block.transactions)?;
let generated_coins = check_miner_tx( let generated_coins = check_miner_tx(
&block.miner_tx, &block.miner_transaction,
total_fees, total_fees,
block_chain_ctx.chain_height, block_chain_ctx.chain_height,
block_weight, block_weight,

View file

@ -35,8 +35,8 @@ pub fn generate_genesis_block(network: &Network) -> Block {
previous: [0; 32], previous: [0; 32],
nonce: genesis_nonce(network), nonce: genesis_nonce(network),
}, },
miner_tx: genesis_miner_tx(network), miner_transaction: genesis_miner_tx(network),
txs: vec![], transactions: vec![],
} }
} }

View file

@ -40,11 +40,11 @@ pub enum HardForkError {
/// Information about a given hard-fork. /// Information about a given hard-fork.
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub struct HFInfo { pub struct HFInfo {
height: u64, height: usize,
threshold: u64, threshold: usize,
} }
impl HFInfo { impl HFInfo {
pub const fn new(height: u64, threshold: u64) -> HFInfo { pub const fn new(height: usize, threshold: usize) -> HFInfo {
HFInfo { height, threshold } HFInfo { height, threshold }
} }
} }
@ -245,7 +245,7 @@ impl HardFork {
/// A struct holding the current voting state of the blockchain. /// A struct holding the current voting state of the blockchain.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct HFVotes { pub struct HFVotes {
votes: [u64; NUMB_OF_HARD_FORKS], votes: [usize; NUMB_OF_HARD_FORKS],
vote_list: VecDeque<HardFork>, vote_list: VecDeque<HardFork>,
window_size: usize, window_size: usize,
} }
@ -296,13 +296,13 @@ impl HFVotes {
/// Returns the total votes for a hard-fork. /// Returns the total votes for a hard-fork.
/// ///
/// ref: <https://monero-book.cuprate.org/consensus_rules/hardforks.html#accepting-a-fork> /// ref: <https://monero-book.cuprate.org/consensus_rules/hardforks.html#accepting-a-fork>
pub fn votes_for_hf(&self, hf: &HardFork) -> u64 { pub fn votes_for_hf(&self, hf: &HardFork) -> usize {
self.votes[*hf as usize - 1..].iter().sum() self.votes[*hf as usize - 1..].iter().sum()
} }
/// Returns the total amount of votes being tracked /// Returns the total amount of votes being tracked
pub fn total_votes(&self) -> u64 { pub fn total_votes(&self) -> usize {
self.votes.iter().sum() self.vote_list.len()
} }
/// Checks if a future hard fork should be activated, returning the next hard-fork that should be /// Checks if a future hard fork should be activated, returning the next hard-fork that should be
@ -312,8 +312,8 @@ impl HFVotes {
pub fn current_fork( pub fn current_fork(
&self, &self,
current_hf: &HardFork, current_hf: &HardFork,
current_height: u64, current_height: usize,
window: u64, window: usize,
hfs_info: &HFsInfo, hfs_info: &HFsInfo,
) -> HardFork { ) -> HardFork {
let mut current_hf = *current_hf; let mut current_hf = *current_hf;
@ -339,6 +339,6 @@ impl HFVotes {
/// Returns the votes needed for a hard-fork. /// Returns the votes needed for a hard-fork.
/// ///
/// ref: <https://monero-book.cuprate.org/consensus_rules/hardforks.html#accepting-a-fork> /// ref: <https://monero-book.cuprate.org/consensus_rules/hardforks.html#accepting-a-fork>
pub fn votes_needed(threshold: u64, window: u64) -> u64 { pub fn votes_needed(threshold: usize, window: usize) -> usize {
(threshold * window).div_ceil(100) (threshold * window).div_ceil(100)
} }

View file

@ -32,7 +32,7 @@ const MONEY_SUPPLY: u64 = u64::MAX;
/// The minimum block reward per minute, "tail-emission" /// The minimum block reward per minute, "tail-emission"
const MINIMUM_REWARD_PER_MIN: u64 = 3 * 10_u64.pow(11); const MINIMUM_REWARD_PER_MIN: u64 = 3 * 10_u64.pow(11);
/// The value which `lock_time` should be for a coinbase output. /// The value which `lock_time` should be for a coinbase output.
const MINER_TX_TIME_LOCKED_BLOCKS: u64 = 60; const MINER_TX_TIME_LOCKED_BLOCKS: usize = 60;
/// Calculates the base block reward without taking away the penalty for expanding /// Calculates the base block reward without taking away the penalty for expanding
/// the block. /// the block.
@ -85,7 +85,7 @@ fn check_miner_tx_version(tx_version: &TxVersion, hf: &HardFork) -> Result<(), M
/// Checks the miner transactions inputs. /// Checks the miner transactions inputs.
/// ///
/// ref: <https://monero-book.cuprate.org/consensus_rules/blocks/miner_tx.html#input> /// ref: <https://monero-book.cuprate.org/consensus_rules/blocks/miner_tx.html#input>
fn check_inputs(inputs: &[Input], chain_height: u64) -> Result<(), MinerTxError> { fn check_inputs(inputs: &[Input], chain_height: usize) -> Result<(), MinerTxError> {
if inputs.len() != 1 { if inputs.len() != 1 {
return Err(MinerTxError::IncorrectNumbOfInputs); return Err(MinerTxError::IncorrectNumbOfInputs);
} }
@ -105,15 +105,15 @@ fn check_inputs(inputs: &[Input], chain_height: u64) -> Result<(), MinerTxError>
/// Checks the miner transaction has a correct time lock. /// Checks the miner transaction has a correct time lock.
/// ///
/// ref: <https://monero-book.cuprate.org/consensus_rules/blocks/miner_tx.html#unlock-time> /// ref: <https://monero-book.cuprate.org/consensus_rules/blocks/miner_tx.html#unlock-time>
fn check_time_lock(time_lock: &Timelock, chain_height: u64) -> Result<(), MinerTxError> { fn check_time_lock(time_lock: &Timelock, chain_height: usize) -> Result<(), MinerTxError> {
match time_lock { match time_lock {
Timelock::Block(till_height) => { &Timelock::Block(till_height) => {
// Lock times above this amount are timestamps not blocks. // Lock times above this amount are timestamps not blocks.
// This is just for safety though and shouldn't actually be hit. // This is just for safety though and shouldn't actually be hit.
if till_height > &500_000_000 { if till_height > 500_000_000 {
Err(MinerTxError::InvalidLockTime)?; Err(MinerTxError::InvalidLockTime)?;
} }
if u64::try_from(*till_height).unwrap() != chain_height + MINER_TX_TIME_LOCKED_BLOCKS { if till_height != chain_height + MINER_TX_TIME_LOCKED_BLOCKS {
Err(MinerTxError::InvalidLockTime) Err(MinerTxError::InvalidLockTime)
} else { } else {
Ok(()) Ok(())
@ -179,7 +179,7 @@ fn check_total_output_amt(
pub fn check_miner_tx( pub fn check_miner_tx(
tx: &Transaction, tx: &Transaction,
total_fees: u64, total_fees: u64,
chain_height: u64, chain_height: usize,
block_weight: usize, block_weight: usize,
median_bw: usize, median_bw: usize,
already_generated_coins: u64, already_generated_coins: u64,
@ -198,7 +198,7 @@ pub fn check_miner_tx(
} }
} }
check_time_lock(&tx.prefix().timelock, chain_height)?; check_time_lock(&tx.prefix().additional_timelock, chain_height)?;
check_inputs(&tx.prefix().inputs, chain_height)?; check_inputs(&tx.prefix().inputs, chain_height)?;

View file

@ -247,14 +247,14 @@ fn check_outputs_semantics(
/// <https://monero-book.cuprate.org/consensus_rules/transactions/unlock_time.html> /// <https://monero-book.cuprate.org/consensus_rules/transactions/unlock_time.html>
pub fn output_unlocked( pub fn output_unlocked(
time_lock: &Timelock, time_lock: &Timelock,
current_chain_height: u64, current_chain_height: usize,
current_time_lock_timestamp: u64, current_time_lock_timestamp: u64,
hf: &HardFork, hf: &HardFork,
) -> bool { ) -> bool {
match *time_lock { match *time_lock {
Timelock::None => true, Timelock::None => true,
Timelock::Block(unlock_height) => { Timelock::Block(unlock_height) => {
check_block_time_lock(unlock_height.try_into().unwrap(), current_chain_height) check_block_time_lock(unlock_height, current_chain_height)
} }
Timelock::Time(unlock_time) => { Timelock::Time(unlock_time) => {
check_timestamp_time_lock(unlock_time, current_time_lock_timestamp, hf) check_timestamp_time_lock(unlock_time, current_time_lock_timestamp, hf)
@ -265,7 +265,7 @@ pub fn output_unlocked(
/// Returns if a locked output, which uses a block height, can be spent. /// Returns if a locked output, which uses a block height, can be spent.
/// ///
/// ref: <https://monero-book.cuprate.org/consensus_rules/transactions/unlock_time.html#block-height> /// ref: <https://monero-book.cuprate.org/consensus_rules/transactions/unlock_time.html#block-height>
fn check_block_time_lock(unlock_height: u64, current_chain_height: u64) -> bool { fn check_block_time_lock(unlock_height: usize, current_chain_height: usize) -> bool {
// current_chain_height = 1 + top height // current_chain_height = 1 + top height
unlock_height <= current_chain_height unlock_height <= current_chain_height
} }
@ -289,7 +289,7 @@ fn check_timestamp_time_lock(
/// <https://monero-book.cuprate.org/consensus_rules/transactions/inputs.html#the-output-must-not-be-locked> /// <https://monero-book.cuprate.org/consensus_rules/transactions/inputs.html#the-output-must-not-be-locked>
fn check_all_time_locks( fn check_all_time_locks(
time_locks: &[Timelock], time_locks: &[Timelock],
current_chain_height: u64, current_chain_height: usize,
current_time_lock_timestamp: u64, current_time_lock_timestamp: u64,
hf: &HardFork, hf: &HardFork,
) -> Result<(), TransactionError> { ) -> Result<(), TransactionError> {
@ -434,8 +434,8 @@ fn check_inputs_sorted(inputs: &[Input], hf: &HardFork) -> Result<(), Transactio
/// ///
/// ref: <https://monero-book.cuprate.org/consensus_rules/transactions/inputs.html#10-block-lock> /// ref: <https://monero-book.cuprate.org/consensus_rules/transactions/inputs.html#10-block-lock>
fn check_10_block_lock( fn check_10_block_lock(
youngest_used_out_height: u64, youngest_used_out_height: usize,
current_chain_height: u64, current_chain_height: usize,
hf: &HardFork, hf: &HardFork,
) -> Result<(), TransactionError> { ) -> Result<(), TransactionError> {
if hf >= &HardFork::V12 { if hf >= &HardFork::V12 {
@ -502,7 +502,7 @@ fn check_inputs_semantics(inputs: &[Input], hf: &HardFork) -> Result<u64, Transa
fn check_inputs_contextual( fn check_inputs_contextual(
inputs: &[Input], inputs: &[Input],
tx_ring_members_info: &TxRingMembersInfo, tx_ring_members_info: &TxRingMembersInfo,
current_chain_height: u64, current_chain_height: usize,
hf: &HardFork, hf: &HardFork,
) -> Result<(), TransactionError> { ) -> Result<(), TransactionError> {
// This rule is not contained in monero-core explicitly, but it is enforced by how Monero picks ring members. // This rule is not contained in monero-core explicitly, but it is enforced by how Monero picks ring members.
@ -659,7 +659,7 @@ pub fn check_transaction_semantic(
pub fn check_transaction_contextual( pub fn check_transaction_contextual(
tx: &Transaction, tx: &Transaction,
tx_ring_members_info: &TxRingMembersInfo, tx_ring_members_info: &TxRingMembersInfo,
current_chain_height: u64, current_chain_height: usize,
current_time_lock_timestamp: u64, current_time_lock_timestamp: u64,
hf: &HardFork, hf: &HardFork,
) -> Result<(), TransactionError> { ) -> Result<(), TransactionError> {

View file

@ -70,7 +70,7 @@ pub struct TxRingMembersInfo {
pub rings: Rings, pub rings: Rings,
/// Information on the structure of the decoys, must be [`None`] for txs before [`HardFork::V1`] /// Information on the structure of the decoys, must be [`None`] for txs before [`HardFork::V1`]
pub decoy_info: Option<DecoyInfo>, pub decoy_info: Option<DecoyInfo>,
pub youngest_used_out_height: u64, pub youngest_used_out_height: usize,
pub time_locked_outs: Vec<Timelock>, pub time_locked_outs: Vec<Timelock>,
} }

View file

@ -75,8 +75,8 @@ fn simple_type_balances(rct_sig: &RctProofs) -> Result<(), RingCTError> {
}; };
let sum_inputs = pseudo_outs.iter().sum::<EdwardsPoint>(); let sum_inputs = pseudo_outs.iter().sum::<EdwardsPoint>();
let sum_outputs = rct_sig.base.commitments.iter().sum::<EdwardsPoint>() let sum_outputs =
+ Scalar::from(rct_sig.base.fee) * H(); rct_sig.base.commitments.iter().sum::<EdwardsPoint>() + Scalar::from(rct_sig.base.fee) * *H;
if sum_inputs == sum_outputs { if sum_inputs == sum_outputs {
Ok(()) Ok(())

View file

@ -53,7 +53,7 @@ pub struct PreparedBlockExPow {
/// The block's hash. /// The block's hash.
pub block_hash: [u8; 32], pub block_hash: [u8; 32],
/// The height of the block. /// The height of the block.
pub height: u64, pub height: usize,
/// The weight of the block's miner transaction. /// The weight of the block's miner transaction.
pub miner_tx_weight: usize, pub miner_tx_weight: usize,
@ -70,7 +70,7 @@ impl PreparedBlockExPow {
let (hf_version, hf_vote) = let (hf_version, hf_vote) =
HardFork::from_block_header(&block.header).map_err(BlockError::HardForkError)?; HardFork::from_block_header(&block.header).map_err(BlockError::HardForkError)?;
let Some(Input::Gen(height)) = block.miner_tx.prefix().inputs.first() else { let Some(Input::Gen(height)) = block.miner_transaction.prefix().inputs.first() else {
Err(ConsensusError::Block(BlockError::MinerTxError( Err(ConsensusError::Block(BlockError::MinerTxError(
MinerTxError::InputNotOfTypeGen, MinerTxError::InputNotOfTypeGen,
)))? )))?
@ -84,7 +84,7 @@ impl PreparedBlockExPow {
block_hash: block.hash(), block_hash: block.hash(),
height: *height, height: *height,
miner_tx_weight: block.miner_tx.weight(), miner_tx_weight: block.miner_transaction.weight(),
block, block,
}) })
} }
@ -124,7 +124,7 @@ impl PreparedBlock {
let (hf_version, hf_vote) = let (hf_version, hf_vote) =
HardFork::from_block_header(&block.header).map_err(BlockError::HardForkError)?; HardFork::from_block_header(&block.header).map_err(BlockError::HardForkError)?;
let Some(Input::Gen(height)) = block.miner_tx.prefix().inputs.first() else { let Some(Input::Gen(height)) = block.miner_transaction.prefix().inputs.first() else {
Err(ConsensusError::Block(BlockError::MinerTxError( Err(ConsensusError::Block(BlockError::MinerTxError(
MinerTxError::InputNotOfTypeGen, MinerTxError::InputNotOfTypeGen,
)))? )))?
@ -143,7 +143,7 @@ impl PreparedBlock {
&hf_version, &hf_version,
)?, )?,
miner_tx_weight: block.miner_tx.weight(), miner_tx_weight: block.miner_transaction.weight(),
block, block,
}) })
} }
@ -173,7 +173,7 @@ impl PreparedBlock {
&block.hf_version, &block.hf_version,
)?, )?,
miner_tx_weight: block.block.miner_tx.weight(), miner_tx_weight: block.block.miner_transaction.weight(),
block: block.block, block: block.block,
}) })
} }
@ -476,7 +476,7 @@ where
// Order the txs correctly. // Order the txs correctly.
let mut ordered_txs = Vec::with_capacity(txs.len()); let mut ordered_txs = Vec::with_capacity(txs.len());
for tx_hash in &block.block.txs { for tx_hash in &block.block.transactions {
let tx = txs let tx = txs
.remove(tx_hash) .remove(tx_hash)
.ok_or(ExtendedConsensusError::TxsIncludedWithBlockIncorrect)?; .ok_or(ExtendedConsensusError::TxsIncludedWithBlockIncorrect)?;
@ -561,8 +561,8 @@ where
tracing::debug!("Ordering transactions for block."); tracing::debug!("Ordering transactions for block.");
if !prepped_block.block.txs.is_empty() { if !prepped_block.block.transactions.is_empty() {
for tx_hash in &prepped_block.block.txs { for tx_hash in &prepped_block.block.transactions {
let tx = txs let tx = txs
.remove(tx_hash) .remove(tx_hash)
.ok_or(ExtendedConsensusError::TxsIncludedWithBlockIncorrect)?; .ok_or(ExtendedConsensusError::TxsIncludedWithBlockIncorrect)?;
@ -621,12 +621,12 @@ where
check_block_pow(&prepped_block.pow_hash, context.next_difficulty) check_block_pow(&prepped_block.pow_hash, context.next_difficulty)
.map_err(ConsensusError::Block)?; .map_err(ConsensusError::Block)?;
if prepped_block.block.txs.len() != txs.len() { if prepped_block.block.transactions.len() != txs.len() {
return Err(ExtendedConsensusError::TxsIncludedWithBlockIncorrect); return Err(ExtendedConsensusError::TxsIncludedWithBlockIncorrect);
} }
if !prepped_block.block.txs.is_empty() { if !prepped_block.block.transactions.is_empty() {
for (expected_tx_hash, tx) in prepped_block.block.txs.iter().zip(txs.iter()) { for (expected_tx_hash, tx) in prepped_block.block.transactions.iter().zip(txs.iter()) {
if expected_tx_hash != &tx.tx_hash { if expected_tx_hash != &tx.tx_hash {
return Err(ExtendedConsensusError::TxsIncludedWithBlockIncorrect); return Err(ExtendedConsensusError::TxsIncludedWithBlockIncorrect);
} }

View file

@ -196,7 +196,7 @@ pub struct NewBlockData {
/// The blocks hash. /// The blocks hash.
pub block_hash: [u8; 32], pub block_hash: [u8; 32],
/// The blocks height. /// The blocks height.
pub height: u64, pub height: usize,
/// The blocks timestamp. /// The blocks timestamp.
pub timestamp: u64, pub timestamp: u64,
/// The blocks weight. /// The blocks weight.
@ -239,7 +239,7 @@ pub enum BlockChainContextResponse {
/// Blockchain context response. /// Blockchain context response.
Context(BlockChainContext), Context(BlockChainContext),
/// A map of seed height to RandomX VMs. /// A map of seed height to RandomX VMs.
RxVms(HashMap<u64, Arc<RandomXVM>>), RxVms(HashMap<usize, Arc<RandomXVM>>),
/// A list of difficulties. /// A list of difficulties.
BatchDifficulties(Vec<u128>), BatchDifficulties(Vec<u128>),
/// Ok response. /// Ok response.

View file

@ -45,8 +45,8 @@ impl DifficultyCacheConfig {
} }
/// Returns the total amount of blocks we need to track to calculate difficulty /// Returns the total amount of blocks we need to track to calculate difficulty
pub fn total_block_count(&self) -> u64 { pub fn total_block_count(&self) -> usize {
(self.window + self.lag).try_into().unwrap() self.window + self.lag
} }
/// The amount of blocks we account for after removing the outliers. /// The amount of blocks we account for after removing the outliers.
@ -75,7 +75,7 @@ pub(crate) struct DifficultyCache {
/// The current cumulative difficulty of the chain. /// The current cumulative difficulty of the chain.
pub(crate) cumulative_difficulties: VecDeque<u128>, pub(crate) cumulative_difficulties: VecDeque<u128>,
/// The last height we accounted for. /// The last height we accounted for.
pub(crate) last_accounted_height: u64, pub(crate) last_accounted_height: usize,
/// The config /// The config
pub(crate) config: DifficultyCacheConfig, pub(crate) config: DifficultyCacheConfig,
} }
@ -84,7 +84,7 @@ impl DifficultyCache {
/// Initialize the difficulty cache from the specified chain height. /// Initialize the difficulty cache from the specified chain height.
#[instrument(name = "init_difficulty_cache", level = "info", skip(database, config))] #[instrument(name = "init_difficulty_cache", level = "info", skip(database, config))]
pub async fn init_from_chain_height<D: Database + Clone>( pub async fn init_from_chain_height<D: Database + Clone>(
chain_height: u64, chain_height: usize,
config: DifficultyCacheConfig, config: DifficultyCacheConfig,
database: D, database: D,
) -> Result<Self, ExtendedConsensusError> { ) -> Result<Self, ExtendedConsensusError> {
@ -117,7 +117,7 @@ impl DifficultyCache {
} }
/// Add a new block to the difficulty cache. /// Add a new block to the difficulty cache.
pub fn new_block(&mut self, height: u64, timestamp: u64, cumulative_difficulty: u128) { pub fn new_block(&mut self, height: usize, timestamp: u64, cumulative_difficulty: u128) {
assert_eq!(self.last_accounted_height + 1, height); assert_eq!(self.last_accounted_height + 1, height);
self.last_accounted_height += 1; self.last_accounted_height += 1;
@ -129,7 +129,7 @@ impl DifficultyCache {
self.cumulative_difficulties self.cumulative_difficulties
.push_back(cumulative_difficulty); .push_back(cumulative_difficulty);
if u64::try_from(self.timestamps.len()).unwrap() > self.config.total_block_count() { if self.timestamps.len() > self.config.total_block_count() {
self.timestamps.pop_front(); self.timestamps.pop_front();
self.cumulative_difficulties.pop_front(); self.cumulative_difficulties.pop_front();
} }
@ -174,7 +174,7 @@ impl DifficultyCache {
let last_cum_diff = cumulative_difficulties.back().copied().unwrap_or(1); let last_cum_diff = cumulative_difficulties.back().copied().unwrap_or(1);
cumulative_difficulties.push_back(last_cum_diff + *difficulties.last().unwrap()); cumulative_difficulties.push_back(last_cum_diff + *difficulties.last().unwrap());
if u64::try_from(timestamps.len()).unwrap() > self.config.total_block_count() { if timestamps.len() > self.config.total_block_count() {
diff_info_popped.push(( diff_info_popped.push((
timestamps.pop_front().unwrap(), timestamps.pop_front().unwrap(),
cumulative_difficulties.pop_front().unwrap(), cumulative_difficulties.pop_front().unwrap(),
@ -196,22 +196,21 @@ impl DifficultyCache {
/// ///
/// Will return [`None`] if there aren't enough blocks. /// Will return [`None`] if there aren't enough blocks.
pub fn median_timestamp(&self, numb_blocks: usize) -> Option<u64> { pub fn median_timestamp(&self, numb_blocks: usize) -> Option<u64> {
let mut timestamps = let mut timestamps = if self.last_accounted_height + 1 == numb_blocks {
if self.last_accounted_height + 1 == u64::try_from(numb_blocks).unwrap() { // if the chain height is equal to `numb_blocks` add the genesis block.
// if the chain height is equal to `numb_blocks` add the genesis block. // otherwise if the chain height is less than `numb_blocks` None is returned
// otherwise if the chain height is less than `numb_blocks` None is returned // and if its more than it would be excluded from calculations.
// and if its more than it would be excluded from calculations. let mut timestamps = self.timestamps.clone();
let mut timestamps = self.timestamps.clone(); // all genesis blocks have a timestamp of 0.
// all genesis blocks have a timestamp of 0. // https://cuprate.github.io/monero-book/consensus_rules/genesis_block.html
// https://cuprate.github.io/monero-book/consensus_rules/genesis_block.html timestamps.push_front(0);
timestamps.push_front(0); timestamps.into()
timestamps.into() } else {
} else { self.timestamps
self.timestamps .range(self.timestamps.len().checked_sub(numb_blocks)?..)
.range(self.timestamps.len().checked_sub(numb_blocks)?..) .copied()
.copied() .collect::<Vec<_>>()
.collect::<Vec<_>>() };
};
timestamps.sort_unstable(); timestamps.sort_unstable();
debug_assert_eq!(timestamps.len(), numb_blocks); debug_assert_eq!(timestamps.len(), numb_blocks);
@ -298,7 +297,7 @@ fn get_window_start_and_end(
#[instrument(name = "get_blocks_timestamps", skip(database), level = "info")] #[instrument(name = "get_blocks_timestamps", skip(database), level = "info")]
async fn get_blocks_in_pow_info<D: Database + Clone>( async fn get_blocks_in_pow_info<D: Database + Clone>(
database: D, database: D,
block_heights: Range<u64>, block_heights: Range<usize>,
) -> Result<(VecDeque<u64>, VecDeque<u128>), ExtendedConsensusError> { ) -> Result<(VecDeque<u64>, VecDeque<u128>), ExtendedConsensusError> {
tracing::info!("Getting blocks timestamps"); tracing::info!("Getting blocks timestamps");

View file

@ -11,7 +11,7 @@ use crate::{Database, ExtendedConsensusError};
/// The default amount of hard-fork votes to track to decide on activation of a hard-fork. /// The default amount of hard-fork votes to track to decide on activation of a hard-fork.
/// ///
/// ref: <https://cuprate.github.io/monero-docs/consensus_rules/hardforks.html#accepting-a-fork> /// ref: <https://cuprate.github.io/monero-docs/consensus_rules/hardforks.html#accepting-a-fork>
const DEFAULT_WINDOW_SIZE: u64 = 10080; // supermajority window check length - a week const DEFAULT_WINDOW_SIZE: usize = 10080; // supermajority window check length - a week
/// Configuration for hard-forks. /// Configuration for hard-forks.
/// ///
@ -20,7 +20,7 @@ pub struct HardForkConfig {
/// The network we are on. /// The network we are on.
pub(crate) info: HFsInfo, pub(crate) info: HFsInfo,
/// The amount of votes we are taking into account to decide on a fork activation. /// The amount of votes we are taking into account to decide on a fork activation.
pub(crate) window: u64, pub(crate) window: usize,
} }
impl HardForkConfig { impl HardForkConfig {
@ -61,14 +61,14 @@ pub struct HardForkState {
pub(crate) votes: HFVotes, pub(crate) votes: HFVotes,
/// The last block height accounted for. /// The last block height accounted for.
pub(crate) last_height: u64, pub(crate) last_height: usize,
} }
impl HardForkState { impl HardForkState {
/// Initialize the [`HardForkState`] from the specified chain height. /// Initialize the [`HardForkState`] from the specified chain height.
#[instrument(name = "init_hardfork_state", skip(config, database), level = "info")] #[instrument(name = "init_hardfork_state", skip(config, database), level = "info")]
pub async fn init_from_chain_height<D: Database + Clone>( pub async fn init_from_chain_height<D: Database + Clone>(
chain_height: u64, chain_height: usize,
config: HardForkConfig, config: HardForkConfig,
mut database: D, mut database: D,
) -> Result<Self, ExtendedConsensusError> { ) -> Result<Self, ExtendedConsensusError> {
@ -118,7 +118,7 @@ impl HardForkState {
} }
/// Add a new block to the cache. /// Add a new block to the cache.
pub fn new_block(&mut self, vote: HardFork, height: u64) { pub fn new_block(&mut self, vote: HardFork, height: usize) {
// We don't _need_ to take in `height` but it's for safety, so we don't silently loose track // We don't _need_ to take in `height` but it's for safety, so we don't silently loose track
// of blocks. // of blocks.
assert_eq!(self.last_height + 1, height); assert_eq!(self.last_height + 1, height);
@ -162,7 +162,7 @@ impl HardForkState {
#[instrument(name = "get_votes", skip(database))] #[instrument(name = "get_votes", skip(database))]
async fn get_votes_in_range<D: Database>( async fn get_votes_in_range<D: Database>(
database: D, database: D,
block_heights: Range<u64>, block_heights: Range<usize>,
window_size: usize, window_size: usize,
) -> Result<HFVotes, ExtendedConsensusError> { ) -> Result<HFVotes, ExtendedConsensusError> {
let mut votes = HFVotes::new(window_size); let mut votes = HFVotes::new(window_size);

View file

@ -70,9 +70,9 @@ impl RandomX for RandomXVM {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct RandomXVMCache { pub struct RandomXVMCache {
/// The top [`RX_SEEDS_CACHED`] RX seeds. /// The top [`RX_SEEDS_CACHED`] RX seeds.
pub(crate) seeds: VecDeque<(u64, [u8; 32])>, pub(crate) seeds: VecDeque<(usize, [u8; 32])>,
/// The VMs for `seeds` (if after hf 12, otherwise this will be empty). /// The VMs for `seeds` (if after hf 12, otherwise this will be empty).
pub(crate) vms: HashMap<u64, Arc<RandomXVM>>, pub(crate) vms: HashMap<usize, Arc<RandomXVM>>,
/// A single cached VM that was given to us from a part of Cuprate. /// A single cached VM that was given to us from a part of Cuprate.
pub(crate) cached_vm: Option<([u8; 32], Arc<RandomXVM>)>, pub(crate) cached_vm: Option<([u8; 32], Arc<RandomXVM>)>,
@ -81,7 +81,7 @@ pub struct RandomXVMCache {
impl RandomXVMCache { impl RandomXVMCache {
#[instrument(name = "init_rx_vm_cache", level = "info", skip(database))] #[instrument(name = "init_rx_vm_cache", level = "info", skip(database))]
pub async fn init_from_chain_height<D: Database + Clone>( pub async fn init_from_chain_height<D: Database + Clone>(
chain_height: u64, chain_height: usize,
hf: &HardFork, hf: &HardFork,
database: D, database: D,
) -> Result<Self, ExtendedConsensusError> { ) -> Result<Self, ExtendedConsensusError> {
@ -90,7 +90,8 @@ impl RandomXVMCache {
tracing::debug!("last {RX_SEEDS_CACHED} randomX seed heights: {seed_heights:?}",); tracing::debug!("last {RX_SEEDS_CACHED} randomX seed heights: {seed_heights:?}",);
let seeds: VecDeque<(u64, [u8; 32])> = seed_heights.into_iter().zip(seed_hashes).collect(); let seeds: VecDeque<(usize, [u8; 32])> =
seed_heights.into_iter().zip(seed_hashes).collect();
let vms = if hf >= &HardFork::V12 { let vms = if hf >= &HardFork::V12 {
tracing::debug!("Creating RandomX VMs"); tracing::debug!("Creating RandomX VMs");
@ -125,7 +126,7 @@ impl RandomXVMCache {
} }
/// Get the RandomX VMs. /// Get the RandomX VMs.
pub async fn get_vms(&mut self) -> HashMap<u64, Arc<RandomXVM>> { pub async fn get_vms(&mut self) -> HashMap<usize, Arc<RandomXVM>> {
match self.seeds.len().checked_sub(self.vms.len()) { match self.seeds.len().checked_sub(self.vms.len()) {
// No difference in the amount of seeds to VMs. // No difference in the amount of seeds to VMs.
Some(0) => (), Some(0) => (),
@ -179,7 +180,7 @@ impl RandomXVMCache {
/// Add a new block to the VM cache. /// Add a new block to the VM cache.
/// ///
/// hash is the block hash not the blocks PoW hash. /// hash is the block hash not the blocks PoW hash.
pub fn new_block(&mut self, height: u64, hash: &[u8; 32]) { pub fn new_block(&mut self, height: usize, hash: &[u8; 32]) {
if is_randomx_seed_height(height) { if is_randomx_seed_height(height) {
tracing::debug!("Block {height} is a randomX seed height, adding it to the cache.",); tracing::debug!("Block {height} is a randomX seed height, adding it to the cache.",);
@ -200,7 +201,7 @@ impl RandomXVMCache {
/// Get the last `amount` of RX seeds, the top height returned here will not necessarily be the RX VM for the top block /// Get the last `amount` of RX seeds, the top height returned here will not necessarily be the RX VM for the top block
/// in the chain as VMs include some lag before a seed activates. /// in the chain as VMs include some lag before a seed activates.
pub(crate) fn get_last_rx_seed_heights(mut last_height: u64, mut amount: usize) -> Vec<u64> { pub(crate) fn get_last_rx_seed_heights(mut last_height: usize, mut amount: usize) -> Vec<usize> {
let mut seeds = Vec::with_capacity(amount); let mut seeds = Vec::with_capacity(amount);
if is_randomx_seed_height(last_height) { if is_randomx_seed_height(last_height) {
seeds.push(last_height); seeds.push(last_height);
@ -223,7 +224,7 @@ pub(crate) fn get_last_rx_seed_heights(mut last_height: u64, mut amount: usize)
/// Gets the block hashes for the heights specified. /// Gets the block hashes for the heights specified.
async fn get_block_hashes<D: Database + Clone>( async fn get_block_hashes<D: Database + Clone>(
heights: Vec<u64>, heights: Vec<usize>,
database: D, database: D,
) -> Result<Vec<[u8; 32]>, ExtendedConsensusError> { ) -> Result<Vec<[u8; 32]>, ExtendedConsensusError> {
let mut fut = FuturesOrdered::new(); let mut fut = FuturesOrdered::new();

View file

@ -44,7 +44,7 @@ pub struct ContextTask {
hardfork_state: hardforks::HardForkState, hardfork_state: hardforks::HardForkState,
/// The current chain height. /// The current chain height.
chain_height: u64, chain_height: usize,
/// The top block hash. /// The top block hash.
top_block_hash: [u8; 32], top_block_hash: [u8; 32],
/// The total amount of coins generated. /// The total amount of coins generated.

View file

@ -23,21 +23,21 @@ use cuprate_types::blockchain::{BCReadRequest, BCResponse};
use crate::{Database, ExtendedConsensusError, HardFork}; use crate::{Database, ExtendedConsensusError, HardFork};
/// The short term block weight window. /// The short term block weight window.
const SHORT_TERM_WINDOW: u64 = 100; const SHORT_TERM_WINDOW: usize = 100;
/// The long term block weight window. /// The long term block weight window.
const LONG_TERM_WINDOW: u64 = 100000; const LONG_TERM_WINDOW: usize = 100000;
/// Configuration for the block weight cache. /// Configuration for the block weight cache.
/// ///
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct BlockWeightsCacheConfig { pub struct BlockWeightsCacheConfig {
short_term_window: u64, short_term_window: usize,
long_term_window: u64, long_term_window: usize,
} }
impl BlockWeightsCacheConfig { impl BlockWeightsCacheConfig {
/// Creates a new [`BlockWeightsCacheConfig`] /// Creates a new [`BlockWeightsCacheConfig`]
pub const fn new(short_term_window: u64, long_term_window: u64) -> BlockWeightsCacheConfig { pub const fn new(short_term_window: usize, long_term_window: usize) -> BlockWeightsCacheConfig {
BlockWeightsCacheConfig { BlockWeightsCacheConfig {
short_term_window, short_term_window,
long_term_window, long_term_window,
@ -73,7 +73,7 @@ pub struct BlockWeightsCache {
cached_sorted_short_term_weights: Vec<usize>, cached_sorted_short_term_weights: Vec<usize>,
/// The height of the top block. /// The height of the top block.
tip_height: u64, tip_height: usize,
/// The block weight config. /// The block weight config.
config: BlockWeightsCacheConfig, config: BlockWeightsCacheConfig,
@ -83,7 +83,7 @@ impl BlockWeightsCache {
/// Initialize the [`BlockWeightsCache`] at the the given chain height. /// Initialize the [`BlockWeightsCache`] at the the given chain height.
#[instrument(name = "init_weight_cache", level = "info", skip(database, config))] #[instrument(name = "init_weight_cache", level = "info", skip(database, config))]
pub async fn init_from_chain_height<D: Database + Clone>( pub async fn init_from_chain_height<D: Database + Clone>(
chain_height: u64, chain_height: usize,
config: BlockWeightsCacheConfig, config: BlockWeightsCacheConfig,
database: D, database: D,
) -> Result<Self, ExtendedConsensusError> { ) -> Result<Self, ExtendedConsensusError> {
@ -129,7 +129,7 @@ impl BlockWeightsCache {
/// ///
/// The block_height **MUST** be one more than the last height the cache has /// The block_height **MUST** be one more than the last height the cache has
/// seen. /// seen.
pub fn new_block(&mut self, block_height: u64, block_weight: usize, long_term_weight: usize) { pub fn new_block(&mut self, block_height: usize, block_weight: usize, long_term_weight: usize) {
assert_eq!(self.tip_height + 1, block_height); assert_eq!(self.tip_height + 1, block_height);
self.tip_height += 1; self.tip_height += 1;
tracing::debug!( tracing::debug!(
@ -151,7 +151,7 @@ impl BlockWeightsCache {
} }
// If the list now has too many entries remove the oldest. // If the list now has too many entries remove the oldest.
if u64::try_from(self.long_term_weights.len()).unwrap() > self.config.long_term_window { if self.long_term_weights.len() > self.config.long_term_window {
let val = self let val = self
.long_term_weights .long_term_weights
.pop_front() .pop_front()
@ -175,9 +175,7 @@ impl BlockWeightsCache {
} }
// If there are now too many entries remove the oldest. // If there are now too many entries remove the oldest.
if u64::try_from(self.short_term_block_weights.len()).unwrap() if self.short_term_block_weights.len() > self.config.short_term_window {
> self.config.short_term_window
{
let val = self let val = self
.short_term_block_weights .short_term_block_weights
.pop_front() .pop_front()
@ -288,7 +286,7 @@ pub fn calculate_block_long_term_weight(
/// Gets the block weights from the blocks with heights in the range provided. /// Gets the block weights from the blocks with heights in the range provided.
#[instrument(name = "get_block_weights", skip(database))] #[instrument(name = "get_block_weights", skip(database))]
async fn get_blocks_weight_in_range<D: Database + Clone>( async fn get_blocks_weight_in_range<D: Database + Clone>(
range: Range<u64>, range: Range<usize>,
database: D, database: D,
) -> Result<Vec<usize>, ExtendedConsensusError> { ) -> Result<Vec<usize>, ExtendedConsensusError> {
tracing::info!("getting block weights."); tracing::info!("getting block weights.");
@ -309,7 +307,7 @@ async fn get_blocks_weight_in_range<D: Database + Clone>(
/// Gets the block long term weights from the blocks with heights in the range provided. /// Gets the block long term weights from the blocks with heights in the range provided.
#[instrument(name = "get_long_term_weights", skip(database), level = "info")] #[instrument(name = "get_long_term_weights", skip(database), level = "info")]
async fn get_long_term_weight_in_range<D: Database + Clone>( async fn get_long_term_weight_in_range<D: Database + Clone>(
range: Range<u64>, range: Range<usize>,
database: D, database: D,
) -> Result<Vec<usize>, ExtendedConsensusError> { ) -> Result<Vec<usize>, ExtendedConsensusError> {
tracing::info!("getting block long term weights."); tracing::info!("getting block long term weights.");

View file

@ -175,7 +175,7 @@ pub enum VerifyTxRequest {
// TODO: Can we use references to remove the Vec? wont play nicely with Service though // TODO: Can we use references to remove the Vec? wont play nicely with Service though
txs: Vec<Arc<TransactionVerificationData>>, txs: Vec<Arc<TransactionVerificationData>>,
/// The current chain height. /// The current chain height.
current_chain_height: u64, current_chain_height: usize,
/// The top block hash. /// The top block hash.
top_hash: [u8; 32], top_hash: [u8; 32],
/// The value for time to use to check time locked outputs. /// The value for time to use to check time locked outputs.
@ -189,7 +189,7 @@ pub enum VerifyTxRequest {
/// The transactions to verify. /// The transactions to verify.
txs: Vec<Transaction>, txs: Vec<Transaction>,
/// The current chain height. /// The current chain height.
current_chain_height: u64, current_chain_height: usize,
/// The top block hash. /// The top block hash.
top_hash: [u8; 32], top_hash: [u8; 32],
/// The value for time to use to check time locked outputs. /// The value for time to use to check time locked outputs.
@ -288,7 +288,7 @@ where
async fn prep_and_verify_transactions<D>( async fn prep_and_verify_transactions<D>(
database: D, database: D,
txs: Vec<Transaction>, txs: Vec<Transaction>,
current_chain_height: u64, current_chain_height: usize,
top_hash: [u8; 32], top_hash: [u8; 32],
time_for_time_lock: u64, time_for_time_lock: u64,
hf: HardFork, hf: HardFork,
@ -323,7 +323,7 @@ where
async fn verify_prepped_transactions<D>( async fn verify_prepped_transactions<D>(
mut database: D, mut database: D,
txs: &[Arc<TransactionVerificationData>], txs: &[Arc<TransactionVerificationData>],
current_chain_height: u64, current_chain_height: usize,
top_hash: [u8; 32], top_hash: [u8; 32],
time_for_time_lock: u64, time_for_time_lock: u64,
hf: HardFork, hf: HardFork,
@ -422,7 +422,7 @@ fn transactions_needing_verification(
txs: &[Arc<TransactionVerificationData>], txs: &[Arc<TransactionVerificationData>],
hashes_in_main_chain: HashSet<[u8; 32]>, hashes_in_main_chain: HashSet<[u8; 32]>,
current_hf: &HardFork, current_hf: &HardFork,
current_chain_height: u64, current_chain_height: usize,
time_for_time_lock: u64, time_for_time_lock: u64,
) -> Result< ) -> Result<
( (
@ -513,7 +513,7 @@ where
async fn verify_transactions<D>( async fn verify_transactions<D>(
txs: Vec<(Arc<TransactionVerificationData>, VerificationNeeded)>, txs: Vec<(Arc<TransactionVerificationData>, VerificationNeeded)>,
current_chain_height: u64, current_chain_height: usize,
top_hash: [u8; 32], top_hash: [u8; 32],
current_time_lock_timestamp: u64, current_time_lock_timestamp: u64,
hf: HardFork, hf: HardFork,

View file

@ -257,7 +257,7 @@ impl<Z: NetworkZone> AddressBook<Z> {
fn take_random_white_peer( fn take_random_white_peer(
&mut self, &mut self,
block_needed: Option<u64>, block_needed: Option<usize>,
) -> Option<ZoneSpecificPeerListEntryBase<Z::Addr>> { ) -> Option<ZoneSpecificPeerListEntryBase<Z::Addr>> {
tracing::debug!("Retrieving random white peer"); tracing::debug!("Retrieving random white peer");
self.white_list self.white_list
@ -266,7 +266,7 @@ impl<Z: NetworkZone> AddressBook<Z> {
fn take_random_gray_peer( fn take_random_gray_peer(
&mut self, &mut self,
block_needed: Option<u64>, block_needed: Option<usize>,
) -> Option<ZoneSpecificPeerListEntryBase<Z::Addr>> { ) -> Option<ZoneSpecificPeerListEntryBase<Z::Addr>> {
tracing::debug!("Retrieving random gray peer"); tracing::debug!("Retrieving random gray peer");
self.gray_list self.gray_list

View file

@ -88,7 +88,7 @@ impl<Z: NetworkZone> PeerList<Z> {
pub fn take_random_peer<R: Rng>( pub fn take_random_peer<R: Rng>(
&mut self, &mut self,
r: &mut R, r: &mut R,
block_needed: Option<u64>, block_needed: Option<usize>,
must_keep_peers: &HashSet<Z::Addr>, must_keep_peers: &HashSet<Z::Addr>,
) -> Option<ZoneSpecificPeerListEntryBase<Z::Addr>> { ) -> Option<ZoneSpecificPeerListEntryBase<Z::Addr>> {
// Take a random peer and see if it's in the list of must_keep_peers, if it is try again. // Take a random peer and see if it's in the list of must_keep_peers, if it is try again.

View file

@ -13,7 +13,7 @@ pub enum PeerSyncRequest<N: NetworkZone> {
/// claim to have a higher cumulative difficulty. /// claim to have a higher cumulative difficulty.
PeersToSyncFrom { PeersToSyncFrom {
current_cumulative_difficulty: u128, current_cumulative_difficulty: u128,
block_needed: Option<u64>, block_needed: Option<usize>,
}, },
/// Add/update a peers core sync data to the sync state service. /// Add/update a peers core sync data to the sync state service.
IncomingCoreSyncData(InternalPeerID<N::Addr>, ConnectionHandle, CoreSyncData), IncomingCoreSyncData(InternalPeerID<N::Addr>, ConnectionHandle, CoreSyncData),
@ -105,18 +105,18 @@ pub enum AddressBookRequest<Z: NetworkZone> {
/// Takes a random white peer from the peer list. If height is specified /// Takes a random white peer from the peer list. If height is specified
/// then the peer list should retrieve a peer that should have a full /// then the peer list should retrieve a peer that should have a full
/// block at that height according to it's pruning seed /// block at that height according to it's pruning seed
TakeRandomWhitePeer { height: Option<u64> }, TakeRandomWhitePeer { height: Option<usize> },
/// Takes a random gray peer from the peer list. If height is specified /// Takes a random gray peer from the peer list. If height is specified
/// then the peer list should retrieve a peer that should have a full /// then the peer list should retrieve a peer that should have a full
/// block at that height according to it's pruning seed /// block at that height according to it's pruning seed
TakeRandomGrayPeer { height: Option<u64> }, TakeRandomGrayPeer { height: Option<usize> },
/// Takes a random peer from the peer list. If height is specified /// Takes a random peer from the peer list. If height is specified
/// then the peer list should retrieve a peer that should have a full /// then the peer list should retrieve a peer that should have a full
/// block at that height according to it's pruning seed. /// block at that height according to it's pruning seed.
/// ///
/// The address book will look in the white peer list first, then the gray /// The address book will look in the white peer list first, then the gray
/// one if no peer is found. /// one if no peer is found.
TakeRandomPeer { height: Option<u64> }, TakeRandomPeer { height: Option<usize> },
/// Gets the specified number of white peers, or less if we don't have enough. /// Gets the specified number of white peers, or less if we don't have enough.
GetWhitePeers(usize), GetWhitePeers(usize),
/// Checks if the given peer is banned. /// Checks if the given peer is banned.

View file

@ -121,7 +121,8 @@ pub enum ChainSvcResponse {
/// The response for [`ChainSvcRequest::FindFirstUnknown`]. /// The response for [`ChainSvcRequest::FindFirstUnknown`].
/// ///
/// Contains the index of the first unknown block and its expected height. /// Contains the index of the first unknown block and its expected height.
FindFirstUnknown(usize, u64), // TODO: make this a named field variant instead of a tuple
FindFirstUnknown(usize, usize),
/// The response for [`ChainSvcRequest::CumulativeDifficulty`]. /// The response for [`ChainSvcRequest::CumulativeDifficulty`].
/// ///
/// The current cumulative difficulty of our chain. /// The current cumulative difficulty of our chain.
@ -207,7 +208,7 @@ struct BlockDownloader<N: NetworkZone, S, C> {
/// The amount of blocks to request in the next batch. /// The amount of blocks to request in the next batch.
amount_of_blocks_to_request: usize, amount_of_blocks_to_request: usize,
/// The height at which [`Self::amount_of_blocks_to_request`] was updated. /// The height at which [`Self::amount_of_blocks_to_request`] was updated.
amount_of_blocks_to_request_updated_at: u64, amount_of_blocks_to_request_updated_at: usize,
/// The amount of consecutive empty chain entries we received. /// The amount of consecutive empty chain entries we received.
/// ///
@ -225,12 +226,12 @@ struct BlockDownloader<N: NetworkZone, S, C> {
/// The current inflight requests. /// The current inflight requests.
/// ///
/// This is a map of batch start heights to block IDs and related information of the batch. /// This is a map of batch start heights to block IDs and related information of the batch.
inflight_requests: BTreeMap<u64, BlocksToRetrieve<N>>, inflight_requests: BTreeMap<usize, BlocksToRetrieve<N>>,
/// A queue of start heights from failed batches that should be retried. /// A queue of start heights from failed batches that should be retried.
/// ///
/// Wrapped in [`Reverse`] so we prioritize early batches. /// Wrapped in [`Reverse`] so we prioritize early batches.
failed_batches: BinaryHeap<Reverse<u64>>, failed_batches: BinaryHeap<Reverse<usize>>,
block_queue: BlockQueue, block_queue: BlockQueue,
@ -524,7 +525,7 @@ where
/// Handles a response to a request to get blocks from a peer. /// Handles a response to a request to get blocks from a peer.
async fn handle_download_batch_res( async fn handle_download_batch_res(
&mut self, &mut self,
start_height: u64, start_height: usize,
res: Result<(ClientPoolDropGuard<N>, BlockBatch), BlockDownloadError>, res: Result<(ClientPoolDropGuard<N>, BlockBatch), BlockDownloadError>,
chain_tracker: &mut ChainTracker<N>, chain_tracker: &mut ChainTracker<N>,
pending_peers: &mut BTreeMap<PruningSeed, Vec<ClientPoolDropGuard<N>>>, pending_peers: &mut BTreeMap<PruningSeed, Vec<ClientPoolDropGuard<N>>>,
@ -692,18 +693,19 @@ where
/// The return value from the block download tasks. /// The return value from the block download tasks.
struct BlockDownloadTaskResponse<N: NetworkZone> { struct BlockDownloadTaskResponse<N: NetworkZone> {
/// The start height of the batch. /// The start height of the batch.
start_height: u64, start_height: usize,
/// A result containing the batch or an error. /// A result containing the batch or an error.
result: Result<(ClientPoolDropGuard<N>, BlockBatch), BlockDownloadError>, result: Result<(ClientPoolDropGuard<N>, BlockBatch), BlockDownloadError>,
} }
/// Returns if a peer has all the blocks in a range, according to its [`PruningSeed`]. /// Returns if a peer has all the blocks in a range, according to its [`PruningSeed`].
fn client_has_block_in_range(pruning_seed: &PruningSeed, start_height: u64, length: usize) -> bool { fn client_has_block_in_range(
pruning_seed: &PruningSeed,
start_height: usize,
length: usize,
) -> bool {
pruning_seed.has_full_block(start_height, CRYPTONOTE_MAX_BLOCK_HEIGHT) pruning_seed.has_full_block(start_height, CRYPTONOTE_MAX_BLOCK_HEIGHT)
&& pruning_seed.has_full_block( && pruning_seed.has_full_block(start_height + length, CRYPTONOTE_MAX_BLOCK_HEIGHT)
start_height + u64::try_from(length).unwrap(),
CRYPTONOTE_MAX_BLOCK_HEIGHT,
)
} }
/// Calculates the next amount of blocks to request in a batch. /// Calculates the next amount of blocks to request in a batch.

View file

@ -15,7 +15,7 @@ use super::{BlockBatch, BlockDownloadError};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ReadyQueueBatch { pub struct ReadyQueueBatch {
/// The start height of the batch. /// The start height of the batch.
pub start_height: u64, pub start_height: usize,
/// The batch of blocks. /// The batch of blocks.
pub block_batch: BlockBatch, pub block_batch: BlockBatch,
} }
@ -64,7 +64,7 @@ impl BlockQueue {
} }
/// Returns the oldest batch that has not been put in the [`async_buffer`] yet. /// Returns the oldest batch that has not been put in the [`async_buffer`] yet.
pub fn oldest_ready_batch(&self) -> Option<u64> { pub fn oldest_ready_batch(&self) -> Option<usize> {
self.ready_batches.peek().map(|batch| batch.start_height) self.ready_batches.peek().map(|batch| batch.start_height)
} }
@ -80,13 +80,13 @@ impl BlockQueue {
pub async fn add_incoming_batch( pub async fn add_incoming_batch(
&mut self, &mut self,
new_batch: ReadyQueueBatch, new_batch: ReadyQueueBatch,
oldest_in_flight_start_height: Option<u64>, oldest_in_flight_start_height: Option<usize>,
) -> Result<(), BlockDownloadError> { ) -> Result<(), BlockDownloadError> {
self.ready_batches_size += new_batch.block_batch.size; self.ready_batches_size += new_batch.block_batch.size;
self.ready_batches.push(new_batch); self.ready_batches.push(new_batch);
// The height to stop pushing batches into the buffer. // The height to stop pushing batches into the buffer.
let height_to_stop_at = oldest_in_flight_start_height.unwrap_or(u64::MAX); let height_to_stop_at = oldest_in_flight_start_height.unwrap_or(usize::MAX);
while self while self
.ready_batches .ready_batches
@ -125,7 +125,7 @@ mod tests {
use super::*; use super::*;
prop_compose! { prop_compose! {
fn ready_batch_strategy()(start_height in 0_u64..500_000_000) -> ReadyQueueBatch { fn ready_batch_strategy()(start_height in 0_usize..500_000_000) -> ReadyQueueBatch {
// TODO: The permit will not be needed here when // TODO: The permit will not be needed here when
let (_, peer_handle) = HandleBuilder::new().with_permit(Arc::new(Semaphore::new(1)).try_acquire_owned().unwrap()).build(); let (_, peer_handle) = HandleBuilder::new().with_permit(Arc::new(Semaphore::new(1)).try_acquire_owned().unwrap()).build();

View file

@ -26,7 +26,7 @@ pub struct BlocksToRetrieve<N: NetworkZone> {
/// The hash of the last block before this batch. /// The hash of the last block before this batch.
pub prev_id: [u8; 32], pub prev_id: [u8; 32],
/// The expected height of the first block in [`BlocksToRetrieve::ids`]. /// The expected height of the first block in [`BlocksToRetrieve::ids`].
pub start_height: u64, pub start_height: usize,
/// The peer who told us about this batch. /// The peer who told us about this batch.
pub peer_who_told_us: InternalPeerID<N::Addr>, pub peer_who_told_us: InternalPeerID<N::Addr>,
/// The peer who told us about this batch's handle. /// The peer who told us about this batch's handle.
@ -54,7 +54,7 @@ pub struct ChainTracker<N: NetworkZone> {
/// A list of [`ChainEntry`]s, in order. /// A list of [`ChainEntry`]s, in order.
entries: VecDeque<ChainEntry<N>>, entries: VecDeque<ChainEntry<N>>,
/// The height of the first block, in the first entry in [`Self::entries`]. /// The height of the first block, in the first entry in [`Self::entries`].
first_height: u64, first_height: usize,
/// The hash of the last block in the last entry. /// The hash of the last block in the last entry.
top_seen_hash: [u8; 32], top_seen_hash: [u8; 32],
/// The hash of the block one below [`Self::first_height`]. /// The hash of the block one below [`Self::first_height`].
@ -67,7 +67,7 @@ impl<N: NetworkZone> ChainTracker<N> {
/// Creates a new chain tracker. /// Creates a new chain tracker.
pub fn new( pub fn new(
new_entry: ChainEntry<N>, new_entry: ChainEntry<N>,
first_height: u64, first_height: usize,
our_genesis: [u8; 32], our_genesis: [u8; 32],
previous_hash: [u8; 32], previous_hash: [u8; 32],
) -> Self { ) -> Self {
@ -96,14 +96,14 @@ impl<N: NetworkZone> ChainTracker<N> {
} }
/// Returns the height of the highest block we are tracking. /// Returns the height of the highest block we are tracking.
pub fn top_height(&self) -> u64 { pub fn top_height(&self) -> usize {
let top_block_idx = self let top_block_idx = self
.entries .entries
.iter() .iter()
.map(|entry| entry.ids.len()) .map(|entry| entry.ids.len())
.sum::<usize>(); .sum::<usize>();
self.first_height + u64::try_from(top_block_idx).unwrap() self.first_height + top_block_idx
} }
/// Returns the total number of queued batches for a certain `batch_size`. /// Returns the total number of queued batches for a certain `batch_size`.
@ -198,7 +198,7 @@ impl<N: NetworkZone> ChainTracker<N> {
failures: 0, failures: 0,
}; };
self.first_height += u64::try_from(end_idx).unwrap(); self.first_height += end_idx;
// TODO: improve ByteArrayVec API. // TODO: improve ByteArrayVec API.
self.previous_hash = blocks.ids[blocks.ids.len() - 1]; self.previous_hash = blocks.ids[blocks.ids.len() - 1];

View file

@ -31,7 +31,7 @@ pub async fn download_batch_task<N: NetworkZone>(
client: ClientPoolDropGuard<N>, client: ClientPoolDropGuard<N>,
ids: ByteArrayVec<32>, ids: ByteArrayVec<32>,
previous_id: [u8; 32], previous_id: [u8; 32],
expected_start_height: u64, expected_start_height: usize,
_attempt: usize, _attempt: usize,
) -> BlockDownloadTaskResponse<N> { ) -> BlockDownloadTaskResponse<N> {
BlockDownloadTaskResponse { BlockDownloadTaskResponse {
@ -48,7 +48,7 @@ async fn request_batch_from_peer<N: NetworkZone>(
mut client: ClientPoolDropGuard<N>, mut client: ClientPoolDropGuard<N>,
ids: ByteArrayVec<32>, ids: ByteArrayVec<32>,
previous_id: [u8; 32], previous_id: [u8; 32],
expected_start_height: u64, expected_start_height: usize,
) -> Result<(ClientPoolDropGuard<N>, BlockBatch), BlockDownloadError> { ) -> Result<(ClientPoolDropGuard<N>, BlockBatch), BlockDownloadError> {
// Request the blocks. // Request the blocks.
let blocks_response = timeout(BLOCK_DOWNLOADER_REQUEST_TIMEOUT, async { let blocks_response = timeout(BLOCK_DOWNLOADER_REQUEST_TIMEOUT, async {
@ -103,7 +103,7 @@ async fn request_batch_from_peer<N: NetworkZone>(
fn deserialize_batch( fn deserialize_batch(
blocks_response: GetObjectsResponse, blocks_response: GetObjectsResponse,
expected_start_height: u64, expected_start_height: usize,
requested_ids: ByteArrayVec<32>, requested_ids: ByteArrayVec<32>,
previous_id: [u8; 32], previous_id: [u8; 32],
peer_handle: ConnectionHandle, peer_handle: ConnectionHandle,
@ -113,7 +113,7 @@ fn deserialize_batch(
.into_par_iter() .into_par_iter()
.enumerate() .enumerate()
.map(|(i, block_entry)| { .map(|(i, block_entry)| {
let expected_height = u64::try_from(i).unwrap() + expected_start_height; let expected_height = i + expected_start_height;
let mut size = block_entry.block.len(); let mut size = block_entry.block.len();
@ -123,7 +123,7 @@ fn deserialize_batch(
let block_hash = block.hash(); let block_hash = block.hash();
// Check the block matches the one requested and the peer sent enough transactions. // Check the block matches the one requested and the peer sent enough transactions.
if requested_ids[i] != block_hash || block.txs.len() != block_entry.txs.len() { if requested_ids[i] != block_hash || block.transactions.len() != block_entry.txs.len() {
return Err(BlockDownloadError::PeersResponseWasInvalid); return Err(BlockDownloadError::PeersResponseWasInvalid);
} }
@ -175,7 +175,7 @@ fn deserialize_batch(
.collect::<Result<Vec<_>, _>>()?; .collect::<Result<Vec<_>, _>>()?;
// Make sure the transactions in the block were the ones the peer sent. // Make sure the transactions in the block were the ones the peer sent.
let mut expected_txs = block.txs.iter().collect::<HashSet<_>>(); let mut expected_txs = block.transactions.iter().collect::<HashSet<_>>();
for tx in &txs { for tx in &txs {
if !expected_txs.remove(&tx.hash()) { if !expected_txs.remove(&tx.hash()) {

View file

@ -38,7 +38,7 @@ enum OutboundConnectorError {
/// set needs specific data that none of the currently connected peers have. /// set needs specific data that none of the currently connected peers have.
pub struct MakeConnectionRequest { pub struct MakeConnectionRequest {
/// The block needed that no connected peers have due to pruning. /// The block needed that no connected peers have due to pruning.
block_needed: Option<u64>, block_needed: Option<usize>,
} }
/// The outbound connection count keeper. /// The outbound connection count keeper.

View file

@ -99,7 +99,7 @@ impl<N: NetworkZone> PeerSyncSvc<N> {
fn peers_to_sync_from( fn peers_to_sync_from(
&self, &self,
current_cum_diff: u128, current_cum_diff: u128,
block_needed: Option<u64>, block_needed: Option<usize>,
) -> Vec<InternalPeerID<N::Addr>> { ) -> Vec<InternalPeerID<N::Addr>> {
self.cumulative_difficulties self.cumulative_difficulties
.range((current_cum_diff + 1)..) .range((current_cum_diff + 1)..)

View file

@ -22,13 +22,13 @@ use std::cmp::Ordering;
use thiserror::Error; use thiserror::Error;
pub const CRYPTONOTE_MAX_BLOCK_HEIGHT: u64 = 500000000; pub const CRYPTONOTE_MAX_BLOCK_HEIGHT: usize = 500000000;
/// The default log stripes for Monero pruning. /// The default log stripes for Monero pruning.
pub const CRYPTONOTE_PRUNING_LOG_STRIPES: u32 = 3; pub const CRYPTONOTE_PRUNING_LOG_STRIPES: u32 = 3;
/// The amount of blocks that peers keep before another stripe starts storing blocks. /// The amount of blocks that peers keep before another stripe starts storing blocks.
pub const CRYPTONOTE_PRUNING_STRIPE_SIZE: u64 = 4096; pub const CRYPTONOTE_PRUNING_STRIPE_SIZE: usize = 4096;
/// The amount of blocks from the top of the chain that should not be pruned. /// The amount of blocks from the top of the chain that should not be pruned.
pub const CRYPTONOTE_PRUNING_TIP_BLOCKS: u64 = 5500; pub const CRYPTONOTE_PRUNING_TIP_BLOCKS: usize = 5500;
const PRUNING_SEED_LOG_STRIPES_SHIFT: u32 = 7; const PRUNING_SEED_LOG_STRIPES_SHIFT: u32 = 7;
const PRUNING_SEED_STRIPE_SHIFT: u32 = 0; const PRUNING_SEED_STRIPE_SHIFT: u32 = 0;
@ -127,7 +127,7 @@ impl PruningSeed {
} }
/// Returns `true` if a peer with this pruning seed should have a non-pruned version of a block. /// Returns `true` if a peer with this pruning seed should have a non-pruned version of a block.
pub fn has_full_block(&self, height: u64, blockchain_height: u64) -> bool { pub fn has_full_block(&self, height: usize, blockchain_height: usize) -> bool {
match self { match self {
PruningSeed::NotPruned => true, PruningSeed::NotPruned => true,
PruningSeed::Pruned(seed) => seed.has_full_block(height, blockchain_height), PruningSeed::Pruned(seed) => seed.has_full_block(height, blockchain_height),
@ -151,9 +151,9 @@ impl PruningSeed {
/// This function will also error if `block_height` > `blockchain_height` /// This function will also error if `block_height` > `blockchain_height`
pub fn get_next_pruned_block( pub fn get_next_pruned_block(
&self, &self,
block_height: u64, block_height: usize,
blockchain_height: u64, blockchain_height: usize,
) -> Result<Option<u64>, PruningError> { ) -> Result<Option<usize>, PruningError> {
Ok(match self { Ok(match self {
PruningSeed::NotPruned => None, PruningSeed::NotPruned => None,
PruningSeed::Pruned(seed) => { PruningSeed::Pruned(seed) => {
@ -177,9 +177,9 @@ impl PruningSeed {
/// ///
pub fn get_next_unpruned_block( pub fn get_next_unpruned_block(
&self, &self,
block_height: u64, block_height: usize,
blockchain_height: u64, blockchain_height: usize,
) -> Result<u64, PruningError> { ) -> Result<usize, PruningError> {
Ok(match self { Ok(match self {
PruningSeed::NotPruned => block_height, PruningSeed::NotPruned => block_height,
PruningSeed::Pruned(seed) => { PruningSeed::Pruned(seed) => {
@ -312,7 +312,7 @@ impl DecompressedPruningSeed {
} }
/// Returns `true` if a peer with this pruning seed should have a non-pruned version of a block. /// Returns `true` if a peer with this pruning seed should have a non-pruned version of a block.
pub fn has_full_block(&self, height: u64, blockchain_height: u64) -> bool { pub fn has_full_block(&self, height: usize, blockchain_height: usize) -> bool {
match get_block_pruning_stripe(height, blockchain_height, self.log_stripes) { match get_block_pruning_stripe(height, blockchain_height, self.log_stripes) {
Some(block_stripe) => self.stripe == block_stripe, Some(block_stripe) => self.stripe == block_stripe,
None => true, None => true,
@ -334,9 +334,9 @@ impl DecompressedPruningSeed {
/// ///
pub fn get_next_unpruned_block( pub fn get_next_unpruned_block(
&self, &self,
block_height: u64, block_height: usize,
blockchain_height: u64, blockchain_height: usize,
) -> Result<u64, PruningError> { ) -> Result<usize, PruningError> {
if block_height > CRYPTONOTE_MAX_BLOCK_HEIGHT || block_height > blockchain_height { if block_height > CRYPTONOTE_MAX_BLOCK_HEIGHT || block_height > blockchain_height {
return Err(PruningError::BlockHeightTooLarge); return Err(PruningError::BlockHeightTooLarge);
} }
@ -373,7 +373,7 @@ impl DecompressedPruningSeed {
// amt_of_cycles * blocks in a cycle + how many blocks through a cycles until the seed starts storing blocks // amt_of_cycles * blocks in a cycle + how many blocks through a cycles until the seed starts storing blocks
let calculated_height = cycles_start * (CRYPTONOTE_PRUNING_STRIPE_SIZE << self.log_stripes) let calculated_height = cycles_start * (CRYPTONOTE_PRUNING_STRIPE_SIZE << self.log_stripes)
+ (self.stripe as u64 - 1) * CRYPTONOTE_PRUNING_STRIPE_SIZE; + (self.stripe as usize - 1) * CRYPTONOTE_PRUNING_STRIPE_SIZE;
if calculated_height + CRYPTONOTE_PRUNING_TIP_BLOCKS > blockchain_height { if calculated_height + CRYPTONOTE_PRUNING_TIP_BLOCKS > blockchain_height {
// if our calculated height is greater than the amount of tip blocks then the start of the tip blocks will be the next un-pruned // if our calculated height is greater than the amount of tip blocks then the start of the tip blocks will be the next un-pruned
@ -400,9 +400,9 @@ impl DecompressedPruningSeed {
/// ///
pub fn get_next_pruned_block( pub fn get_next_pruned_block(
&self, &self,
block_height: u64, block_height: usize,
blockchain_height: u64, blockchain_height: usize,
) -> Result<Option<u64>, PruningError> { ) -> Result<Option<usize>, PruningError> {
if block_height + CRYPTONOTE_PRUNING_TIP_BLOCKS >= blockchain_height { if block_height + CRYPTONOTE_PRUNING_TIP_BLOCKS >= blockchain_height {
// If we are within `CRYPTONOTE_PRUNING_TIP_BLOCKS` of the chain we should // If we are within `CRYPTONOTE_PRUNING_TIP_BLOCKS` of the chain we should
// not prune blocks. // not prune blocks.
@ -434,16 +434,16 @@ impl DecompressedPruningSeed {
} }
fn get_block_pruning_stripe( fn get_block_pruning_stripe(
block_height: u64, block_height: usize,
blockchain_height: u64, blockchain_height: usize,
log_stripe: u32, log_stripe: u32,
) -> Option<u32> { ) -> Option<u32> {
if block_height + CRYPTONOTE_PRUNING_TIP_BLOCKS >= blockchain_height { if block_height + CRYPTONOTE_PRUNING_TIP_BLOCKS >= blockchain_height {
None None
} else { } else {
Some( Some(
(((block_height / CRYPTONOTE_PRUNING_STRIPE_SIZE) & ((1 << log_stripe) as u64 - 1)) + 1) (((block_height / CRYPTONOTE_PRUNING_STRIPE_SIZE) & ((1 << log_stripe) as usize - 1))
as u32, // it's trivial to prove it's ok to us `as` here + 1) as u32, // it's trivial to prove it's ok to us `as` here
) )
} }
} }
@ -503,7 +503,7 @@ mod tests {
for i in 0_u32..8 { for i in 0_u32..8 {
assert_eq!( assert_eq!(
get_block_pruning_stripe( get_block_pruning_stripe(
(i * 4096) as u64, (i * 4096) as usize,
blockchain_height, blockchain_height,
CRYPTONOTE_PRUNING_LOG_STRIPES CRYPTONOTE_PRUNING_LOG_STRIPES
) )
@ -515,7 +515,7 @@ mod tests {
for i in 0_u32..8 { for i in 0_u32..8 {
assert_eq!( assert_eq!(
get_block_pruning_stripe( get_block_pruning_stripe(
32768 + (i * 4096) as u64, 32768 + (i * 4096) as usize,
blockchain_height, blockchain_height,
CRYPTONOTE_PRUNING_LOG_STRIPES CRYPTONOTE_PRUNING_LOG_STRIPES
) )
@ -527,7 +527,7 @@ mod tests {
for i in 1_u32..8 { for i in 1_u32..8 {
assert_eq!( assert_eq!(
get_block_pruning_stripe( get_block_pruning_stripe(
32767 + (i * 4096) as u64, 32767 + (i * 4096) as usize,
blockchain_height, blockchain_height,
CRYPTONOTE_PRUNING_LOG_STRIPES CRYPTONOTE_PRUNING_LOG_STRIPES
) )
@ -553,23 +553,23 @@ mod tests {
for (i, seed) in all_valid_seeds.iter().enumerate() { for (i, seed) in all_valid_seeds.iter().enumerate() {
assert_eq!( assert_eq!(
seed.get_next_unpruned_block(0, blockchain_height).unwrap(), seed.get_next_unpruned_block(0, blockchain_height).unwrap(),
i as u64 * 4096 i * 4096
) )
} }
for (i, seed) in all_valid_seeds.iter().enumerate() { for (i, seed) in all_valid_seeds.iter().enumerate() {
assert_eq!( assert_eq!(
seed.get_next_unpruned_block((i as u64 + 1) * 4096, blockchain_height) seed.get_next_unpruned_block((i + 1) * 4096, blockchain_height)
.unwrap(), .unwrap(),
i as u64 * 4096 + 32768 i * 4096 + 32768
) )
} }
for (i, seed) in all_valid_seeds.iter().enumerate() { for (i, seed) in all_valid_seeds.iter().enumerate() {
assert_eq!( assert_eq!(
seed.get_next_unpruned_block((i as u64 + 8) * 4096, blockchain_height) seed.get_next_unpruned_block((i + 8) * 4096, blockchain_height)
.unwrap(), .unwrap(),
i as u64 * 4096 + 32768 i * 4096 + 32768
) )
} }
@ -610,19 +610,19 @@ mod tests {
for (i, seed) in all_valid_seeds.iter().enumerate() { for (i, seed) in all_valid_seeds.iter().enumerate() {
assert_eq!( assert_eq!(
seed.get_next_pruned_block((i as u64 + 1) * 4096, blockchain_height) seed.get_next_pruned_block((i + 1) * 4096, blockchain_height)
.unwrap() .unwrap()
.unwrap(), .unwrap(),
(i as u64 + 1) * 4096 (i + 1) * 4096
) )
} }
for (i, seed) in all_valid_seeds.iter().enumerate() { for (i, seed) in all_valid_seeds.iter().enumerate() {
assert_eq!( assert_eq!(
seed.get_next_pruned_block((i as u64 + 8) * 4096, blockchain_height) seed.get_next_pruned_block((i + 8) * 4096, blockchain_height)
.unwrap() .unwrap()
.unwrap(), .unwrap(),
(i as u64 + 9) * 4096 (i + 9) * 4096
) )
} }

View file

@ -31,6 +31,7 @@ curve25519-dalek = { workspace = true }
cuprate-pruning = { path = "../../pruning" } cuprate-pruning = { path = "../../pruning" }
monero-serai = { workspace = true, features = ["std"] } monero-serai = { workspace = true, features = ["std"] }
paste = { workspace = true } paste = { workspace = true }
serde = { workspace = true, optional = true }
# `service` feature. # `service` feature.
crossbeam = { workspace = true, features = ["std"], optional = true } crossbeam = { workspace = true, features = ["std"], optional = true }

View file

@ -65,17 +65,17 @@ pub fn add_block(
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
{ {
assert_eq!(block.block.serialize(), block.block_blob); assert_eq!(block.block.serialize(), block.block_blob);
assert_eq!(block.block.txs.len(), block.txs.len()); assert_eq!(block.block.transactions.len(), block.txs.len());
for (i, tx) in block.txs.iter().enumerate() { for (i, tx) in block.txs.iter().enumerate() {
assert_eq!(tx.tx_blob, tx.tx.serialize()); assert_eq!(tx.tx_blob, tx.tx.serialize());
assert_eq!(tx.tx_hash, block.block.txs[i]); assert_eq!(tx.tx_hash, block.block.transactions[i]);
} }
} }
//------------------------------------------------------ Transaction / Outputs / Key Images //------------------------------------------------------ Transaction / Outputs / Key Images
// Add the miner transaction first. // Add the miner transaction first.
{ {
let tx = &block.block.miner_tx; let tx = &block.block.miner_transaction;
add_tx(tx, &tx.serialize(), &tx.hash(), &chain_height, tables)?; add_tx(tx, &tx.serialize(), &tx.hash(), &chain_height, tables)?;
} }
@ -154,8 +154,8 @@ pub fn pop_block(
let block = Block::read(&mut block_blob.as_slice())?; let block = Block::read(&mut block_blob.as_slice())?;
//------------------------------------------------------ Transaction / Outputs / Key Images //------------------------------------------------------ Transaction / Outputs / Key Images
remove_tx(&block.miner_tx.hash(), tables)?; remove_tx(&block.miner_transaction.hash(), tables)?;
for tx_hash in &block.txs { for tx_hash in &block.transactions {
remove_tx(tx_hash, tables)?; remove_tx(tx_hash, tables)?;
} }
@ -297,7 +297,7 @@ mod test {
// HACK: `add_block()` asserts blocks with non-sequential heights // HACK: `add_block()` asserts blocks with non-sequential heights
// cannot be added, to get around this, manually edit the block height. // cannot be added, to get around this, manually edit the block height.
for (height, block) in blocks.iter_mut().enumerate() { for (height, block) in blocks.iter_mut().enumerate() {
block.height = height as u64; block.height = height;
assert_eq!(block.block.serialize(), block.block_blob); assert_eq!(block.block.serialize(), block.block_blob);
} }
let generated_coins_sum = blocks let generated_coins_sum = blocks
@ -388,7 +388,7 @@ mod test {
assert_eq!(tx.tx_blob, tx2.serialize()); assert_eq!(tx.tx_blob, tx2.serialize());
assert_eq!(tx.tx_weight, tx2.weight()); assert_eq!(tx.tx_weight, tx2.weight());
assert_eq!(tx.tx_hash, block.block.txs[i]); assert_eq!(tx.tx_hash, block.block.transactions[i]);
assert_eq!(tx.tx_hash, tx2.hash()); assert_eq!(tx.tx_hash, tx2.hash());
} }
} }
@ -440,7 +440,7 @@ mod test {
let mut block = block_v9_tx3().clone(); let mut block = block_v9_tx3().clone();
block.height = u64::from(u32::MAX) + 1; block.height = usize::try_from(u32::MAX).unwrap() + 1;
add_block(&block, &mut tables).unwrap(); add_block(&block, &mut tables).unwrap();
} }

View file

@ -25,7 +25,7 @@ use crate::{
pub fn chain_height( pub fn chain_height(
table_block_heights: &impl DatabaseRo<BlockHeights>, table_block_heights: &impl DatabaseRo<BlockHeights>,
) -> Result<BlockHeight, RuntimeError> { ) -> Result<BlockHeight, RuntimeError> {
table_block_heights.len() table_block_heights.len().map(|height| height as usize)
} }
/// Retrieve the height of the top block. /// Retrieve the height of the top block.
@ -47,7 +47,7 @@ pub fn top_block_height(
) -> Result<BlockHeight, RuntimeError> { ) -> Result<BlockHeight, RuntimeError> {
match table_block_heights.len()? { match table_block_heights.len()? {
0 => Err(RuntimeError::KeyNotFound), 0 => Err(RuntimeError::KeyNotFound),
height => Ok(height - 1), height => Ok(height as usize - 1),
} }
} }
@ -111,7 +111,7 @@ mod test {
block_v9_tx3().clone(), block_v9_tx3().clone(),
block_v16_tx0().clone(), block_v16_tx0().clone(),
]; ];
let blocks_len = u64::try_from(blocks.len()).unwrap(); let blocks_len = blocks.len();
// Add blocks. // Add blocks.
{ {
@ -128,7 +128,6 @@ mod test {
); );
for (i, block) in blocks.iter_mut().enumerate() { for (i, block) in blocks.iter_mut().enumerate() {
let i = u64::try_from(i).unwrap();
// HACK: `add_block()` asserts blocks with non-sequential heights // HACK: `add_block()` asserts blocks with non-sequential heights
// cannot be added, to get around this, manually edit the block height. // cannot be added, to get around this, manually edit the block height.
block.height = i; block.height = i;

View file

@ -157,7 +157,7 @@ pub fn output_to_output_on_chain(
) -> Result<OutputOnChain, RuntimeError> { ) -> Result<OutputOnChain, RuntimeError> {
// FIXME: implement lookup table for common values: // FIXME: implement lookup table for common values:
// <https://github.com/monero-project/monero/blob/c8214782fb2a769c57382a999eaf099691c836e7/src/ringct/rctOps.cpp#L322> // <https://github.com/monero-project/monero/blob/c8214782fb2a769c57382a999eaf099691c836e7/src/ringct/rctOps.cpp#L322>
let commitment = ED25519_BASEPOINT_POINT + H() * Scalar::from(amount); let commitment = ED25519_BASEPOINT_POINT + *H * Scalar::from(amount);
let time_lock = if output let time_lock = if output
.output_flags .output_flags
@ -173,7 +173,7 @@ pub fn output_to_output_on_chain(
.unwrap_or(None); .unwrap_or(None);
Ok(OutputOnChain { Ok(OutputOnChain {
height: u64::from(output.height), height: output.height as usize,
time_lock, time_lock,
key, key,
commitment, commitment,
@ -213,7 +213,7 @@ pub fn rct_output_to_output_on_chain(
.unwrap_or(None); .unwrap_or(None);
Ok(OutputOnChain { Ok(OutputOnChain {
height: u64::from(rct_output.height), height: rct_output.height as usize,
time_lock, time_lock,
key, key,
commitment, commitment,

View file

@ -68,7 +68,7 @@ pub fn add_tx(
// so the `u64/usize` is stored without any tag. // so the `u64/usize` is stored without any tag.
// //
// <https://github.com/Cuprate/cuprate/pull/102#discussion_r1558504285> // <https://github.com/Cuprate/cuprate/pull/102#discussion_r1558504285>
match tx.prefix().timelock { match tx.prefix().additional_timelock {
Timelock::None => (), Timelock::None => (),
Timelock::Block(height) => tables.tx_unlock_time_mut().put(&tx_id, &(height as u64))?, Timelock::Block(height) => tables.tx_unlock_time_mut().put(&tx_id, &(height as u64))?,
Timelock::Time(time) => tables.tx_unlock_time_mut().put(&tx_id, &time)?, Timelock::Time(time) => tables.tx_unlock_time_mut().put(&tx_id, &time)?,
@ -106,7 +106,7 @@ pub fn add_tx(
//------------------------------------------------------ Outputs //------------------------------------------------------ Outputs
// Output bit flags. // Output bit flags.
// Set to a non-zero bit value if the unlock time is non-zero. // Set to a non-zero bit value if the unlock time is non-zero.
let output_flags = match tx.prefix().timelock { let output_flags = match tx.prefix().additional_timelock {
Timelock::None => OutputFlags::empty(), Timelock::None => OutputFlags::empty(),
Timelock::Block(_) | Timelock::Time(_) => OutputFlags::NON_ZERO_UNLOCK_TIME, Timelock::Block(_) | Timelock::Time(_) => OutputFlags::NON_ZERO_UNLOCK_TIME,
}; };
@ -141,7 +141,7 @@ pub fn add_tx(
// <https://github.com/monero-project/monero/blob/c8214782fb2a769c57382a999eaf099691c836e7/src/ringct/rctOps.cpp#L322> // <https://github.com/monero-project/monero/blob/c8214782fb2a769c57382a999eaf099691c836e7/src/ringct/rctOps.cpp#L322>
let commitment = if miner_tx { let commitment = if miner_tx {
ED25519_BASEPOINT_POINT ED25519_BASEPOINT_POINT
+ monero_serai::generators::H() * Scalar::from(output.amount.unwrap_or(0)) + *monero_serai::generators::H * Scalar::from(output.amount.unwrap_or(0))
} else { } else {
let commitment = proofs let commitment = proofs
.as_ref() .as_ref()

View file

@ -68,7 +68,7 @@ pub type BlockBlob = StorableVec<u8>;
pub type BlockHash = [u8; 32]; pub type BlockHash = [u8; 32];
/// A block's height. /// A block's height.
pub type BlockHeight = u64; pub type BlockHeight = usize;
/// A key image. /// A key image.
pub type KeyImage = [u8; 32]; pub type KeyImage = [u8; 32];

View file

@ -31,7 +31,7 @@ use crate::data::constants::{
struct VerifiedBlockMap { struct VerifiedBlockMap {
block_blob: &'static [u8], block_blob: &'static [u8],
pow_hash: [u8; 32], pow_hash: [u8; 32],
height: u64, height: usize,
generated_coins: u64, generated_coins: u64,
weight: usize, weight: usize,
long_term_weight: usize, long_term_weight: usize,
@ -68,11 +68,11 @@ impl VerifiedBlockMap {
assert_eq!( assert_eq!(
txs.len(), txs.len(),
block.txs.len(), block.transactions.len(),
"(deserialized txs).len() != (txs hashes in block).len()" "(deserialized txs).len() != (txs hashes in block).len()"
); );
for (tx, tx_hash_in_block) in txs.iter().zip(&block.txs) { for (tx, tx_hash_in_block) in txs.iter().zip(&block.transactions) {
assert_eq!( assert_eq!(
&tx.tx_hash, tx_hash_in_block, &tx.tx_hash, tx_hash_in_block,
"deserialized tx hash is not the same as the one in the parent block" "deserialized tx hash is not the same as the one in the parent block"

View file

@ -59,7 +59,7 @@ impl HttpRpcClient {
/// # Panics /// # Panics
/// This function will panic at any error point, e.g., /// This function will panic at any error point, e.g.,
/// if the node cannot be connected to, if deserialization fails, etc. /// if the node cannot be connected to, if deserialization fails, etc.
pub async fn get_verified_block_information(&self, height: u64) -> VerifiedBlockInformation { pub async fn get_verified_block_information(&self, height: usize) -> VerifiedBlockInformation {
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct Result { struct Result {
blob: String, blob: String,
@ -72,7 +72,7 @@ impl HttpRpcClient {
long_term_weight: usize, long_term_weight: usize,
cumulative_difficulty: u128, cumulative_difficulty: u128,
hash: String, hash: String,
height: u64, height: usize,
pow_hash: String, pow_hash: String,
reward: u64, // generated_coins + total_tx_fees reward: u64, // generated_coins + total_tx_fees
} }
@ -108,7 +108,7 @@ impl HttpRpcClient {
.unwrap(); .unwrap();
let txs: Vec<VerifiedTransactionInformation> = self let txs: Vec<VerifiedTransactionInformation> = self
.get_transaction_verification_data(&block.txs) .get_transaction_verification_data(&block.transactions)
.await .await
.collect(); .collect();
@ -121,7 +121,7 @@ impl HttpRpcClient {
let total_tx_fees = txs.iter().map(|tx| tx.fee).sum::<u64>(); let total_tx_fees = txs.iter().map(|tx| tx.fee).sum::<u64>();
let generated_coins = block let generated_coins = block
.miner_tx .miner_transaction
.prefix() .prefix()
.outputs .outputs
.iter() .iter()
@ -197,7 +197,7 @@ mod tests {
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
async fn assert_eq( async fn assert_eq(
rpc: &HttpRpcClient, rpc: &HttpRpcClient,
height: u64, height: usize,
block_hash: [u8; 32], block_hash: [u8; 32],
pow_hash: [u8; 32], pow_hash: [u8; 32],
generated_coins: u64, generated_coins: u64,

View file

@ -16,4 +16,7 @@ blockchain = []
curve25519-dalek = { workspace = true } curve25519-dalek = { workspace = true }
monero-serai = { workspace = true } monero-serai = { workspace = true }
serde = { workspace = true, optional = true }
borsh = { workspace = true, optional = true }
[dev-dependencies] [dev-dependencies]

View file

@ -30,12 +30,12 @@ pub enum BCReadRequest {
/// Request a block's extended header. /// Request a block's extended header.
/// ///
/// The input is the block's height. /// The input is the block's height.
BlockExtendedHeader(u64), BlockExtendedHeader(usize),
/// Request a block's hash. /// Request a block's hash.
/// ///
/// The input is the block's height. /// The input is the block's height.
BlockHash(u64), BlockHash(usize),
/// Removes the block hashes that are not in the _main_ chain. /// Removes the block hashes that are not in the _main_ chain.
/// ///
@ -45,7 +45,7 @@ pub enum BCReadRequest {
/// Request a range of block extended headers. /// Request a range of block extended headers.
/// ///
/// The input is a range of block heights. /// The input is a range of block heights.
BlockExtendedHeaderInRange(Range<u64>), BlockExtendedHeaderInRange(Range<usize>),
/// Request the current chain height. /// Request the current chain height.
/// ///
@ -136,7 +136,7 @@ pub enum BCResponse {
/// Response to [`BCReadRequest::ChainHeight`]. /// Response to [`BCReadRequest::ChainHeight`].
/// ///
/// Inner value is the chain height, and the top block's hash. /// Inner value is the chain height, and the top block's hash.
ChainHeight(u64, [u8; 32]), ChainHeight(usize, [u8; 32]),
/// Response to [`BCReadRequest::GeneratedCoins`]. /// Response to [`BCReadRequest::GeneratedCoins`].
/// ///

View file

@ -80,7 +80,7 @@ pub struct VerifiedBlockInformation {
/// The block's proof-of-work hash. /// The block's proof-of-work hash.
pub pow_hash: [u8; 32], pub pow_hash: [u8; 32],
/// The block's height. /// The block's height.
pub height: u64, pub height: usize,
/// The amount of generated coins (atomic units) in this block. /// The amount of generated coins (atomic units) in this block.
pub generated_coins: u64, pub generated_coins: u64,
/// The adjusted block size, in bytes. /// The adjusted block size, in bytes.
@ -96,7 +96,7 @@ pub struct VerifiedBlockInformation {
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OutputOnChain { pub struct OutputOnChain {
/// The block height this output belongs to. /// The block height this output belongs to.
pub height: u64, pub height: usize,
/// The timelock of this output, if any. /// The timelock of this output, if any.
pub time_lock: Timelock, pub time_lock: Timelock,
/// The public key of this output, if any. /// The public key of this output, if any.