From 1ffa86c5ae6092f60746a2e0b9bf502afa4ece20 Mon Sep 17 00:00:00 2001 From: "hinto.janai" Date: Tue, 26 Nov 2024 19:23:33 -0500 Subject: [PATCH] review fixes --- binaries/cuprated/src/rpc/helper.rs | 2 +- binaries/cuprated/src/rpc/json.rs | 92 ++++++++++++------ .../cuprated/src/rpc/request/address_book.rs | 2 +- .../cuprated/src/rpc/request/blockchain.rs | 2 +- .../src/rpc/request/blockchain_context.rs | 4 +- .../src/rpc/request/blockchain_manager.rs | 2 +- binaries/cuprated/src/rpc/request/txpool.rs | 2 +- rpc/interface/src/rpc_handler_dummy.rs | 1 - rpc/types/src/json.rs | 3 - rpc/types/src/misc/address_type.rs | 97 ------------------- rpc/types/src/misc/mod.rs | 2 - types/src/address_type.rs | 2 +- 12 files changed, 68 insertions(+), 143 deletions(-) delete mode 100644 rpc/types/src/misc/address_type.rs diff --git a/binaries/cuprated/src/rpc/helper.rs b/binaries/cuprated/src/rpc/helper.rs index 5ee42444..e12c20a7 100644 --- a/binaries/cuprated/src/rpc/helper.rs +++ b/binaries/cuprated/src/rpc/helper.rs @@ -142,7 +142,7 @@ pub(super) async fn check_height( if height > top_height { return Err(anyhow!( - "Requested block height: {height} greater than current top block height: {top_height}", + "Requested block height: {height} greater than top block height: {top_height}", )); } diff --git a/binaries/cuprated/src/rpc/json.rs b/binaries/cuprated/src/rpc/json.rs index 0bd41255..272c42b2 100644 --- a/binaries/cuprated/src/rpc/json.rs +++ b/binaries/cuprated/src/rpc/json.rs @@ -1,10 +1,13 @@ //! RPC request handler functions (JSON-RPC). //! //! TODO: -//! Many handlers have `todo!()`s for internals that must be completed, see: +//! Many handlers have `todo!()`s for other Cuprate internals that must be completed, see: //! -use std::time::{Duration, Instant}; +use std::{ + num::NonZero, + time::{Duration, Instant}, +}; use anyhow::{anyhow, Error}; use monero_serai::block::Block; @@ -970,20 +973,21 @@ async fn calc_pow( let block = Block::read(&mut block_blob.as_slice())?; let seed_hash = helper::hex_to_hash(request.seed_hash)?; - let block_weight = todo!("calculate block weight"); + // let block_weight = todo!(); - let median_for_block_reward = blockchain_context::context(&mut state.blockchain_context) - .await? - .unchecked_blockchain_context() - .context_to_verify_block - .median_weight_for_block_reward; + // let median_for_block_reward = blockchain_context::context(&mut state.blockchain_context) + // .await? + // .unchecked_blockchain_context() + // .context_to_verify_block + // .median_weight_for_block_reward; - if cuprate_consensus_rules::blocks::check_block_weight(block_weight, median_for_block_reward) - .is_err() - { - return Err(anyhow!("Block blob size is too big, rejecting block")); - } + // if cuprate_consensus_rules::blocks::check_block_weight(block_weight, median_for_block_reward) + // .is_err() + // { + // return Err(anyhow!("Block blob size is too big, rejecting block")); + // } + // TODO: will `CalculatePow` do the above checks? let pow_hash = blockchain_context::calculate_pow( &mut state.blockchain_context, hardfork, @@ -1022,9 +1026,9 @@ fn add_aux_pow_inner( mut state: CupratedRpcHandler, request: AddAuxPowRequest, ) -> Result { - if request.aux_pow.is_empty() { + let Some(non_zero_len) = NonZero::::new(request.aux_pow.len()) else { return Err(anyhow!("Empty `aux_pow` vector")); - } + }; let aux_pow = request .aux_pow @@ -1040,21 +1044,41 @@ fn add_aux_pow_inner( // Boxed slices are used over `Vec` to slightly // safe-guard against accidently pushing to it. - // --- BEGIN AUX POW IMPL --- - - // Original impl: - // - - let len = aux_pow.len(); - // TODO: why is this here? it does nothing: // - let mut path_domain = 1_usize; - while 1 << path_domain < len { - path_domain += 1; - } + // let mut path_domain = 1_usize; + // while 1 << path_domain < len { + // path_domain += 1; + // } + + fn find_nonce( + aux_pow: &[cuprate_types::AuxPow], + non_zero_len: NonZero, + aux_pow_len: usize, + ) -> Result<(u32, Box<[u32]>), Error> { + /// + fn get_aux_slot(id: &[u8; 32], nonce: u32, n_aux_chains: NonZero) -> u32 { + const HASH_SIZE: usize = 32; + + let mut buf = [0; HASH_SIZE + size_of::() + 1]; + buf[..HASH_SIZE].copy_from_slice(id); + + let v: [u8; 4] = nonce.to_le_bytes(); + buf[HASH_SIZE..HASH_SIZE + size_of::()].copy_from_slice(&v); + + const HASH_KEY_MM_SLOT: u8 = b'm'; + buf[HASH_SIZE + size_of::()] = HASH_KEY_MM_SLOT; + + fn sha256sum(buf: &[u8]) -> [u8; 32] { + todo!() + } + let res = sha256sum(&buf); + + let v = u32::from_le_bytes(res[..4].try_into().unwrap()); + + v % n_aux_chains.get() + } - fn find_nonce(aux_pow_len: usize) -> Result<(u32, Box<[u32]>), Error> { // INVARIANT: this must be the same `.len()` as `aux_pow` let mut slots: Box<[u32]> = vec![u32::MAX; aux_pow_len].into_boxed_slice(); let mut slot_seen: Box<[bool]> = vec![false; aux_pow_len].into_boxed_slice(); @@ -1063,7 +1087,12 @@ fn add_aux_pow_inner( for nonce in 0..=MAX_NONCE { for i in &mut slots { - let slot_u32: u32 = todo!("const uint32_t slot = cryptonote::get_aux_slot(aux_pow[idx].first, nonce, aux_pow.size());"); + let slot_u32 = get_aux_slot( + &aux_pow[u32_to_usize(*i)].id, + nonce, + non_zero_len.try_into().unwrap(), + ); + let slot = u32_to_usize(slot_u32); if slot >= aux_pow_len { @@ -1084,7 +1113,8 @@ fn add_aux_pow_inner( Err(anyhow!("Failed to find a suitable nonce")) } - let (nonce, slots) = find_nonce(len)?; + let len = non_zero_len.get(); + let (nonce, slots) = find_nonce(&aux_pow, non_zero_len, len)?; // FIXME: use iterator version. let (aux_pow_id_raw, aux_pow_raw) = { @@ -1135,7 +1165,7 @@ fn add_aux_pow_inner( }; fn tree_hash(aux_pow_raw: &[[u8; 32]]) -> [u8; 32] { - todo!("https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/rpc/core_rpc_server.cpp#L2163") + todo!("https://github.com/serai-dex/serai/pull/629") } fn encode_mm_depth(aux_pow_len: usize, nonce: u32) -> u64 { @@ -1189,8 +1219,6 @@ fn add_aux_pow_inner( }) .collect::>(); - // --- END AUX POW IMPL --- - Ok(AddAuxPowResponse { base: ResponseBase::OK, blocktemplate_blob, diff --git a/binaries/cuprated/src/rpc/request/address_book.rs b/binaries/cuprated/src/rpc/request/address_book.rs index fd2c0b1a..7fbb470c 100644 --- a/binaries/cuprated/src/rpc/request/address_book.rs +++ b/binaries/cuprated/src/rpc/request/address_book.rs @@ -1,4 +1,4 @@ -//! Functions for TODO: doc enum message. +//! Functions to send [`AddressBookRequest`]s. use anyhow::{anyhow, Error}; use tower::ServiceExt; diff --git a/binaries/cuprated/src/rpc/request/blockchain.rs b/binaries/cuprated/src/rpc/request/blockchain.rs index 53799440..003708da 100644 --- a/binaries/cuprated/src/rpc/request/blockchain.rs +++ b/binaries/cuprated/src/rpc/request/blockchain.rs @@ -1,4 +1,4 @@ -//! Functions for [`BlockchainReadRequest`]. +//! Functions to send [`BlockchainReadRequest`]s. use std::{ collections::{HashMap, HashSet}, diff --git a/binaries/cuprated/src/rpc/request/blockchain_context.rs b/binaries/cuprated/src/rpc/request/blockchain_context.rs index 099c6c61..6a8c315f 100644 --- a/binaries/cuprated/src/rpc/request/blockchain_context.rs +++ b/binaries/cuprated/src/rpc/request/blockchain_context.rs @@ -1,4 +1,4 @@ -//! Functions for [`BlockChainContextRequest`] and [`BlockChainContextResponse`]. +//! Functions to send [`BlockChainContextRequest`]s. use anyhow::{anyhow, Error}; use monero_serai::block::Block; @@ -77,7 +77,7 @@ pub(crate) async fn calculate_pow( seed_hash: [u8; 32], ) -> Result<[u8; 32], Error> { let Some(height) = block.number() else { - return Err(anyhow!("block is missing height")); + return Err(anyhow!("Block is missing height")); }; let block = Box::new(block); diff --git a/binaries/cuprated/src/rpc/request/blockchain_manager.rs b/binaries/cuprated/src/rpc/request/blockchain_manager.rs index fe3f5572..cdbf5474 100644 --- a/binaries/cuprated/src/rpc/request/blockchain_manager.rs +++ b/binaries/cuprated/src/rpc/request/blockchain_manager.rs @@ -1,4 +1,4 @@ -//! Functions for [`BlockchainManagerRequest`] & [`BlockchainManagerResponse`]. +//! Functions to send [`BlockchainManagerRequest`]s. use anyhow::Error; use monero_serai::block::Block; diff --git a/binaries/cuprated/src/rpc/request/txpool.rs b/binaries/cuprated/src/rpc/request/txpool.rs index eadbb23d..78dfc53e 100644 --- a/binaries/cuprated/src/rpc/request/txpool.rs +++ b/binaries/cuprated/src/rpc/request/txpool.rs @@ -1,4 +1,4 @@ -//! Functions for [`TxpoolReadRequest`]. +//! Functions to send [`TxpoolReadRequest`]s. use std::convert::Infallible; diff --git a/rpc/interface/src/rpc_handler_dummy.rs b/rpc/interface/src/rpc_handler_dummy.rs index ac48ceca..acc3726f 100644 --- a/rpc/interface/src/rpc_handler_dummy.rs +++ b/rpc/interface/src/rpc_handler_dummy.rs @@ -85,7 +85,6 @@ impl Service for RpcHandlerDummy { Req::GetTransactionPoolBacklog(_) => { Resp::GetTransactionPoolBacklog(Default::default()) } - Req::GetOutputDistribution(_) => Resp::GetOutputDistribution(Default::default()), Req::GetMinerData(_) => Resp::GetMinerData(Default::default()), Req::PruneBlockchain(_) => Resp::PruneBlockchain(Default::default()), Req::CalcPow(_) => Resp::CalcPow(Default::default()), diff --git a/rpc/types/src/json.rs b/rpc/types/src/json.rs index d4087da3..46b9c38b 100644 --- a/rpc/types/src/json.rs +++ b/rpc/types/src/json.rs @@ -1623,7 +1623,6 @@ pub enum JsonRpcRequest { RelayTx(RelayTxRequest), SyncInfo(SyncInfoRequest), GetTransactionPoolBacklog(GetTransactionPoolBacklogRequest), - GetOutputDistribution(GetOutputDistributionRequest), GetMinerData(GetMinerDataRequest), PruneBlockchain(PruneBlockchainRequest), CalcPow(CalcPowRequest), @@ -1649,7 +1648,6 @@ impl RpcCallValue for JsonRpcRequest { Self::GetVersion(x) => x.is_restricted(), Self::GetFeeEstimate(x) => x.is_restricted(), Self::GetTransactionPoolBacklog(x) => x.is_restricted(), - Self::GetOutputDistribution(x) => x.is_restricted(), Self::GetMinerData(x) => x.is_restricted(), Self::AddAuxPow(x) => x.is_restricted(), Self::GetTxIdsLoose(x) => x.is_restricted(), @@ -1685,7 +1683,6 @@ impl RpcCallValue for JsonRpcRequest { Self::GetVersion(x) => x.is_empty(), Self::GetFeeEstimate(x) => x.is_empty(), Self::GetTransactionPoolBacklog(x) => x.is_empty(), - Self::GetOutputDistribution(x) => x.is_empty(), Self::GetMinerData(x) => x.is_empty(), Self::AddAuxPow(x) => x.is_empty(), Self::GetTxIdsLoose(x) => x.is_empty(), diff --git a/rpc/types/src/misc/address_type.rs b/rpc/types/src/misc/address_type.rs deleted file mode 100644 index ca9f8370..00000000 --- a/rpc/types/src/misc/address_type.rs +++ /dev/null @@ -1,97 +0,0 @@ -//! Types of network addresses; used in P2P. - -use cuprate_epee_encoding::Marker; - -#[cfg(feature = "serde")] -use serde::{Deserialize, Serialize}; - -#[cfg(feature = "epee")] -use cuprate_epee_encoding::{ - error, - macros::bytes::{Buf, BufMut}, - EpeeValue, -}; - -/// Used in [`crate::misc::ConnectionInfo::address_type`]. -#[doc = crate::macros::monero_definition_link!( - cc73fe71162d564ffda8e549b79a350bca53c454, - "epee/include/net/enums.h", - 39..=47 -)] -#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -#[cfg_attr(feature = "serde", serde(untagged))] -#[repr(u8)] -pub enum AddressType { - #[default] - Invalid, - Ipv4, - Ipv6, - I2p, - Tor, -} - -impl AddressType { - /// Convert [`Self`] to a [`u8`]. - /// - /// ```rust - /// use cuprate_rpc_types::misc::AddressType as A; - /// - /// assert_eq!(A::Invalid.to_u8(), 0); - /// assert_eq!(A::Ipv4.to_u8(), 1); - /// assert_eq!(A::Ipv6.to_u8(), 2); - /// assert_eq!(A::I2p.to_u8(), 3); - /// assert_eq!(A::Tor.to_u8(), 4); - /// ``` - pub const fn to_u8(self) -> u8 { - self as u8 - } - - /// Convert a [`u8`] to a [`Self`]. - /// - /// # Errors - /// This returns [`None`] if `u > 4`. - /// - /// ```rust - /// use cuprate_rpc_types::misc::AddressType as A; - /// - /// assert_eq!(A::from_u8(0), Some(A::Invalid)); - /// assert_eq!(A::from_u8(1), Some(A::Ipv4)); - /// assert_eq!(A::from_u8(2), Some(A::Ipv6)); - /// assert_eq!(A::from_u8(3), Some(A::I2p)); - /// assert_eq!(A::from_u8(4), Some(A::Tor)); - /// assert_eq!(A::from_u8(5), None); - /// ``` - pub const fn from_u8(u: u8) -> Option { - Some(match u { - 0 => Self::Invalid, - 1 => Self::Ipv4, - 2 => Self::Ipv6, - 3 => Self::I2p, - 4 => Self::Tor, - _ => return None, - }) - } -} - -impl From for u8 { - fn from(value: AddressType) -> Self { - value.to_u8() - } -} - -#[cfg(feature = "epee")] -impl EpeeValue for AddressType { - const MARKER: Marker = u8::MARKER; - - fn read(r: &mut B, marker: &Marker) -> error::Result { - let u = u8::read(r, marker)?; - Self::from_u8(u).ok_or(error::Error::Format("u8 was greater than 4")) - } - - fn write(self, w: &mut B) -> error::Result<()> { - let u = self.to_u8(); - u8::write(u, w)?; - Ok(()) - } -} diff --git a/rpc/types/src/misc/mod.rs b/rpc/types/src/misc/mod.rs index 672d4935..e09f8477 100644 --- a/rpc/types/src/misc/mod.rs +++ b/rpc/types/src/misc/mod.rs @@ -12,7 +12,6 @@ )] //---------------------------------------------------------------------------------------------------- Mod -mod address_type; mod binary_string; mod distribution; mod key_image_spent_status; @@ -22,7 +21,6 @@ mod pool_info_extent; mod status; mod tx_entry; -pub use address_type::AddressType; pub use binary_string::BinaryString; pub use distribution::{Distribution, DistributionCompressedBinary, DistributionUncompressed}; pub use key_image_spent_status::KeyImageSpentStatus; diff --git a/types/src/address_type.rs b/types/src/address_type.rs index 743902da..b18ef501 100644 --- a/types/src/address_type.rs +++ b/types/src/address_type.rs @@ -16,7 +16,7 @@ use strum::{ /// An enumeration of address types. /// -/// Used in `cuprate_p2p` and `cuprate_types` +/// Used in `cuprate-p2p`, `cuprate-rpc-types`. /// /// Original definition: /// -