fix merge

This commit is contained in:
Boog900 2024-08-01 20:57:49 +01:00
parent 91ceda1b01
commit 2b8bc4d67f
No known key found for this signature in database
GPG key ID: 42AB1287CB0041C2
30 changed files with 297 additions and 319 deletions

290
Cargo.lock generated
View file

@ -56,17 +56,6 @@ version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "038dfcf04a5feb68e9c60b21c9625a54c2c0616e79b72b0fd87075a056ae1d1b"
[[package]]
name = "async-lock"
version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18"
dependencies = [
"event-listener",
"event-listener-strategy",
"pin-project-lite",
]
[[package]]
name = "async-stream"
version = "0.3.5"
@ -121,28 +110,12 @@ dependencies = [
"rustc-demangle",
]
[[package]]
name = "base58-monero"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "978e81a45367d2409ecd33369a45dda2e9a3ca516153ec194de1fbda4b9fb79d"
dependencies = [
"thiserror",
"tiny-keccak",
]
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64ct"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b"
[[package]]
name = "bincode"
version = "1.3.3"
@ -346,15 +319,6 @@ version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b82cf0babdbd58558212896d1a4272303a57bdb245c2bf1147185fb45640e70"
[[package]]
name = "concurrent-queue"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "core-foundation"
version = "0.9.4"
@ -436,12 +400,6 @@ version = "0.8.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80"
[[package]]
name = "crunchy"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7"
[[package]]
name = "crypto-bigint"
version = "0.5.5"
@ -449,6 +407,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"
dependencies = [
"subtle",
"zeroize",
]
[[package]]
@ -527,12 +486,10 @@ dependencies = [
"cuprate-test-utils",
"cuprate-types",
"curve25519-dalek",
"dalek-ff-group",
"futures",
"hex",
"hex-literal",
"monero-serai",
"multiexp",
"proptest",
"proptest-derive",
"rand",
@ -555,11 +512,9 @@ dependencies = [
"cuprate-cryptonight",
"cuprate-helper",
"curve25519-dalek",
"dalek-ff-group",
"hex",
"hex-literal",
"monero-serai",
"multiexp",
"proptest",
"proptest-derive",
"rand",
@ -790,7 +745,9 @@ dependencies = [
"futures",
"hex",
"hex-literal",
"monero-rpc",
"monero-serai",
"monero-simple-request-rpc",
"paste",
"pretty_assertions",
"serde",
@ -808,6 +765,7 @@ version = "0.0.0"
name = "cuprate-types"
version = "0.0.0"
dependencies = [
"borsh",
"bytes",
"cuprate-epee-encoding",
"cuprate-fixed-bytes",
@ -862,7 +820,7 @@ dependencies = [
[[package]]
name = "dalek-ff-group"
version = "0.4.1"
source = "git+https://github.com/Cuprate/serai.git?rev=d27d934#d27d93480aa8a849d84214ad4c71d83ce6fea0c1"
source = "git+https://github.com/Cuprate/serai.git?rev=d5205ce#d5205ce2319e09414eb91d12cf38e83a08165f79"
dependencies = [
"crypto-bigint",
"curve25519-dalek",
@ -981,27 +939,6 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "event-listener"
version = "5.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6032be9bd27023a771701cc49f9f053c751055f71efb2e0ae5c15809093675ba"
dependencies = [
"concurrent-queue",
"parking",
"pin-project-lite",
]
[[package]]
name = "event-listener-strategy"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f214dc438f977e6d4e3500aaa277f5ad94ca83fbbd9b1a15713ce2344ccc5a1"
dependencies = [
"event-listener",
"pin-project-lite",
]
[[package]]
name = "fastrand"
version = "2.1.0"
@ -1028,7 +965,7 @@ checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
[[package]]
name = "flexible-transcript"
version = "0.3.2"
source = "git+https://github.com/Cuprate/serai.git?rev=d27d934#d27d93480aa8a849d84214ad4c71d83ce6fea0c1"
source = "git+https://github.com/Cuprate/serai.git?rev=d5205ce#d5205ce2319e09414eb91d12cf38e83a08165f79"
dependencies = [
"blake2",
"digest",
@ -1262,15 +1199,6 @@ version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46"
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest",
]
[[package]]
name = "http"
version = "1.1.0"
@ -1680,63 +1608,163 @@ dependencies = [
"windows-sys 0.48.0",
]
[[package]]
name = "monero-address"
version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?rev=d5205ce#d5205ce2319e09414eb91d12cf38e83a08165f79"
dependencies = [
"curve25519-dalek",
"monero-io",
"monero-primitives",
"std-shims",
"thiserror",
"zeroize",
]
[[package]]
name = "monero-borromean"
version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?rev=d5205ce#d5205ce2319e09414eb91d12cf38e83a08165f79"
dependencies = [
"curve25519-dalek",
"monero-generators",
"monero-io",
"monero-primitives",
"std-shims",
"zeroize",
]
[[package]]
name = "monero-bulletproofs"
version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?rev=d5205ce#d5205ce2319e09414eb91d12cf38e83a08165f79"
dependencies = [
"curve25519-dalek",
"monero-generators",
"monero-io",
"monero-primitives",
"rand_core",
"std-shims",
"thiserror",
"zeroize",
]
[[package]]
name = "monero-clsag"
version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?rev=d5205ce#d5205ce2319e09414eb91d12cf38e83a08165f79"
dependencies = [
"curve25519-dalek",
"dalek-ff-group",
"flexible-transcript",
"group",
"monero-generators",
"monero-io",
"monero-primitives",
"rand_chacha",
"rand_core",
"std-shims",
"subtle",
"thiserror",
"zeroize",
]
[[package]]
name = "monero-generators"
version = "0.4.0"
source = "git+https://github.com/Cuprate/serai.git?rev=d27d934#d27d93480aa8a849d84214ad4c71d83ce6fea0c1"
source = "git+https://github.com/Cuprate/serai.git?rev=d5205ce#d5205ce2319e09414eb91d12cf38e83a08165f79"
dependencies = [
"curve25519-dalek",
"dalek-ff-group",
"group",
"monero-io",
"sha3",
"std-shims",
"subtle",
]
[[package]]
name = "monero-io"
version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?rev=d5205ce#d5205ce2319e09414eb91d12cf38e83a08165f79"
dependencies = [
"curve25519-dalek",
"std-shims",
]
[[package]]
name = "monero-mlsag"
version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?rev=d5205ce#d5205ce2319e09414eb91d12cf38e83a08165f79"
dependencies = [
"curve25519-dalek",
"monero-generators",
"monero-io",
"monero-primitives",
"std-shims",
"thiserror",
"zeroize",
]
[[package]]
name = "monero-primitives"
version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?rev=d5205ce#d5205ce2319e09414eb91d12cf38e83a08165f79"
dependencies = [
"curve25519-dalek",
"monero-generators",
"monero-io",
"sha3",
"std-shims",
"zeroize",
]
[[package]]
name = "monero-rpc"
version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?rev=d5205ce#d5205ce2319e09414eb91d12cf38e83a08165f79"
dependencies = [
"async-trait",
"curve25519-dalek",
"hex",
"monero-address",
"monero-serai",
"serde",
"serde_json",
"std-shims",
"thiserror",
"zeroize",
]
[[package]]
name = "monero-serai"
version = "0.1.4-alpha"
source = "git+https://github.com/Cuprate/serai.git?rev=d27d934#d27d93480aa8a849d84214ad4c71d83ce6fea0c1"
source = "git+https://github.com/Cuprate/serai.git?rev=d5205ce#d5205ce2319e09414eb91d12cf38e83a08165f79"
dependencies = [
"async-lock",
"async-trait",
"base58-monero",
"curve25519-dalek",
"dalek-ff-group",
"digest_auth",
"flexible-transcript",
"group",
"hex",
"hex-literal",
"monero-borromean",
"monero-bulletproofs",
"monero-clsag",
"monero-generators",
"multiexp",
"pbkdf2",
"rand",
"rand_chacha",
"rand_core",
"rand_distr",
"serde",
"serde_json",
"sha3",
"simple-request",
"monero-io",
"monero-mlsag",
"monero-primitives",
"std-shims",
"subtle",
"thiserror",
"tokio",
"zeroize",
]
[[package]]
name = "multiexp"
version = "0.4.0"
source = "git+https://github.com/Cuprate/serai.git?rev=d27d934#d27d93480aa8a849d84214ad4c71d83ce6fea0c1"
name = "monero-simple-request-rpc"
version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?rev=d5205ce#d5205ce2319e09414eb91d12cf38e83a08165f79"
dependencies = [
"ff",
"group",
"rand_core",
"rustversion",
"std-shims",
"zeroize",
"async-trait",
"digest_auth",
"hex",
"monero-rpc",
"simple-request",
"tokio",
]
[[package]]
@ -1796,12 +1824,6 @@ dependencies = [
"winapi",
]
[[package]]
name = "parking"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb813b8af86854136c6922af0598d719255ecb2179515e6e7730d468f05c9cae"
[[package]]
name = "parking_lot"
version = "0.12.3"
@ -1825,35 +1847,12 @@ dependencies = [
"windows-targets 0.52.5",
]
[[package]]
name = "password-hash"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
dependencies = [
"base64ct",
"rand_core",
"subtle",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pbkdf2"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
dependencies = [
"digest",
"hmac",
"password-hash",
"sha2",
]
[[package]]
name = "percent-encoding"
version = "2.3.1"
@ -2406,7 +2405,7 @@ dependencies = [
[[package]]
name = "simple-request"
version = "0.1.0"
source = "git+https://github.com/Cuprate/serai.git?rev=d27d934#d27d93480aa8a849d84214ad4c71d83ce6fea0c1"
source = "git+https://github.com/Cuprate/serai.git?rev=d5205ce#d5205ce2319e09414eb91d12cf38e83a08165f79"
dependencies = [
"http-body-util",
"hyper",
@ -2462,7 +2461,7 @@ checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
[[package]]
name = "std-shims"
version = "0.1.1"
source = "git+https://github.com/Cuprate/serai.git?rev=d27d934#d27d93480aa8a849d84214ad4c71d83ce6fea0c1"
source = "git+https://github.com/Cuprate/serai.git?rev=d5205ce#d5205ce2319e09414eb91d12cf38e83a08165f79"
dependencies = [
"hashbrown 0.14.5",
"spin",
@ -2576,15 +2575,6 @@ dependencies = [
"once_cell",
]
[[package]]
name = "tiny-keccak"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"
dependencies = [
"crunchy",
]
[[package]]
name = "tinystr"
version = "0.7.6"

View file

@ -63,9 +63,9 @@ futures = { version = "0.3.29", default-features = false }
hex = { version = "0.4.3", default-features = false }
hex-literal = { version = "0.4", default-features = false }
indexmap = { version = "2.2.5", 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", rev = "880565c", default-features = false }
monero-serai = { git = "https://github.com/Cuprate/serai.git", rev = "880565c", default-features = false }
monero-rpc = { git = "https://github.com/Cuprate/serai.git", rev = "d5205ce", default-features = false }
monero-simple-request-rpc = { git = "https://github.com/Cuprate/serai.git", rev = "d5205ce", default-features = false }
monero-serai = { git = "https://github.com/Cuprate/serai.git", rev = "d5205ce", default-features = false }
paste = { version = "1.0.14", 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 }

View file

@ -4,7 +4,7 @@ use proptest::{arbitrary::any, prop_assert_eq, prop_compose, proptest};
use crate::hard_forks::{HFVotes, HardFork, NUMB_OF_HARD_FORKS};
const TEST_WINDOW_SIZE: u64 = 25;
const TEST_WINDOW_SIZE: usize = 25;
#[test]
fn target_block_time() {
@ -48,9 +48,9 @@ prop_compose! {
proptest! {
#[test]
fn hf_vote_counter_total_correct(hf_votes in arb_full_hf_votes()) {
prop_assert_eq!(hf_votes.total_votes(), u64::try_from(hf_votes.vote_list.len()).unwrap());
prop_assert_eq!(hf_votes.total_votes(), hf_votes.vote_list.len());
let mut votes = [0_u64; NUMB_OF_HARD_FORKS];
let mut votes = [0_usize; NUMB_OF_HARD_FORKS];
for vote in hf_votes.vote_list.iter() {
// manually go through the list of votes tallying
votes[*vote as usize - 1] += 1;

View file

@ -231,7 +231,7 @@ proptest! {
}
#[test]
fn test_block_unlock_time(height in 1..u64::MAX) {
fn test_block_unlock_time(height in 1..usize::MAX) {
prop_assert!(check_block_time_lock(height, height));
prop_assert!(!check_block_time_lock(height, height - 1));
prop_assert!(check_block_time_lock(height, height+1));

View file

@ -57,7 +57,7 @@ pub struct PreparedBlockExPow {
/// The block's hash.
pub block_hash: [u8; 32],
/// The height of the block.
pub height: u64,
pub height: usize,
/// The weight of the block's miner transaction.
pub miner_tx_weight: usize,
@ -74,7 +74,7 @@ impl PreparedBlockExPow {
let (hf_version, hf_vote) =
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(
MinerTxError::InputNotOfTypeGen,
)))?
@ -88,7 +88,7 @@ impl PreparedBlockExPow {
block_hash: block.hash(),
height: *height,
miner_tx_weight: block.miner_tx.weight(),
miner_tx_weight: block.miner_transaction.weight(),
block,
})
}
@ -128,7 +128,7 @@ impl PreparedBlock {
let (hf_version, hf_vote) =
HardFork::from_block_header(&block.header).map_err(BlockError::HardForkError)?;
let [Input::Gen(height)] = &block.miner_tx.prefix.inputs[..] else {
let [Input::Gen(height)] = &block.miner_transaction.prefix().inputs[..] else {
Err(ConsensusError::Block(BlockError::MinerTxError(
MinerTxError::InputNotOfTypeGen,
)))?
@ -142,12 +142,12 @@ impl PreparedBlock {
block_hash: block.hash(),
pow_hash: calculate_pow_hash(
randomx_vm,
&block.serialize_hashable(),
&block.serialize_pow_hash(),
*height,
&hf_version,
)?,
miner_tx_weight: block.miner_tx.weight(),
miner_tx_weight: block.miner_transaction.weight(),
block,
})
}
@ -172,12 +172,12 @@ impl PreparedBlock {
block_hash: block.block_hash,
pow_hash: calculate_pow_hash(
randomx_vm,
&block.block.serialize_hashable(),
&block.block.serialize_pow_hash(),
block.height,
&block.hf_version,
)?,
miner_tx_weight: block.block.miner_tx.weight(),
miner_tx_weight: block.block.miner_transaction.weight(),
block: block.block,
})
}
@ -359,8 +359,8 @@ where
// Set up the block and just pass it to [`verify_prepped_main_chain_block`]
// We just use the raw `major_version` here, no need to turn it into a `HardFork`.
let rx_vms = if block.header.major_version < 12 {
// We just use the raw `hardfork_version` here, no need to turn it into a `HardFork`.
let rx_vms = if block.header.hardfork_version < 12 {
HashMap::new()
} else {
let BlockChainContextResponse::RxVms(rx_vms) = context_svc
@ -443,12 +443,12 @@ where
check_block_pow(&prepped_block.pow_hash, context.next_difficulty)
.map_err(ConsensusError::Block)?;
if prepped_block.block.txs.len() != txs.len() {
if prepped_block.block.transactions.len() != txs.len() {
return Err(ExtendedConsensusError::TxsIncludedWithBlockIncorrect);
}
if !prepped_block.block.txs.is_empty() {
for (expected_tx_hash, tx) in prepped_block.block.txs.iter().zip(txs.iter()) {
if !prepped_block.block.transactions.is_empty() {
for (expected_tx_hash, tx) in prepped_block.block.transactions.iter().zip(txs.iter()) {
if expected_tx_hash != &tx.tx_hash {
return Err(ExtendedConsensusError::TxsIncludedWithBlockIncorrect);
}

View file

@ -63,7 +63,7 @@ where
};
// Check if the block's miner input is formed correctly.
let [Input::Gen(height)] = &block.miner_tx.prefix.inputs[..] else {
let [Input::Gen(height)] = &block.miner_transaction.prefix().inputs[..] else {
Err(ConsensusError::Block(BlockError::MinerTxError(
MinerTxError::InputNotOfTypeGen,
)))?
@ -79,7 +79,7 @@ where
let prepped_block = {
let rx_vm = alt_rx_vm(
alt_context_cache.chain_height,
block.header.major_version,
block.header.hardfork_version,
alt_context_cache.parent_chain,
&mut alt_context_cache,
&mut context_svc,
@ -188,7 +188,7 @@ where
///
/// If the `hf` is less than 12 (the height RX activates), then [`None`] is returned.
async fn alt_rx_vm<C>(
block_height: u64,
block_height: usize,
hf: u8,
parent_chain: Chain,
alt_chain_context: &mut AltChainContextCache,

View file

@ -12,14 +12,14 @@ pub(crate) fn pull_ordered_transactions(
block: &Block,
mut txs: HashMap<[u8; 32], TransactionVerificationData>,
) -> Result<Vec<TransactionVerificationData>, ExtendedConsensusError> {
if block.txs.len() != txs.len() {
if block.transactions.len() != txs.len() {
return Err(ExtendedConsensusError::TxsIncludedWithBlockIncorrect);
}
let mut ordered_txs = Vec::with_capacity(txs.len());
if !block.txs.is_empty() {
for tx_hash in &block.txs {
if !block.transactions.is_empty() {
for tx_hash in &block.transactions {
let tx = txs
.remove(tx_hash)
.ok_or(ExtendedConsensusError::TxsIncludedWithBlockIncorrect)?;

View file

@ -246,7 +246,7 @@ pub enum BlockChainContextRequest {
/// # Panics
///
/// This will panic if the number of blocks will pop the genesis block.
numb_blocks: u64,
numb_blocks: usize,
},
/// Clear the alt chain context caches.
ClearAltCache,
@ -289,7 +289,7 @@ pub enum BlockChainContextRequest {
/// handle getting the randomX VM of an alt chain.
AltChainRxVM {
/// The height the RandomX VM is needed for.
height: u64,
height: usize,
/// The chain to look in for the seed.
chain: Chain,
/// An internal token to prevent external crates calling this request.

View file

@ -32,10 +32,10 @@ pub struct AltChainContextCache {
pub difficulty_cache: Option<DifficultyCache>,
/// A cached RX VM.
pub cached_rx_vm: Option<(u64, Arc<RandomXVM>)>,
pub cached_rx_vm: Option<(usize, Arc<RandomXVM>)>,
/// The chain height of the alt chain.
pub chain_height: u64,
pub chain_height: usize,
/// The top hash of the alt chain.
pub top_hash: [u8; 32],
/// The [`ChainID`] of the alt chain.
@ -48,7 +48,7 @@ impl AltChainContextCache {
/// Add a new block to the cache.
pub fn add_new_block(
&mut self,
height: u64,
height: usize,
block_hash: [u8; 32],
block_weight: usize,
long_term_block_weight: usize,

View file

@ -48,8 +48,8 @@ impl DifficultyCacheConfig {
}
/// Returns the total amount of blocks we need to track to calculate difficulty
pub fn total_block_count(&self) -> u64 {
(self.window + self.lag).try_into().unwrap()
pub fn total_block_count(&self) -> usize {
self.window + self.lag
}
/// The amount of blocks we account for after removing the outliers.
@ -78,7 +78,7 @@ pub struct DifficultyCache {
/// The current cumulative difficulty of the chain.
pub(crate) cumulative_difficulties: VecDeque<u128>,
/// The last height we accounted for.
pub(crate) last_accounted_height: u64,
pub(crate) last_accounted_height: usize,
/// The config
pub(crate) config: DifficultyCacheConfig,
}
@ -87,7 +87,7 @@ impl DifficultyCache {
/// Initialize the difficulty cache from the specified chain height.
#[instrument(name = "init_difficulty_cache", level = "info", skip(database, config))]
pub async fn init_from_chain_height<D: Database + Clone>(
chain_height: u64,
chain_height: usize,
config: DifficultyCacheConfig,
database: D,
chain: Chain,
@ -104,7 +104,7 @@ impl DifficultyCache {
let (timestamps, cumulative_difficulties) =
get_blocks_in_pow_info(database.clone(), block_start..chain_height, chain).await?;
debug_assert_eq!(timestamps.len() as u64, chain_height - block_start);
debug_assert_eq!(timestamps.len(), chain_height - block_start);
tracing::info!(
"Current chain height: {}, accounting for {} blocks timestamps",
@ -132,7 +132,7 @@ impl DifficultyCache {
#[instrument(name = "pop_blocks_diff_cache", skip_all, fields(numb_blocks = numb_blocks))]
pub async fn pop_blocks_main_chain<D: Database + Clone>(
&mut self,
numb_blocks: u64,
numb_blocks: usize,
database: D,
) -> Result<(), ExtendedConsensusError> {
let Some(retained_blocks) = self
@ -167,7 +167,7 @@ impl DifficultyCache {
database,
new_start_height
// current_chain_height - self.timestamps.len() blocks are already in the cache.
..(current_chain_height - u64::try_from(self.timestamps.len()).unwrap()),
..(current_chain_height - self.timestamps.len()),
Chain::Main,
)
.await?;
@ -187,7 +187,7 @@ impl DifficultyCache {
}
/// 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);
self.last_accounted_height += 1;
@ -199,7 +199,7 @@ impl DifficultyCache {
self.cumulative_difficulties
.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.cumulative_difficulties.pop_front();
}
@ -244,7 +244,7 @@ impl DifficultyCache {
let last_cum_diff = cumulative_difficulties.back().copied().unwrap_or(1);
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((
timestamps.pop_front().unwrap(),
cumulative_difficulties.pop_front().unwrap(),
@ -266,22 +266,21 @@ impl DifficultyCache {
///
/// Will return [`None`] if there aren't enough blocks.
pub fn median_timestamp(&self, numb_blocks: usize) -> Option<u64> {
let mut timestamps =
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.
// otherwise if the chain height is less than `numb_blocks` None is returned
// and if it's more it would be excluded from calculations.
let mut timestamps = self.timestamps.clone();
// all genesis blocks have a timestamp of 0.
// https://cuprate.github.io/monero-book/consensus_rules/genesis_block.html
timestamps.push_front(0);
timestamps.into()
} else {
self.timestamps
.range(self.timestamps.len().checked_sub(numb_blocks)?..)
.copied()
.collect::<Vec<_>>()
};
let mut timestamps = if self.last_accounted_height + 1 == numb_blocks {
// 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
// and if it's more it would be excluded from calculations.
let mut timestamps = self.timestamps.clone();
// all genesis blocks have a timestamp of 0.
// https://cuprate.github.io/monero-book/consensus_rules/genesis_block.html
timestamps.push_front(0);
timestamps.into()
} else {
self.timestamps
.range(self.timestamps.len().checked_sub(numb_blocks)?..)
.copied()
.collect::<Vec<_>>()
};
timestamps.sort_unstable();
debug_assert_eq!(timestamps.len(), numb_blocks);
@ -368,7 +367,7 @@ fn get_window_start_and_end(
#[instrument(name = "get_blocks_timestamps", skip(database), level = "info")]
async fn get_blocks_in_pow_info<D: Database + Clone>(
database: D,
block_heights: Range<u64>,
block_heights: Range<usize>,
chain: Chain,
) -> Result<(VecDeque<u64>, VecDeque<u128>), ExtendedConsensusError> {
tracing::info!("Getting blocks timestamps");

View file

@ -129,7 +129,7 @@ impl HardForkState {
/// This _must_ only be used on a main-chain cache.
pub async fn pop_blocks_main_chain<D: Database + Clone>(
&mut self,
numb_blocks: u64,
numb_blocks: usize,
database: D,
) -> Result<(), ExtendedConsensusError> {
let Some(retained_blocks) = self.votes.total_votes().checked_sub(self.config.window) else {
@ -153,12 +153,11 @@ impl HardForkState {
..current_chain_height
.saturating_sub(numb_blocks)
.saturating_sub(retained_blocks),
usize::try_from(numb_blocks).unwrap(),
numb_blocks,
)
.await?;
self.votes
.reverse_blocks(usize::try_from(numb_blocks).unwrap(), oldest_votes);
self.votes.reverse_blocks(numb_blocks, oldest_votes);
self.last_height -= numb_blocks;
Ok(())

View file

@ -74,9 +74,9 @@ impl RandomX for RandomXVM {
#[derive(Clone, Debug)]
pub struct RandomXVMCache {
/// 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).
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.
pub(crate) cached_vm: Option<([u8; 32], Arc<RandomXVM>)>,
@ -85,7 +85,7 @@ pub struct RandomXVMCache {
impl RandomXVMCache {
#[instrument(name = "init_rx_vm_cache", level = "info", skip(database))]
pub async fn init_from_chain_height<D: Database + Clone>(
chain_height: u64,
chain_height: usize,
hf: &HardFork,
database: D,
) -> Result<Self, ExtendedConsensusError> {
@ -94,7 +94,8 @@ impl RandomXVMCache {
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 {
tracing::debug!("Creating RandomX VMs");
@ -132,7 +133,7 @@ impl RandomXVMCache {
/// of them first.
pub async fn get_alt_vm<D: Database>(
&mut self,
height: u64,
height: usize,
chain: Chain,
database: D,
) -> Result<Arc<RandomXVM>, ExtendedConsensusError> {
@ -161,7 +162,7 @@ impl RandomXVMCache {
}
/// Get the main-chain 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()) {
// No difference in the amount of seeds to VMs.
Some(0) => (),
@ -213,7 +214,7 @@ impl RandomXVMCache {
}
/// Removes all the RandomX VMs above the `new_height`.
pub fn pop_blocks_main_chain(&mut self, new_height: u64) {
pub fn pop_blocks_main_chain(&mut self, new_height: usize) {
self.seeds.retain(|(height, _)| *height < new_height);
self.vms.retain(|height, _| *height < new_height);
}
@ -221,7 +222,7 @@ impl RandomXVMCache {
/// Add a new block to the VM cache.
///
/// 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) {
tracing::debug!("Block {height} is a randomX seed height, adding it to the cache.",);
@ -242,7 +243,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
/// 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);
if is_randomx_seed_height(last_height) {
seeds.push(last_height);
@ -265,7 +266,7 @@ pub(crate) fn get_last_rx_seed_heights(mut last_height: u64, mut amount: usize)
/// Gets the block hashes for the heights specified.
async fn get_block_hashes<D: Database + Clone>(
heights: Vec<u64>,
heights: Vec<usize>,
database: D,
) -> Result<Vec<[u8; 32]>, ExtendedConsensusError> {
let mut fut = FuturesOrdered::new();

View file

@ -24,21 +24,21 @@ use cuprate_types::{
use crate::{Database, ExtendedConsensusError, HardFork};
/// The short term block weight window.
const SHORT_TERM_WINDOW: u64 = 100;
const SHORT_TERM_WINDOW: usize = 100;
/// The long term block weight window.
const LONG_TERM_WINDOW: u64 = 100000;
const LONG_TERM_WINDOW: usize = 100000;
/// Configuration for the block weight cache.
///
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct BlockWeightsCacheConfig {
short_term_window: u64,
long_term_window: u64,
short_term_window: usize,
long_term_window: usize,
}
impl 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 {
short_term_window,
long_term_window,
@ -67,7 +67,7 @@ pub struct BlockWeightsCache {
long_term_weights: RollingMedian<usize>,
/// The height of the top block.
pub(crate) tip_height: u64,
pub(crate) tip_height: usize,
pub(crate) config: BlockWeightsCacheConfig,
}
@ -76,7 +76,7 @@ impl BlockWeightsCache {
/// Initialize the [`BlockWeightsCache`] at the the given chain height.
#[instrument(name = "init_weight_cache", level = "info", skip(database, config))]
pub async fn init_from_chain_height<D: Database + Clone>(
chain_height: u64,
chain_height: usize,
config: BlockWeightsCacheConfig,
database: D,
chain: Chain,
@ -125,10 +125,10 @@ impl BlockWeightsCache {
#[instrument(name = "pop_blocks_weight_cache", skip_all, fields(numb_blocks = numb_blocks))]
pub async fn pop_blocks_main_chain<D: Database + Clone>(
&mut self,
numb_blocks: u64,
numb_blocks: usize,
database: D,
) -> Result<(), ExtendedConsensusError> {
if self.long_term_weights.window_len() <= usize::try_from(numb_blocks).unwrap() {
if self.long_term_weights.window_len() <= numb_blocks {
// More blocks to pop than we have in the cache, so just restart a new cache.
*self = Self::init_from_chain_height(
self.tip_height - numb_blocks + 1,
@ -150,7 +150,7 @@ impl BlockWeightsCache {
let old_long_term_weights = get_long_term_weight_in_range(
new_long_term_start_height
// current_chain_height - self.long_term_weights.len() blocks are already in the cache.
..(chain_height - u64::try_from(self.long_term_weights.window_len()).unwrap()),
..(chain_height - self.long_term_weights.window_len()),
database.clone(),
Chain::Main,
)
@ -163,11 +163,11 @@ impl BlockWeightsCache {
let old_short_term_weights = get_blocks_weight_in_range(
new_short_term_start_height
// current_chain_height - self.long_term_weights.len() blocks are already in the cache.
..(chain_height - u64::try_from(self.short_term_block_weights.window_len()).unwrap()),
..(chain_height - self.short_term_block_weights.window_len()),
database,
Chain::Main
Chain::Main,
)
.await?;
.await?;
for _ in 0..numb_blocks {
self.short_term_block_weights.pop_back();
@ -186,7 +186,7 @@ impl BlockWeightsCache {
///
/// The block_height **MUST** be one more than the last height the cache has
/// 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);
self.tip_height += 1;
tracing::debug!(
@ -290,7 +290,7 @@ pub fn calculate_block_long_term_weight(
/// Gets the block weights from the blocks with heights in the range provided.
#[instrument(name = "get_block_weights", skip(database))]
async fn get_blocks_weight_in_range<D: Database + Clone>(
range: Range<u64>,
range: Range<usize>,
database: D,
chain: Chain,
) -> Result<Vec<usize>, ExtendedConsensusError> {
@ -312,7 +312,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.
#[instrument(name = "get_long_term_weights", skip(database), level = "info")]
async fn get_long_term_weight_in_range<D: Database + Clone>(
range: Range<u64>,
range: Range<usize>,
database: D,
chain: Chain,
) -> Result<Vec<usize>, ExtendedConsensusError> {

View file

@ -29,7 +29,7 @@ const TEST_CONTEXT_CONFIG: ContextConfig = ContextConfig {
#[tokio::test]
async fn context_invalidated_on_new_block() -> Result<(), tower::BoxError> {
const BLOCKCHAIN_HEIGHT: u64 = 6000;
const BLOCKCHAIN_HEIGHT: usize = 6000;
let mut runner = TestRunner::default();
let db = arb_dummy_database(BLOCKCHAIN_HEIGHT.try_into().unwrap())
@ -71,7 +71,7 @@ async fn context_invalidated_on_new_block() -> Result<(), tower::BoxError> {
#[tokio::test]
async fn context_height_correct() -> Result<(), tower::BoxError> {
const BLOCKCHAIN_HEIGHT: u64 = 6000;
const BLOCKCHAIN_HEIGHT: usize = 6000;
let mut runner = TestRunner::default();
let db = arb_dummy_database(BLOCKCHAIN_HEIGHT.try_into().unwrap())

View file

@ -82,14 +82,14 @@ async fn calculate_diff_3000000_3002000() -> Result<(), tower::BoxError> {
for (i, diff_info) in DIF_3000000_3002000
.windows(2)
.skip(cfg.total_block_count() as usize - 1)
.skip(cfg.total_block_count() - 1)
.enumerate()
{
let diff = diff_info[1].0 - diff_info[0].0;
assert_eq!(diff_cache.next_difficulty(&HardFork::V16), diff);
diff_cache.new_block(3_000_720 + i as u64, diff_info[1].1, diff_info[1].0);
diff_cache.new_block(3_000_720 + i, diff_info[1].1, diff_info[1].0);
}
Ok(())
@ -234,7 +234,7 @@ proptest! {
new_cache.new_block(new_cache.last_accounted_height+1, timestamp, cumulative_difficulty);
}
new_cache.pop_blocks_main_chain(blocks_to_pop as u64, database).await?;
new_cache.pop_blocks_main_chain(blocks_to_pop, database).await?;
prop_assert_eq!(new_cache, old_cache);
@ -258,7 +258,7 @@ proptest! {
new_cache.new_block(new_cache.last_accounted_height+1, timestamp, cumulative_difficulty);
}
new_cache.pop_blocks_main_chain(blocks_to_pop as u64, database).await?;
new_cache.pop_blocks_main_chain(blocks_to_pop, database).await?;
prop_assert_eq!(new_cache, old_cache);

View file

@ -10,7 +10,7 @@ use crate::{
},
};
const TEST_WINDOW_SIZE: u64 = 25;
const TEST_WINDOW_SIZE: usize = 25;
const TEST_HFS: [HFInfo; NUMB_OF_HARD_FORKS] = [
HFInfo::new(0, 0),
@ -79,7 +79,7 @@ async fn hf_v15_v16_correct() {
for (i, (_, vote)) in HFS_2688888_2689608.into_iter().enumerate() {
assert_eq!(state.current_hardfork, HardFork::V15);
state.new_block(vote, (2688888 + i) as u64);
state.new_block(vote, 2688888 + i);
}
assert_eq!(state.current_hardfork, HardFork::V16);
@ -91,8 +91,8 @@ proptest! {
extra_hfs in vec(any::<HardFork>(), 0..100)
) {
tokio_test::block_on(async move {
let numb_hfs = hfs.len() as u64;
let numb_pop_blocks = extra_hfs.len() as u64;
let numb_hfs = hfs.len();
let numb_pop_blocks = extra_hfs.len();
let mut db_builder = DummyDatabaseBuilder::default();
@ -102,7 +102,7 @@ proptest! {
);
}
let db = db_builder.finish(Some(numb_hfs as usize));
let db = db_builder.finish(Some(numb_hfs ));
let mut state = HardForkState::init_from_chain_height(
numb_hfs,
@ -114,7 +114,7 @@ proptest! {
let state_clone = state.clone();
for (i, hf) in extra_hfs.into_iter().enumerate() {
state.new_block(hf, state.last_height + u64::try_from(i).unwrap() + 1);
state.new_block(hf, state.last_height + i + 1);
}
state.pop_blocks_main_chain(numb_pop_blocks, db).await?;

View file

@ -123,14 +123,14 @@ async fn weight_cache_calculates_correct_median() -> Result<(), tower::BoxError>
.await?;
for height in 1..=100 {
weight_cache.new_block(height as u64, height, height);
weight_cache.new_block(height, height, height);
assert_eq!(weight_cache.median_short_term_weight(), height / 2);
assert_eq!(weight_cache.median_long_term_weight(), height / 2);
}
for height in 101..=5000 {
weight_cache.new_block(height as u64, height, height);
weight_cache.new_block(height, height, height);
assert_eq!(weight_cache.median_long_term_weight(), height / 2);
}
@ -162,7 +162,7 @@ async fn calc_bw_ltw_2850000_3050000() {
weight_cache.median_long_term_weight(),
);
assert_eq!(calc_ltw, *ltw);
weight_cache.new_block((2950000 + i) as u64, *weight, *ltw);
weight_cache.new_block(2950000 + i, *weight, *ltw);
}
}

View file

@ -196,10 +196,7 @@ impl Service<BCReadRequest> for DummyDatabase {
)
}
BCReadRequest::ChainHeight => {
let height: u64 = dummy_height
.unwrap_or(blocks.read().unwrap().len())
.try_into()
.unwrap();
let height = dummy_height.unwrap_or(blocks.read().unwrap().len());
let mut top_hash = [0; 32];
top_hash[0..8].copy_from_slice(&height.to_le_bytes());

View file

@ -121,7 +121,7 @@ pub enum ChainSvcResponse {
/// The response for [`ChainSvcRequest::FindFirstUnknown`].
///
/// Contains the index of the first unknown block and its expected height.
FindFirstUnknown(Option<(usize, u64)>),
FindFirstUnknown(Option<(usize, usize)>),
/// The response for [`ChainSvcRequest::CumulativeDifficulty`].
///
/// The current cumulative difficulty of our chain.
@ -207,7 +207,7 @@ struct BlockDownloader<N: NetworkZone, S, C> {
/// The amount of blocks to request in the next batch.
amount_of_blocks_to_request: usize,
/// 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.
///
@ -225,12 +225,12 @@ struct BlockDownloader<N: NetworkZone, S, C> {
/// The current inflight requests.
///
/// 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.
///
/// Wrapped in [`Reverse`] so we prioritize early batches.
failed_batches: BinaryHeap<Reverse<u64>>,
failed_batches: BinaryHeap<Reverse<usize>>,
block_queue: BlockQueue,
@ -524,7 +524,7 @@ where
/// Handles a response to a request to get blocks from a peer.
async fn handle_download_batch_res(
&mut self,
start_height: u64,
start_height: usize,
res: Result<(ClientPoolDropGuard<N>, BlockBatch), BlockDownloadError>,
chain_tracker: &mut ChainTracker<N>,
pending_peers: &mut BTreeMap<PruningSeed, Vec<ClientPoolDropGuard<N>>>,
@ -692,18 +692,19 @@ where
/// The return value from the block download tasks.
struct BlockDownloadTaskResponse<N: NetworkZone> {
/// The start height of the batch.
start_height: u64,
start_height: usize,
/// A result containing the batch or an error.
result: Result<(ClientPoolDropGuard<N>, BlockBatch), BlockDownloadError>,
}
/// 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 + u64::try_from(length).unwrap(),
CRYPTONOTE_MAX_BLOCK_HEIGHT,
)
&& pruning_seed.has_full_block(start_height + length, CRYPTONOTE_MAX_BLOCK_HEIGHT)
}
/// Calculates the next amount of blocks to request in a batch.

View file

@ -15,7 +15,7 @@ use super::{BlockBatch, BlockDownloadError};
#[derive(Debug, Clone)]
pub struct ReadyQueueBatch {
/// The start height of the batch.
pub start_height: u64,
pub start_height: usize,
/// The batch of blocks.
pub block_batch: BlockBatch,
}
@ -64,7 +64,7 @@ impl BlockQueue {
}
/// 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)
}
@ -80,13 +80,13 @@ impl BlockQueue {
pub async fn add_incoming_batch(
&mut self,
new_batch: ReadyQueueBatch,
oldest_in_flight_start_height: Option<u64>,
oldest_in_flight_start_height: Option<usize>,
) -> Result<(), BlockDownloadError> {
self.ready_batches_size += new_batch.block_batch.size;
self.ready_batches.push(new_batch);
// 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
.ready_batches
@ -124,7 +124,7 @@ mod tests {
use super::*;
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 {
let (_, peer_handle) = HandleBuilder::new().build();
ReadyQueueBatch {

View file

@ -89,7 +89,7 @@ proptest! {
prop_compose! {
/// Returns a strategy to generate a [`Transaction`] that is valid for the block downloader.
fn dummy_transaction_stragtegy(height: u64)
fn dummy_transaction_stragtegy(height: usize)
(
extra in vec(any::<u8>(), 0..1_000),
timelock in 1_usize..50_000_000,
@ -97,7 +97,7 @@ prop_compose! {
-> Transaction {
Transaction::V1 {
prefix: TransactionPrefix {
timelock: Timelock::Block(timelock),
additional_timelock: Timelock::Block(timelock),
inputs: vec![Input::Gen(height)],
outputs: vec![],
extra,
@ -110,11 +110,11 @@ prop_compose! {
prop_compose! {
/// Returns a strategy to generate a [`Block`] that is valid for the block downloader.
fn dummy_block_stragtegy(
height: u64,
height: usize,
previous: [u8; 32],
)
(
miner_tx in dummy_transaction_stragtegy(height),
miner_transaction in dummy_transaction_stragtegy(height),
txs in vec(dummy_transaction_stragtegy(height), 0..25)
)
-> (Block, Vec<Transaction>) {
@ -127,8 +127,8 @@ prop_compose! {
previous,
nonce: 0,
},
miner_tx,
txs: txs.iter().map(Transaction::hash).collect(),
miner_transaction,
transactions: txs.iter().map(Transaction::hash).collect(),
},
txs
)
@ -156,7 +156,7 @@ prop_compose! {
for (height, mut block) in blocks.into_iter().enumerate() {
if let Some(last) = blockchain.last() {
block.0.header.previous = *last.0;
block.0.miner_tx.prefix_mut().inputs = vec![Input::Gen(height as u64)]
block.0.miner_transaction.prefix_mut().inputs = vec![Input::Gen(height)]
}
blockchain.insert(block.0.hash(), block);

View file

@ -38,9 +38,9 @@ pub fn init(config: Config) -> Result<(DatabaseReadHandle, DatabaseWriteHandle),
///
/// The height offset is the difference between the top block's height and the block height that should be in that position.
#[inline]
pub(super) const fn compact_history_index_to_height_offset<const INITIAL_BLOCKS: u64>(
i: u64,
) -> u64 {
pub(super) const fn compact_history_index_to_height_offset<const INITIAL_BLOCKS: usize>(
i: usize,
) -> usize {
// If the position is below the initial blocks just return the position back
if i <= INITIAL_BLOCKS {
i
@ -56,8 +56,8 @@ pub(super) const fn compact_history_index_to_height_offset<const INITIAL_BLOCKS:
///
/// The genesis must always be included in the compact history.
#[inline]
pub(super) const fn compact_history_genesis_not_included<const INITIAL_BLOCKS: u64>(
top_block_height: u64,
pub(super) const fn compact_history_genesis_not_included<const INITIAL_BLOCKS: usize>(
top_block_height: usize,
) -> bool {
// If the top block height is less than the initial blocks then it will always be included.
// Otherwise, we use the fact that to reach the genesis block this statement must be true (for a
@ -81,7 +81,7 @@ mod tests {
proptest! {
#[test]
fn compact_history(top_height in 0_u64..500_000_000) {
fn compact_history(top_height in 0_usize..500_000_000) {
let mut heights = (0..)
.map(compact_history_index_to_height_offset::<11>)
.map_while(|i| top_height.checked_sub(i))

View file

@ -85,7 +85,7 @@
//!
//! // Prepare a request to write block.
//! let mut block = block_v16_tx0().clone();
//! # block.height = 0_u64; // must be 0th height or panic in `add_block()`
//! # block.height = 0_usize; // must be 0th height or panic in `add_block()`
//! let request = BCWriteRequest::WriteBlock(block);
//!
//! // Send the request.

View file

@ -403,7 +403,7 @@ fn chain_height(env: &ConcreteEnv) -> ResponseResult {
/// [`BCReadRequest::GeneratedCoins`].
#[inline]
fn generated_coins(env: &ConcreteEnv, height: u64) -> ResponseResult {
fn generated_coins(env: &ConcreteEnv, height: usize) -> ResponseResult {
// Single-threaded, no `ThreadLocal` required.
let env_inner = env.env_inner();
let tx_ro = env_inner.tx_ro()?;
@ -555,7 +555,7 @@ fn compact_chain_history(env: &ConcreteEnv) -> ResponseResult {
);
/// The amount of top block IDs in the compact chain.
const INITIAL_BLOCKS: u64 = 11;
const INITIAL_BLOCKS: usize = 11;
// rayon is not used here because the amount of block IDs is expected to be small.
let mut block_ids = (0..)

View file

@ -79,7 +79,7 @@ async fn test_template(
// cannot be added, to get around this, manually edit the block height.
for (i, block_fn) in block_fns.iter().enumerate() {
let mut block = block_fn().clone();
block.height = i as u64;
block.height = i;
// Request a block to be written, assert it was written.
let request = BCWriteRequest::WriteBlock(block);

View file

@ -13,7 +13,9 @@ cuprate-p2p-core = { path = "../p2p/p2p-core", features = ["borsh"] }
hex = { workspace = true }
hex-literal = { workspace = true }
monero-serai = { workspace = true, features = ["std", "http-rpc"] }
monero-serai = { workspace = true, features = ["std"] }
monero-simple-request-rpc = { workspace = true }
monero-rpc = { workspace = true }
futures = { workspace = true, features = ["std"] }
async-trait = { workspace = true }
tokio = { workspace = true, features = ["full"] }

View file

@ -34,12 +34,12 @@ macro_rules! const_block_blob {
#[doc = ""]
#[doc = concat!("let block = Block::read(&mut ", stringify!($name), ").unwrap();")]
#[doc = ""]
#[doc = concat!("assert_eq!(block.header.major_version, ", $major_version, ");")]
#[doc = concat!("assert_eq!(block.header.minor_version, ", $minor_version, ");")]
#[doc = concat!("assert_eq!(block.header.hardfork_version, ", $major_version, ");")]
#[doc = concat!("assert_eq!(block.header.hardfork_signal, ", $minor_version, ");")]
#[doc = concat!("assert_eq!(block.header.timestamp, ", $timestamp, ");")]
#[doc = concat!("assert_eq!(block.header.nonce, ", $nonce, ");")]
#[doc = concat!("assert!(matches!(block.miner_tx.prefix.inputs[0], Input::Gen(", $height, ")));")]
#[doc = concat!("assert_eq!(block.txs.len(), ", $tx_len, ");")]
#[doc = concat!("assert!(matches!(block.miner_transaction.prefix().inputs[0], Input::Gen(", $height, ")));")]
#[doc = concat!("assert_eq!(block.transactions.len(), ", $tx_len, ");")]
#[doc = concat!("assert_eq!(hex::encode(block.hash()), \"", $hash, "\")")]
/// ```
pub const $name: &[u8] = include_bytes!($data_path);
@ -107,7 +107,6 @@ macro_rules! const_tx_blob {
timelock: $timelock:expr, // Transaction's timelock (use the real type `Timelock`)
input_len: $input_len:literal, // Amount of inputs
output_len: $output_len:literal, // Amount of outputs
signatures_len: $signatures_len:literal, // Amount of signatures
) => {
#[doc = concat!("Transaction with hash `", $hash, "`.")]
///
@ -117,11 +116,10 @@ macro_rules! const_tx_blob {
#[doc = ""]
#[doc = concat!("let tx = Transaction::read(&mut ", stringify!($name), ").unwrap();")]
#[doc = ""]
#[doc = concat!("assert_eq!(tx.prefix.version, ", $version, ");")]
#[doc = concat!("assert_eq!(tx.prefix.timelock, ", stringify!($timelock), ");")]
#[doc = concat!("assert_eq!(tx.prefix.inputs.len(), ", $input_len, ");")]
#[doc = concat!("assert_eq!(tx.prefix.outputs.len(), ", $output_len, ");")]
#[doc = concat!("assert_eq!(tx.signatures.len(), ", $signatures_len, ");")]
#[doc = concat!("assert_eq!(tx.version(), ", $version, ");")]
#[doc = concat!("assert_eq!(tx.prefix().additional_timelock, ", stringify!($timelock), ");")]
#[doc = concat!("assert_eq!(tx.prefix().inputs.len(), ", $input_len, ");")]
#[doc = concat!("assert_eq!(tx.prefix().outputs.len(), ", $output_len, ");")]
#[doc = concat!("assert_eq!(hex::encode(tx.hash()), \"", $hash, "\")")]
/// ```
pub const $name: &[u8] = include_bytes!($data_path);
@ -136,7 +134,6 @@ const_tx_blob! {
timelock: Timelock::Block(100_081),
input_len: 1,
output_len: 5,
signatures_len: 0,
}
const_tx_blob! {
@ -147,7 +144,6 @@ const_tx_blob! {
timelock: Timelock::None,
input_len: 19,
output_len: 61,
signatures_len: 19,
}
const_tx_blob! {
@ -158,7 +154,6 @@ const_tx_blob! {
timelock: Timelock::None,
input_len: 46,
output_len: 46,
signatures_len: 46,
}
const_tx_blob! {
@ -169,7 +164,6 @@ const_tx_blob! {
timelock: Timelock::None,
input_len: 1,
output_len: 2,
signatures_len: 0,
}
const_tx_blob! {
@ -180,7 +174,6 @@ const_tx_blob! {
timelock: Timelock::None,
input_len: 1,
output_len: 2,
signatures_len: 0,
}
const_tx_blob! {
@ -191,7 +184,6 @@ const_tx_blob! {
timelock: Timelock::None,
input_len: 2,
output_len: 2,
signatures_len: 0,
}
const_tx_blob! {
@ -202,7 +194,6 @@ const_tx_blob! {
timelock: Timelock::None,
input_len: 2,
output_len: 5,
signatures_len: 2,
}
const_tx_blob! {
@ -213,7 +204,6 @@ const_tx_blob! {
timelock: Timelock::None,
input_len: 2,
output_len: 2,
signatures_len: 0,
}
//---------------------------------------------------------------------------------------------------- Tests

View file

@ -21,9 +21,8 @@ cuprate-fixed-bytes = { path = "../net/fixed-bytes" }
bytes = { workspace = true }
curve25519-dalek = { workspace = true }
monero-serai = { workspace = true }
serde = { workspace = true, features = ["derive"], optional = true }
serde = { workspace = true, optional = true }
serde = { workspace = true, features = ["derive"], optional = true }
borsh = { workspace = true, optional = true }
[dev-dependencies]

View file

@ -25,12 +25,12 @@ pub enum BCReadRequest {
/// Request a block's extended header.
///
/// The input is the block's height.
BlockExtendedHeader(u64),
BlockExtendedHeader(usize),
/// Request a block's hash.
///
/// The input is the block's height and the chain it is on.
BlockHash(u64, Chain),
BlockHash(usize, Chain),
/// Request to check if we have a block and which [`Chain`] it is on.
///
@ -45,7 +45,7 @@ pub enum BCReadRequest {
/// Request a range of block extended headers.
///
/// The input is a range of block heights.
BlockExtendedHeaderInRange(Range<u64>, Chain),
BlockExtendedHeaderInRange(Range<usize>, Chain),
/// Request the current chain height.
///
@ -53,7 +53,7 @@ pub enum BCReadRequest {
ChainHeight,
/// Request the total amount of generated coins (atomic units) at this height.
GeneratedCoins(u64),
GeneratedCoins(usize),
/// Request data for multiple outputs.
///
@ -137,7 +137,7 @@ pub enum BCResponse {
/// Response to [`BCReadRequest::FindBlock`].
///
/// Inner value is the chain and height of the block if found.
FindBlock(Option<(Chain, u64)>),
FindBlock(Option<(Chain, usize)>),
/// Response to [`BCReadRequest::FilterUnknownHashes`].
///
@ -152,7 +152,7 @@ pub enum BCResponse {
/// Response to [`BCReadRequest::ChainHeight`].
///
/// Inner value is the chain height, and the top block's hash.
ChainHeight(u64, [u8; 32]),
ChainHeight(usize, [u8; 32]),
/// Response to [`BCReadRequest::GeneratedCoins`].
///
@ -195,7 +195,7 @@ pub enum BCResponse {
/// Contains the index of the first unknown block and its expected height.
///
/// This will be [`None`] if all blocks were known.
FindFirstUnknown(Option<(usize, u64)>),
FindFirstUnknown(Option<(usize, usize)>),
//------------------------------------------------------ Writes
/// Response to [`BCWriteRequest::WriteBlock`].

View file

@ -128,7 +128,7 @@ pub struct AltBlockInformation {
/// The block's proof-of-work hash.
pub pow_hash: [u8; 32],
/// The block's height.
pub height: u64,
pub height: usize,
/// The adjusted block size, in bytes.
pub weight: usize,
/// The long term block weight, which is the weight factored in with previous block weights.