review fixes

This commit is contained in:
hinto.janai 2024-11-26 19:23:33 -05:00
parent de7abfc3f0
commit 1ffa86c5ae
No known key found for this signature in database
GPG key ID: D47CE05FA175A499
12 changed files with 68 additions and 143 deletions

View file

@ -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}",
));
}

View file

@ -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:
//! <https://github.com/Cuprate/cuprate/pull/308>
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<AddAuxPowResponse, Error> {
if request.aux_pow.is_empty() {
let Some(non_zero_len) = NonZero::<usize>::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:
// <https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/rpc/core_rpc_server.cpp#L2110-L2206>
let len = aux_pow.len();
// TODO: why is this here? it does nothing:
// <https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/rpc/core_rpc_server.cpp#L2110-L2112>
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<usize>,
aux_pow_len: usize,
) -> Result<(u32, Box<[u32]>), Error> {
/// <https://github.com/monero-project/monero/blob/893916ad091a92e765ce3241b94e706ad012b62a/src/cryptonote_basic/merge_mining.cpp#L48>
fn get_aux_slot(id: &[u8; 32], nonce: u32, n_aux_chains: NonZero<u32>) -> u32 {
const HASH_SIZE: usize = 32;
let mut buf = [0; HASH_SIZE + size_of::<u32>() + 1];
buf[..HASH_SIZE].copy_from_slice(id);
let v: [u8; 4] = nonce.to_le_bytes();
buf[HASH_SIZE..HASH_SIZE + size_of::<u32>()].copy_from_slice(&v);
const HASH_KEY_MM_SLOT: u8 = b'm';
buf[HASH_SIZE + size_of::<u32>()] = 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::<Vec<AuxPow>>();
// --- END AUX POW IMPL ---
Ok(AddAuxPowResponse {
base: ResponseBase::OK,
blocktemplate_blob,

View file

@ -1,4 +1,4 @@
//! Functions for TODO: doc enum message.
//! Functions to send [`AddressBookRequest`]s.
use anyhow::{anyhow, Error};
use tower::ServiceExt;

View file

@ -1,4 +1,4 @@
//! Functions for [`BlockchainReadRequest`].
//! Functions to send [`BlockchainReadRequest`]s.
use std::{
collections::{HashMap, HashSet},

View file

@ -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);

View file

@ -1,4 +1,4 @@
//! Functions for [`BlockchainManagerRequest`] & [`BlockchainManagerResponse`].
//! Functions to send [`BlockchainManagerRequest`]s.
use anyhow::Error;
use monero_serai::block::Block;

View file

@ -1,4 +1,4 @@
//! Functions for [`TxpoolReadRequest`].
//! Functions to send [`TxpoolReadRequest`]s.
use std::convert::Infallible;

View file

@ -85,7 +85,6 @@ impl Service<JsonRpcRequest> 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()),

View file

@ -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(),

View file

@ -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<Self> {
Some(match u {
0 => Self::Invalid,
1 => Self::Ipv4,
2 => Self::Ipv6,
3 => Self::I2p,
4 => Self::Tor,
_ => return None,
})
}
}
impl From<AddressType> for u8 {
fn from(value: AddressType) -> Self {
value.to_u8()
}
}
#[cfg(feature = "epee")]
impl EpeeValue for AddressType {
const MARKER: Marker = u8::MARKER;
fn read<B: Buf>(r: &mut B, marker: &Marker) -> error::Result<Self> {
let u = u8::read(r, marker)?;
Self::from_u8(u).ok_or(error::Error::Format("u8 was greater than 4"))
}
fn write<B: BufMut>(self, w: &mut B) -> error::Result<()> {
let u = self.to_u8();
u8::write(u, w)?;
Ok(())
}
}

View file

@ -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;

View file

@ -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:
/// - <https://github.com/monero-project/monero/blob/cc73fe71162d564ffda8e549b79a350bca53c454/src/epee/include/net/enums.h/#L49>