Compare commits

...

7 commits

Author SHA1 Message Date
hinto.janai
fd136b23f6
add BlockChainContextService, on_get_block_hash 2024-10-11 18:07:34 -04:00
hinto.janai
2522bb8836
binaries/cuprated/src/rpc/request: pub(super) -> pub(crate) 2024-10-11 18:06:31 -04:00
hinto.janai
ac6360a4f3
Merge branch 'main' into json 2024-10-11 17:42:41 -04:00
hinto.janai
e57c887d15
Merge branch 'hf' into json 2024-10-11 17:42:10 -04:00
hinto.janai
cec746bdde
review fixes 2024-10-11 17:15:10 -04:00
hinto-janai
d43f12ea3f
rpc-types: fix HardForkInfoRequest (#310)
Some checks are pending
CI / fmt (push) Waiting to run
CI / typo (push) Waiting to run
CI / ci (macos-latest, stable, bash) (push) Waiting to run
CI / ci (ubuntu-latest, stable, bash) (push) Waiting to run
CI / ci (windows-latest, stable-x86_64-pc-windows-gnu, msys2 {0}) (push) Waiting to run
Doc / build (push) Waiting to run
Doc / deploy (push) Blocked by required conditions
* apply diffs

* fix tests
2024-10-11 18:51:16 +01:00
hinto.janai
c590bbb8d7
apply diffs 2024-10-10 20:39:44 -04:00
8 changed files with 54 additions and 63 deletions

View file

@ -3,6 +3,7 @@
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use anyhow::Error; use anyhow::Error;
use cuprate_consensus::BlockChainContextService;
use futures::future::BoxFuture; use futures::future::BoxFuture;
use monero_serai::block::Block; use monero_serai::block::Block;
use tower::Service; use tower::Service;
@ -102,6 +103,9 @@ pub struct CupratedRpcHandler {
/// Read handle to the blockchain database. /// Read handle to the blockchain database.
pub blockchain_read: BlockchainReadHandle, pub blockchain_read: BlockchainReadHandle,
/// Handle to the blockchain context service.
pub blockchain_context: BlockChainContextService,
/// Handle to the blockchain manager. /// Handle to the blockchain manager.
pub blockchain_manager: BlockchainManagerHandle, pub blockchain_manager: BlockchainManagerHandle,
@ -117,6 +121,7 @@ impl CupratedRpcHandler {
pub const fn new( pub const fn new(
restricted: bool, restricted: bool,
blockchain_read: BlockchainReadHandle, blockchain_read: BlockchainReadHandle,
blockchain_context: BlockChainContextService,
blockchain_manager: BlockchainManagerHandle, blockchain_manager: BlockchainManagerHandle,
txpool_read: TxpoolReadHandle, txpool_read: TxpoolReadHandle,
txpool_manager: std::convert::Infallible, txpool_manager: std::convert::Infallible,
@ -124,6 +129,7 @@ impl CupratedRpcHandler {
Self { Self {
restricted, restricted,
blockchain_read, blockchain_read,
blockchain_context,
blockchain_manager, blockchain_manager,
txpool_read, txpool_read,
txpool_manager, txpool_manager,

View file

@ -38,7 +38,11 @@ use cuprate_rpc_types::{
CORE_RPC_VERSION, CORE_RPC_VERSION,
}; };
use crate::rpc::{helper, request::blockchain, CupratedRpcHandler}; use crate::rpc::{
helper,
request::{blockchain, blockchain_context, blockchain_manager},
CupratedRpcHandler,
};
/// Map a [`JsonRpcRequest`] to the function that will lead to a [`JsonRpcResponse`]. /// Map a [`JsonRpcRequest`] to the function that will lead to a [`JsonRpcResponse`].
pub(super) async fn map_request( pub(super) async fn map_request(
@ -115,7 +119,8 @@ async fn on_get_block_hash(
request: OnGetBlockHashRequest, request: OnGetBlockHashRequest,
) -> Result<OnGetBlockHashResponse, Error> { ) -> Result<OnGetBlockHashResponse, Error> {
let [height] = request.block_height; let [height] = request.block_height;
let hash = blockchain::block_hash(&mut state.blockchain_read, height, todo!()).await?; let hash = blockchain::block_hash(&mut state.blockchain_read, height, todo!("access to chain"))
.await?;
let block_hash = hex::encode(hash); let block_hash = hex::encode(hash);
Ok(OnGetBlockHashResponse { block_hash }) Ok(OnGetBlockHashResponse { block_hash })
@ -126,21 +131,14 @@ async fn submit_block(
mut state: CupratedRpcHandler, mut state: CupratedRpcHandler,
request: SubmitBlockRequest, request: SubmitBlockRequest,
) -> Result<SubmitBlockResponse, Error> { ) -> Result<SubmitBlockResponse, Error> {
// Parse hex into block.
let [blob] = request.block_blob; let [blob] = request.block_blob;
let limit = todo!(); //blockchain::cumulative_block_weight_limit(&mut state.blockchain_read).await?;
// if blob.len() > limit + BLOCK_SIZE_SANITY_LEEWAY {
// return Err(anyhow!("Block size is too big, rejecting block"));
// }
let bytes = hex::decode(blob)?; let bytes = hex::decode(blob)?;
let block = Block::read(&mut bytes.as_slice())?; let block = Block::read(&mut bytes.as_slice())?;
let block_id = hex::encode(block.hash());
// <https://github.com/monero-project/monero/blob/master/src/cryptonote_core/cryptonote_core.cpp#L1540> // Attempt to relay the block.
let block_id = todo!("submit block to DB"); blockchain_manager::relay_block(&mut state.blockchain_manager, block).await?;
todo!("relay to P2P");
todo!("send to txpool");
Ok(SubmitBlockResponse { Ok(SubmitBlockResponse {
base: ResponseBase::ok(), base: ResponseBase::ok(),
@ -383,7 +381,7 @@ async fn hard_fork_info(
Ok(HardForkInfoResponse { Ok(HardForkInfoResponse {
base: AccessResponseBase::ok(), base: AccessResponseBase::ok(),
earliest_height: todo!(), earliest_height: todo!(),
enabled: hard_fork.is_current(), enabled: todo!("hard_fork.is_latest() is not always correct"),
state: todo!(), state: todo!(),
threshold: todo!(), threshold: todo!(),
version: hard_fork.as_u8(), version: hard_fork.as_u8(),

View file

@ -12,7 +12,7 @@ use cuprate_p2p_core::{
}; };
/// [`AddressBookRequest::PeerlistSize`] /// [`AddressBookRequest::PeerlistSize`]
pub(super) async fn peerlist_size<Z: NetworkZone>( pub(crate) async fn peerlist_size<Z: NetworkZone>(
address_book: &mut impl AddressBook<Z>, address_book: &mut impl AddressBook<Z>,
) -> Result<(u64, u64), Error> { ) -> Result<(u64, u64), Error> {
let AddressBookResponse::PeerlistSize { white, grey } = address_book let AddressBookResponse::PeerlistSize { white, grey } = address_book
@ -30,7 +30,7 @@ pub(super) async fn peerlist_size<Z: NetworkZone>(
} }
/// [`AddressBookRequest::ConnectionCount`] /// [`AddressBookRequest::ConnectionCount`]
pub(super) async fn connection_count<Z: NetworkZone>( pub(crate) async fn connection_count<Z: NetworkZone>(
address_book: &mut impl AddressBook<Z>, address_book: &mut impl AddressBook<Z>,
) -> Result<(u64, u64), Error> { ) -> Result<(u64, u64), Error> {
let AddressBookResponse::ConnectionCount { incoming, outgoing } = address_book let AddressBookResponse::ConnectionCount { incoming, outgoing } = address_book
@ -48,7 +48,7 @@ pub(super) async fn connection_count<Z: NetworkZone>(
} }
/// [`AddressBookRequest::SetBan`] /// [`AddressBookRequest::SetBan`]
pub(super) async fn set_ban<Z: NetworkZone>( pub(crate) async fn set_ban<Z: NetworkZone>(
address_book: &mut impl AddressBook<Z>, address_book: &mut impl AddressBook<Z>,
peer: cuprate_p2p_core::ban::SetBan<Z::Addr>, peer: cuprate_p2p_core::ban::SetBan<Z::Addr>,
) -> Result<(), Error> { ) -> Result<(), Error> {
@ -67,7 +67,7 @@ pub(super) async fn set_ban<Z: NetworkZone>(
} }
/// [`AddressBookRequest::GetBan`] /// [`AddressBookRequest::GetBan`]
pub(super) async fn get_ban<Z: NetworkZone>( pub(crate) async fn get_ban<Z: NetworkZone>(
address_book: &mut impl AddressBook<Z>, address_book: &mut impl AddressBook<Z>,
peer: Z::Addr, peer: Z::Addr,
) -> Result<Option<std::time::Instant>, Error> { ) -> Result<Option<std::time::Instant>, Error> {
@ -86,7 +86,7 @@ pub(super) async fn get_ban<Z: NetworkZone>(
} }
/// [`AddressBookRequest::GetBans`] /// [`AddressBookRequest::GetBans`]
pub(super) async fn get_bans<Z: NetworkZone>( pub(crate) async fn get_bans<Z: NetworkZone>(
address_book: &mut impl AddressBook<Z>, address_book: &mut impl AddressBook<Z>,
) -> Result<(), Error> { ) -> Result<(), Error> {
let AddressBookResponse::GetBans(bans) = address_book let AddressBookResponse::GetBans(bans) = address_book

View file

@ -12,9 +12,8 @@ use cuprate_consensus::context::{
use cuprate_types::{FeeEstimate, HardFork, HardForkInfo}; use cuprate_types::{FeeEstimate, HardFork, HardForkInfo};
/// [`BlockChainContextRequest::Context`]. /// [`BlockChainContextRequest::Context`].
pub(super) async fn context( pub(crate) async fn context(
service: &mut BlockChainContextService, service: &mut BlockChainContextService,
height: u64,
) -> Result<BlockChainContext, Error> { ) -> Result<BlockChainContext, Error> {
let BlockChainContextResponse::Context(context) = service let BlockChainContextResponse::Context(context) = service
.ready() .ready()
@ -31,7 +30,7 @@ pub(super) async fn context(
} }
/// [`BlockChainContextRequest::HardForkInfo`]. /// [`BlockChainContextRequest::HardForkInfo`].
pub(super) async fn hard_fork_info( pub(crate) async fn hard_fork_info(
service: &mut BlockChainContextService, service: &mut BlockChainContextService,
hard_fork: HardFork, hard_fork: HardFork,
) -> Result<HardForkInfo, Error> { ) -> Result<HardForkInfo, Error> {
@ -50,7 +49,7 @@ pub(super) async fn hard_fork_info(
} }
/// [`BlockChainContextRequest::FeeEstimate`]. /// [`BlockChainContextRequest::FeeEstimate`].
pub(super) async fn fee_estimate( pub(crate) async fn fee_estimate(
service: &mut BlockChainContextService, service: &mut BlockChainContextService,
grace_blocks: u64, grace_blocks: u64,
) -> Result<FeeEstimate, Error> { ) -> Result<FeeEstimate, Error> {

View file

@ -11,7 +11,7 @@ use crate::rpc::handler::{
}; };
/// [`BlockchainManagerRequest::PopBlocks`] /// [`BlockchainManagerRequest::PopBlocks`]
pub(super) async fn pop_blocks( pub(crate) async fn pop_blocks(
blockchain_manager: &mut BlockchainManagerHandle, blockchain_manager: &mut BlockchainManagerHandle,
amount: u64, amount: u64,
) -> Result<u64, Error> { ) -> Result<u64, Error> {
@ -30,7 +30,7 @@ pub(super) async fn pop_blocks(
} }
/// [`BlockchainManagerRequest::Prune`] /// [`BlockchainManagerRequest::Prune`]
pub(super) async fn prune(blockchain_manager: &mut BlockchainManagerHandle) -> Result<(), Error> { pub(crate) async fn prune(blockchain_manager: &mut BlockchainManagerHandle) -> Result<(), Error> {
let BlockchainManagerResponse::Ok = blockchain_manager let BlockchainManagerResponse::Ok = blockchain_manager
.ready() .ready()
.await? .await?
@ -44,7 +44,7 @@ pub(super) async fn prune(blockchain_manager: &mut BlockchainManagerHandle) -> R
} }
/// [`BlockchainManagerRequest::Pruned`] /// [`BlockchainManagerRequest::Pruned`]
pub(super) async fn pruned( pub(crate) async fn pruned(
blockchain_manager: &mut BlockchainManagerHandle, blockchain_manager: &mut BlockchainManagerHandle,
) -> Result<bool, Error> { ) -> Result<bool, Error> {
let BlockchainManagerResponse::Pruned(pruned) = blockchain_manager let BlockchainManagerResponse::Pruned(pruned) = blockchain_manager
@ -60,7 +60,7 @@ pub(super) async fn pruned(
} }
/// [`BlockchainManagerRequest::RelayBlock`] /// [`BlockchainManagerRequest::RelayBlock`]
pub(super) async fn relay_block( pub(crate) async fn relay_block(
blockchain_manager: &mut BlockchainManagerHandle, blockchain_manager: &mut BlockchainManagerHandle,
block: Block, block: Block,
) -> Result<(), Error> { ) -> Result<(), Error> {
@ -77,7 +77,7 @@ pub(super) async fn relay_block(
} }
/// [`BlockchainManagerRequest::Syncing`] /// [`BlockchainManagerRequest::Syncing`]
pub(super) async fn syncing( pub(crate) async fn syncing(
blockchain_manager: &mut BlockchainManagerHandle, blockchain_manager: &mut BlockchainManagerHandle,
) -> Result<bool, Error> { ) -> Result<bool, Error> {
let BlockchainManagerResponse::Syncing(syncing) = blockchain_manager let BlockchainManagerResponse::Syncing(syncing) = blockchain_manager
@ -93,7 +93,7 @@ pub(super) async fn syncing(
} }
/// [`BlockchainManagerRequest::Synced`] /// [`BlockchainManagerRequest::Synced`]
pub(super) async fn synced( pub(crate) async fn synced(
blockchain_manager: &mut BlockchainManagerHandle, blockchain_manager: &mut BlockchainManagerHandle,
) -> Result<bool, Error> { ) -> Result<bool, Error> {
let BlockchainManagerResponse::Synced(syncing) = blockchain_manager let BlockchainManagerResponse::Synced(syncing) = blockchain_manager
@ -109,7 +109,7 @@ pub(super) async fn synced(
} }
/// [`BlockchainManagerRequest::Target`] /// [`BlockchainManagerRequest::Target`]
pub(super) async fn target( pub(crate) async fn target(
blockchain_manager: &mut BlockchainManagerHandle, blockchain_manager: &mut BlockchainManagerHandle,
) -> Result<std::time::Duration, Error> { ) -> Result<std::time::Duration, Error> {
let BlockchainManagerResponse::Target(target) = blockchain_manager let BlockchainManagerResponse::Target(target) = blockchain_manager
@ -125,7 +125,7 @@ pub(super) async fn target(
} }
/// [`BlockchainManagerRequest::TargetHeight`] /// [`BlockchainManagerRequest::TargetHeight`]
pub(super) async fn target_height( pub(crate) async fn target_height(
blockchain_manager: &mut BlockchainManagerHandle, blockchain_manager: &mut BlockchainManagerHandle,
) -> Result<u64, Error> { ) -> Result<u64, Error> {
let BlockchainManagerResponse::TargetHeight { height } = blockchain_manager let BlockchainManagerResponse::TargetHeight { height } = blockchain_manager

View file

@ -15,7 +15,7 @@ use cuprate_txpool::{
}; };
/// [`TxpoolReadRequest::Backlog`] /// [`TxpoolReadRequest::Backlog`]
pub(super) async fn backlog(txpool_read: &mut TxpoolReadHandle) -> Result<Vec<TxEntry>, Error> { pub(crate) async fn backlog(txpool_read: &mut TxpoolReadHandle) -> Result<Vec<TxEntry>, Error> {
let TxpoolReadResponse::Backlog(tx_entries) = txpool_read let TxpoolReadResponse::Backlog(tx_entries) = txpool_read
.ready() .ready()
.await .await
@ -31,7 +31,7 @@ pub(super) async fn backlog(txpool_read: &mut TxpoolReadHandle) -> Result<Vec<Tx
} }
/// [`TxpoolReadRequest::Size`] /// [`TxpoolReadRequest::Size`]
pub(super) async fn size(txpool_read: &mut TxpoolReadHandle) -> Result<u64, Error> { pub(crate) async fn size(txpool_read: &mut TxpoolReadHandle) -> Result<u64, Error> {
let TxpoolReadResponse::Size(size) = txpool_read let TxpoolReadResponse::Size(size) = txpool_read
.ready() .ready()
.await .await
@ -48,7 +48,7 @@ pub(super) async fn size(txpool_read: &mut TxpoolReadHandle) -> Result<u64, Erro
/// TODO /// TODO
#[expect(clippy::needless_pass_by_ref_mut, reason = "TODO: remove after impl")] #[expect(clippy::needless_pass_by_ref_mut, reason = "TODO: remove after impl")]
pub(super) async fn flush( pub(crate) async fn flush(
txpool_read: &mut TxpoolReadHandle, txpool_read: &mut TxpoolReadHandle,
tx_hashes: Vec<[u8; 32]>, tx_hashes: Vec<[u8; 32]>,
) -> Result<(), Error> { ) -> Result<(), Error> {

View file

@ -820,7 +820,7 @@ define_request_and_response! {
HardForkInfo, HardForkInfo,
#[doc = serde_doc_test!( #[doc = serde_doc_test!(
HARD_FORK_INFO => HardForkInfo { HARD_FORK_INFO_REQUEST => HardForkInfoRequest {
version: 16, version: 16,
} }
)] )]
@ -836,9 +836,9 @@ define_request_and_response! {
enabled: true, enabled: true,
state: 0, state: 0,
threshold: 0, threshold: 0,
version: 3, version: 16,
votes: 10080, votes: 10080,
voting: 3, voting: 16,
window: 10080 window: 10080
} }
)] )]

View file

@ -73,13 +73,13 @@ pub enum HardFork {
} }
impl HardFork { impl HardFork {
/// The current [`HardFork`]. /// The latest [`HardFork`].
/// ///
/// ```rust /// ```rust
/// # use cuprate_types::HardFork; /// # use cuprate_types::HardFork;
/// assert_eq!(HardFork::CURRENT, HardFork::V16); /// assert_eq!(HardFork::LATEST, HardFork::V16);
/// ``` /// ```
pub const CURRENT: Self = Self::VARIANTS[Self::COUNT - 1]; pub const LATEST: Self = Self::VARIANTS[Self::COUNT - 1];
/// Returns the hard-fork for a blocks [`BlockHeader::hardfork_version`] field. /// Returns the hard-fork for a blocks [`BlockHeader::hardfork_version`] field.
/// ///
@ -101,21 +101,9 @@ impl HardFork {
/// ``` /// ```
#[inline] #[inline]
pub const fn from_version(version: u8) -> Result<Self, HardForkError> { pub const fn from_version(version: u8) -> Result<Self, HardForkError> {
#[expect( match Self::from_repr(version) {
clippy::cast_possible_truncation, Some(this) => Ok(this),
reason = "we check that `HardFork::COUNT` fits into a `u8`." None => Err(HardForkError::HardForkUnknown),
)]
const COUNT_AS_U8: u8 = {
const COUNT: usize = HardFork::COUNT;
assert!(COUNT <= u8::MAX as usize);
COUNT as u8
};
if version == 0 || version > COUNT_AS_U8 {
Err(HardForkError::HardForkUnknown)
} else {
// INVARIANT: we've proved above that `version` is in a valid range.
Ok(Self::VARIANTS[(version - 1) as usize])
} }
} }
@ -128,7 +116,7 @@ impl HardFork {
/// # use strum::VariantArray; /// # use strum::VariantArray;
/// // 0 is interpreted as 1. /// // 0 is interpreted as 1.
/// assert_eq!(HardFork::from_vote(0), HardFork::V1); /// assert_eq!(HardFork::from_vote(0), HardFork::V1);
/// // Unknown defaults to `CURRENT`. /// // Unknown defaults to `LATEST`.
/// assert_eq!(HardFork::from_vote(17), HardFork::V16); /// assert_eq!(HardFork::from_vote(17), HardFork::V16);
/// ///
/// for (vote, hf) in HardFork::VARIANTS.iter().enumerate() { /// for (vote, hf) in HardFork::VARIANTS.iter().enumerate() {
@ -143,7 +131,7 @@ impl HardFork {
Self::V1 Self::V1
} else { } else {
// This must default to the latest hard-fork! // This must default to the latest hard-fork!
Self::from_version(vote).unwrap_or(Self::CURRENT) Self::from_version(vote).unwrap_or(Self::LATEST)
} }
} }
@ -188,21 +176,21 @@ impl HardFork {
} }
} }
/// Returns `true` if `self` is [`Self::CURRENT`]. /// Returns `true` if `self` is [`Self::LATEST`].
/// ///
/// ```rust /// ```rust
/// # use cuprate_types::HardFork; /// # use cuprate_types::HardFork;
/// # use strum::VariantArray; /// # use strum::VariantArray;
/// ///
/// for hf in HardFork::VARIANTS.iter() { /// for hf in HardFork::VARIANTS.iter() {
/// if *hf == HardFork::CURRENT { /// if *hf == HardFork::LATEST {
/// assert!(hf.is_current()); /// assert!(hf.is_latest());
/// } else { /// } else {
/// assert!(!hf.is_current()); /// assert!(!hf.is_latest());
/// } /// }
/// } /// }
/// ``` /// ```
pub const fn is_current(self) -> bool { pub const fn is_latest(self) -> bool {
matches!(self, Self::CURRENT) matches!(self, Self::LATEST)
} }
} }