Compare commits

...

2 commits

Author SHA1 Message Date
hinto.janai
dfbdec3157
add blockchain_context msgs 2024-09-24 18:27:46 -04:00
hinto.janai
e8de295b57
add txpool msgs 2024-09-24 18:02:39 -04:00
13 changed files with 350 additions and 142 deletions

View file

@ -12,7 +12,8 @@
//! the [`blockchain`] modules contains methods for the
//! blockchain database [`tower::Service`] API.
mod address_book;
mod blockchain;
mod blockchain_context;
mod blockchain_manager;
mod p2p;
mod txpool;

View file

@ -0,0 +1,120 @@
//! Functions for TODO: doc enum message.
use std::{
collections::{HashMap, HashSet},
convert::Infallible,
sync::Arc,
};
use anyhow::{anyhow, Error};
use futures::StreamExt;
use monero_serai::block::Block;
use tower::{Service, ServiceExt};
use cuprate_helper::{
cast::{u64_to_usize, usize_to_u64},
map::split_u128_into_low_high_bits,
};
use cuprate_p2p_core::{
client::handshaker::builder::DummyAddressBook,
services::{AddressBookRequest, AddressBookResponse},
AddressBook, ClearNet, NetworkZone,
};
use cuprate_types::{
blockchain::{BlockchainReadRequest, BlockchainWriteRequest},
Chain, ExtendedBlockHeader, HardFork, OutputOnChain, VerifiedBlockInformation,
};
use crate::rpc::{CupratedRpcHandler, CupratedRpcHandlerState};
/// [`AddressBookRequest::PeerlistSize`]
pub(super) async fn peerlist_size<Z: NetworkZone>(
address_book: &mut impl AddressBook<Z>,
) -> Result<(u64, u64), Error> {
let AddressBookResponse::PeerlistSize { white, grey } = address_book
.ready()
.await
.expect("TODO")
.call(AddressBookRequest::PeerlistSize)
.await
.expect("TODO")
else {
unreachable!();
};
Ok((usize_to_u64(white), usize_to_u64(grey)))
}
/// [`AddressBookRequest::ConnectionCount`]
pub(super) async fn connection_count<Z: NetworkZone>(
address_book: &mut impl AddressBook<Z>,
) -> Result<(u64, u64), Error> {
let AddressBookResponse::ConnectionCount { incoming, outgoing } = address_book
.ready()
.await
.expect("TODO")
.call(AddressBookRequest::ConnectionCount)
.await
.expect("TODO")
else {
unreachable!();
};
Ok((usize_to_u64(incoming), usize_to_u64(outgoing)))
}
/// [`AddressBookRequest::SetBan`]
pub(super) async fn set_ban<Z: NetworkZone>(
address_book: &mut impl AddressBook<Z>,
peer: Infallible,
) -> Result<(), Error> {
let AddressBookResponse::Ok = address_book
.ready()
.await
.expect("TODO")
.call(AddressBookRequest::SetBan(peer))
.await
.expect("TODO")
else {
unreachable!();
};
Ok(())
}
/// [`AddressBookRequest::GetBan`]
pub(super) async fn get_ban<Z: NetworkZone>(
address_book: &mut impl AddressBook<Z>,
peer: Infallible,
) -> Result<(), Error> {
let AddressBookResponse::GetBan(ban) = address_book
.ready()
.await
.expect("TODO")
.call(AddressBookRequest::GetBan(peer))
.await
.expect("TODO")
else {
unreachable!();
};
Ok(())
}
/// [`AddressBookRequest::GetBans`]
pub(super) async fn get_bans<Z: NetworkZone>(
address_book: &mut impl AddressBook<Z>,
) -> Result<(), Error> {
let AddressBookResponse::GetBans(bans) = address_book
.ready()
.await
.expect("TODO")
.call(AddressBookRequest::GetBans)
.await
.expect("TODO")
else {
unreachable!();
};
Ok(todo!())
}

View file

@ -0,0 +1,86 @@
//! Functions for [`BlockChainContextRequest`] and [`BlockChainContextResponse`].
use std::{
collections::{HashMap, HashSet},
convert::Infallible,
ops::Range,
sync::Arc,
};
use anyhow::{anyhow, Error};
use futures::StreamExt;
use monero_serai::block::Block;
use randomx_rs::RandomXVM;
use tower::{Service, ServiceExt};
use cuprate_consensus::context::{
BlockChainContext, BlockChainContextRequest, BlockChainContextResponse,
BlockChainContextService,
};
use cuprate_helper::{
cast::{u64_to_usize, usize_to_u64},
map::split_u128_into_low_high_bits,
};
use cuprate_types::{
blockchain::{BlockchainReadRequest, BlockchainResponse, BlockchainWriteRequest},
Chain, ExtendedBlockHeader, HardFork, OutputOnChain, VerifiedBlockInformation,
};
use crate::rpc::CupratedRpcHandlerState;
/// [`BlockChainContextRequest::Context`].
pub(super) async fn context(
service: &mut BlockChainContextService,
height: u64,
) -> Result<BlockChainContext, Error> {
let BlockChainContextResponse::Context(context) = service
.ready()
.await
.expect("TODO")
.call(BlockChainContextRequest::Context)
.await
.expect("TODO")
else {
unreachable!();
};
Ok(context)
}
/// [`BlockChainContextRequest::HardForkInfo`].
pub(super) async fn hard_fork_info(
service: &mut BlockChainContextService,
hard_fork: HardFork,
) -> Result<Infallible, Error> {
let BlockChainContextResponse::HardForkInfo(hf_info) = service
.ready()
.await
.expect("TODO")
.call(BlockChainContextRequest::HardForkInfo(hard_fork))
.await
.expect("TODO")
else {
unreachable!();
};
Ok(hf_info)
}
/// [`BlockChainContextRequest::FeeEstimate`].
pub(super) async fn fee_estimate(
service: &mut BlockChainContextService,
grace_blocks: u64,
) -> Result<Infallible, Error> {
let BlockChainContextResponse::FeeEstimate(hf_info) = service
.ready()
.await
.expect("TODO")
.call(BlockChainContextRequest::FeeEstimate { grace_blocks })
.await
.expect("TODO")
else {
unreachable!();
};
Ok(hf_info)
}

View file

@ -1,119 +0,0 @@
//! Functions for TODO: doc enum message.
use std::{
collections::{HashMap, HashSet},
convert::Infallible,
sync::Arc,
};
use anyhow::{anyhow, Error};
use futures::StreamExt;
use monero_serai::block::Block;
use tower::{Service, ServiceExt};
use cuprate_helper::{
cast::{u64_to_usize, usize_to_u64},
map::split_u128_into_low_high_bits,
};
use cuprate_p2p_core::{
client::handshaker::builder::DummyAddressBook,
services::{AddressBookRequest, AddressBookResponse},
AddressBook, ClearNet,
};
use cuprate_types::{
blockchain::{BlockchainReadRequest, BlockchainWriteRequest},
Chain, ExtendedBlockHeader, HardFork, OutputOnChain, VerifiedBlockInformation,
};
use crate::rpc::{CupratedRpcHandler, CupratedRpcHandlerState};
#[expect(clippy::needless_pass_by_ref_mut, reason = "TODO: remove after impl")]
impl CupratedRpcHandlerState {
/// [`AddressBookRequest::PeerlistSize`]
pub(super) async fn peerlist_size(&mut self) -> Result<(u64, u64), Error> {
let AddressBookResponse::<ClearNet>::PeerlistSize { white, grey } =
<DummyAddressBook as tower::ServiceExt<AddressBookRequest<ClearNet>>>::ready(
&mut DummyAddressBook,
)
.await
.expect("TODO")
.call(AddressBookRequest::PeerlistSize)
.await
.expect("TODO")
else {
unreachable!();
};
Ok((usize_to_u64(white), usize_to_u64(grey)))
}
/// [`AddressBookRequest::ConnectionCount`]
pub(super) async fn connection_count(&mut self) -> Result<(u64, u64), Error> {
let AddressBookResponse::<ClearNet>::ConnectionCount { incoming, outgoing } =
<DummyAddressBook as tower::ServiceExt<AddressBookRequest<ClearNet>>>::ready(
&mut DummyAddressBook,
)
.await
.expect("TODO")
.call(AddressBookRequest::ConnectionCount)
.await
.expect("TODO")
else {
unreachable!();
};
Ok((usize_to_u64(incoming), usize_to_u64(outgoing)))
}
/// [`AddressBookRequest::SetBan`]
pub(super) async fn set_ban(&mut self, peer: Infallible) -> Result<(), Error> {
let AddressBookResponse::<ClearNet>::Ok = <DummyAddressBook as tower::ServiceExt<
AddressBookRequest<ClearNet>,
>>::ready(&mut DummyAddressBook)
.await
.expect("TODO")
.call(AddressBookRequest::SetBan(peer))
.await
.expect("TODO") else {
unreachable!();
};
Ok(())
}
/// [`AddressBookRequest::GetBan`]
pub(super) async fn get_ban(&mut self, peer: Infallible) -> Result<(), Error> {
let AddressBookResponse::<ClearNet>::GetBan(ban) =
<DummyAddressBook as tower::ServiceExt<AddressBookRequest<ClearNet>>>::ready(
&mut DummyAddressBook,
)
.await
.expect("TODO")
.call(AddressBookRequest::GetBan(peer))
.await
.expect("TODO")
else {
unreachable!();
};
Ok(())
}
/// [`AddressBookRequest::GetBans`]
pub(super) async fn get_bans(&mut self) -> Result<(), Error> {
let AddressBookResponse::<ClearNet>::GetBans(bans) =
<DummyAddressBook as tower::ServiceExt<AddressBookRequest<ClearNet>>>::ready(
&mut DummyAddressBook,
)
.await
.expect("TODO")
.call(AddressBookRequest::GetBans)
.await
.expect("TODO")
else {
unreachable!();
};
Ok(todo!())
}
}

View file

@ -2,10 +2,12 @@
use std::{
collections::{HashMap, HashSet},
convert::Infallible,
sync::Arc,
};
use anyhow::{anyhow, Error};
use cuprate_database_service::DatabaseReadService;
use futures::StreamExt;
use monero_serai::block::Block;
use tower::{Service, ServiceExt};
@ -15,6 +17,10 @@ use cuprate_helper::{
cast::{u64_to_usize, usize_to_u64},
map::split_u128_into_low_high_bits,
};
use cuprate_txpool::service::{
interface::{TxpoolReadRequest, TxpoolReadResponse},
TxpoolReadHandle,
};
use cuprate_types::{
blockchain::{BlockchainReadRequest, BlockchainWriteRequest},
Chain, ExtendedBlockHeader, HardFork, OutputOnChain, VerifiedBlockInformation,
@ -22,4 +28,44 @@ use cuprate_types::{
use crate::rpc::{CupratedRpcHandler, CupratedRpcHandlerState};
impl CupratedRpcHandlerState {}
/// [`TxpoolReadRequest::Backlog`]
pub(super) async fn backlog(txpool_read: &mut TxpoolReadHandle) -> Result<Vec<Infallible>, Error> {
let TxpoolReadResponse::Backlog(backlog) = txpool_read
.ready()
.await
.expect("TODO")
.call(TxpoolReadRequest::Backlog)
.await
.expect("TODO")
else {
unreachable!();
};
Ok(backlog)
}
/// [`TxpoolReadRequest::Size`]
pub(super) async fn size(txpool_read: &mut TxpoolReadHandle) -> Result<u64, Error> {
let TxpoolReadResponse::Size(size) = txpool_read
.ready()
.await
.expect("TODO")
.call(TxpoolReadRequest::Size)
.await
.expect("TODO")
else {
unreachable!();
};
Ok(usize_to_u64(size))
}
// [`::Flush`]
#[expect(clippy::needless_pass_by_ref_mut, reason = "TODO: remove after impl")]
pub(super) async fn flush(
txpool_read: &mut TxpoolReadHandle,
tx_hashes: Vec<[u8; 32]>,
) -> Result<(), Error> {
todo!();
Ok(())
}

View file

@ -230,7 +230,7 @@ where
let BlockChainContextResponse::Context(checked_context) = context_svc
.ready()
.await?
.call(BlockChainContextRequest::GetContext)
.call(BlockChainContextRequest::Context)
.await?
else {
panic!("Context service returned wrong response!");

View file

@ -337,7 +337,7 @@ where
let BlockChainContextResponse::Context(checked_context) = context_svc
.ready()
.await?
.call(BlockChainContextRequest::GetContext)
.call(BlockChainContextRequest::Context)
.await?
else {
panic!("Context service returned wrong response!");
@ -360,7 +360,7 @@ where
let BlockChainContextResponse::RxVms(rx_vms) = context_svc
.ready()
.await?
.call(BlockChainContextRequest::GetCurrentRxVm)
.call(BlockChainContextRequest::CurrentRxVm)
.await?
else {
panic!("Blockchain context service returned wrong response!");
@ -419,7 +419,7 @@ where
context
} else {
let BlockChainContextResponse::Context(checked_context) = context_svc
.oneshot(BlockChainContextRequest::GetContext)
.oneshot(BlockChainContextRequest::Context)
.await?
else {
panic!("Context service returned wrong response!");

View file

@ -93,7 +93,7 @@ where
let BlockChainContextResponse::Context(checked_context) = context_svc
.ready()
.await?
.call(BlockChainContextRequest::GetContext)
.call(BlockChainContextRequest::Context)
.await?
else {
panic!("Context service returned wrong response!");
@ -136,7 +136,7 @@ where
let BlockChainContextResponse::RxVms(rx_vms) = context_svc
.ready()
.await?
.call(BlockChainContextRequest::GetCurrentRxVm)
.call(BlockChainContextRequest::CurrentRxVm)
.await?
else {
panic!("Blockchain context service returned wrong response!");

View file

@ -221,15 +221,18 @@ pub struct NewBlockData {
#[derive(Debug, Clone)]
pub enum BlockChainContextRequest {
/// Get the current blockchain context.
GetContext,
Context,
/// Gets the current `RandomX` VM.
GetCurrentRxVm,
CurrentRxVm,
/// Get the next difficulties for these blocks.
///
/// Inputs: a list of block timestamps and hfs
///
/// The number of difficulties returned will be one more than the number of timestamps/ hfs.
BatchGetDifficulties(Vec<(u64, HardFork)>),
/// Add a VM that has been created outside of the blockchain context service to the blockchain context.
/// This is useful when batch calculating POW as you may need to create a new VM if you batch a lot of blocks together,
/// it would be wasteful to then not give this VM to the context service to then use when it needs to init a VM with the same
@ -237,8 +240,10 @@ pub enum BlockChainContextRequest {
///
/// This should include the seed used to init this VM and the VM.
NewRXVM(([u8; 32], Arc<RandomXVm>)),
/// A request to add a new block to the cache.
Update(NewBlockData),
/// Pop blocks from the cache to the specified height.
PopBlocks {
/// The number of blocks to pop from the top of the chain.
@ -248,8 +253,10 @@ pub enum BlockChainContextRequest {
/// This will panic if the number of blocks will pop the genesis block.
numb_blocks: usize,
},
/// Clear the alt chain context caches.
ClearAltCache,
//----------------------------------------------------------------------------------------------------------- AltChainRequests
/// A request for an alt chain context cache.
///
@ -261,6 +268,7 @@ pub enum BlockChainContextRequest {
/// An internal token to prevent external crates calling this request.
_token: AltChainRequestToken,
},
/// A request for a difficulty cache of an alternative chin.
///
/// This variant is private and is not callable from outside this crate, the block verifier service will
@ -271,6 +279,7 @@ pub enum BlockChainContextRequest {
/// An internal token to prevent external crates calling this request.
_token: AltChainRequestToken,
},
/// A request for a block weight cache of an alternative chin.
///
/// This variant is private and is not callable from outside this crate, the block verifier service will
@ -281,6 +290,7 @@ pub enum BlockChainContextRequest {
/// An internal token to prevent external crates calling this request.
_token: AltChainRequestToken,
},
/// A request for a RX VM for an alternative chin.
///
/// Response variant: [`BlockChainContextResponse::AltChainRxVM`].
@ -295,6 +305,7 @@ pub enum BlockChainContextRequest {
/// An internal token to prevent external crates calling this request.
_token: AltChainRequestToken,
},
/// A request to add an alt chain context cache to the context cache.
///
/// This variant is private and is not callable from outside this crate, the block verifier service will
@ -307,25 +318,61 @@ pub enum BlockChainContextRequest {
/// An internal token to prevent external crates calling this request.
_token: AltChainRequestToken,
},
/// TODO
HardForkInfo(HardFork),
/// TODO
FeeEstimate {
/// TODO
grace_blocks: u64,
}
}
pub enum BlockChainContextResponse {
/// Blockchain context response.
/// A generic Ok response.
///
/// Response to:
/// - [`BlockChainContextRequest::NewRXVM`]
/// - [`BlockChainContextRequest::Update`]
/// - [`BlockChainContextRequest::PopBlocks`]
/// - [`BlockChainContextRequest::ClearAltCache`]
/// - [`BlockChainContextRequest::AddAltChainContextCache`]
Ok,
/// Response to [`BlockChainContextRequest::Context`]
Context(BlockChainContext),
// TODO: why does this return a `HashMap` when the request is `CurrentRxVm`?
/// Response to [`BlockChainContextRequest::CurrentRxVm`]
///
/// A map of seed height to `RandomX` VMs.
RxVms(HashMap<usize, Arc<RandomXVm>>),
/// A list of difficulties.
BatchDifficulties(Vec<u128>),
/// An alt chain context cache.
AltChainContextCache(Box<AltChainContextCache>),
/// A difficulty cache for an alt chain.
AltChainDifficultyCache(DifficultyCache),
/// A randomX VM for an alt chain.
AltChainRxVM(Arc<RandomXVm>),
/// A weight cache for an alt chain
AltChainWeightCache(BlockWeightsCache),
/// A generic Ok response.
Ok,
/// Response to [`BlockChainContextRequest::HardForkInfo`]
///
/// TODO
HardForkInfo(std::convert::Infallible /* TODO */),
/// Response to [`BlockChainContextRequest::FeeEstimate`]
///
/// TODO
FeeEstimate(std::convert::Infallible /* TODO */),
}
/// The blockchain context service.

View file

@ -153,7 +153,7 @@ impl<D: Database + Clone + Send + 'static> ContextTask<D> {
req: BlockChainContextRequest,
) -> Result<BlockChainContextResponse, tower::BoxError> {
Ok(match req {
BlockChainContextRequest::GetContext => {
BlockChainContextRequest::Context => {
tracing::debug!("Getting blockchain context");
let current_hf = self.hardfork_state.current_hardfork();
@ -183,7 +183,7 @@ impl<D: Database + Clone + Send + 'static> ContextTask<D> {
},
})
}
BlockChainContextRequest::GetCurrentRxVm => {
BlockChainContextRequest::CurrentRxVm => {
BlockChainContextResponse::RxVms(self.rx_vm_cache.get_vms().await)
}
BlockChainContextRequest::BatchGetDifficulties(blocks) => {
@ -325,6 +325,9 @@ impl<D: Database + Clone + Send + 'static> ContextTask<D> {
self.alt_chain_cache_map.add_alt_cache(prev_id, cache);
BlockChainContextResponse::Ok
}
BlockChainContextRequest::HardForkInfo(_) | BlockChainContextRequest::FeeEstimate { .. } => {
todo!()
}
})
}

View file

@ -41,7 +41,7 @@ async fn context_invalidated_on_new_block() -> Result<(), tower::BoxError> {
let BlockChainContextResponse::Context(context) = ctx_svc
.clone()
.oneshot(BlockChainContextRequest::GetContext)
.oneshot(BlockChainContextRequest::Context)
.await?
else {
panic!("Context service returned wrong response!");
@ -81,9 +81,8 @@ async fn context_height_correct() -> Result<(), tower::BoxError> {
let ctx_svc = initialize_blockchain_context(TEST_CONTEXT_CONFIG, db).await?;
let BlockChainContextResponse::Context(context) = ctx_svc
.oneshot(BlockChainContextRequest::GetContext)
.await?
let BlockChainContextResponse::Context(context) =
ctx_svc.oneshot(BlockChainContextRequest::Context).await?
else {
panic!("context service returned incorrect response!")
};

View file

@ -12,19 +12,39 @@ use crate::types::TransactionHash;
pub enum TxpoolReadRequest {
/// A request for the blob (raw bytes) of a transaction with the given hash.
TxBlob(TransactionHash),
/// A request for the [`TransactionVerificationData`] of a transaction in the tx pool.
TxVerificationData(TransactionHash),
/// TODO
Backlog,
/// TODO
Size,
}
//---------------------------------------------------------------------------------------------------- TxpoolReadResponse
/// The transaction pool [`tower::Service`] read response type.
#[expect(clippy::large_enum_variant)]
pub enum TxpoolReadResponse {
/// A response containing the raw bytes of a transaction.
/// Response to [`TxpoolReadRequest::TxBlob`].
///
/// The inner value is the raw bytes of a transaction.
// TODO: use bytes::Bytes.
TxBlob(Vec<u8>),
/// A response of [`TransactionVerificationData`].
/// Response to [`TxpoolReadRequest::TxVerificationData`].
TxVerificationData(TransactionVerificationData),
/// Response to [`TxpoolReadRequest::Backlog`].
///
/// TODO
Backlog(Vec<std::convert::Infallible>),
/// Response to [`TxpoolReadRequest::Size`].
///
/// TODO
Size(usize),
}
//---------------------------------------------------------------------------------------------------- TxpoolWriteRequest
@ -42,6 +62,7 @@ pub enum TxpoolWriteRequest {
/// [`true`] if this tx is in the stem state.
state_stem: bool,
},
/// Remove a transaction with the given hash from the pool.
///
/// Returns [`TxpoolWriteResponse::Ok`].
@ -52,9 +73,12 @@ pub enum TxpoolWriteRequest {
/// The transaction pool [`tower::Service`] write response type.
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
pub enum TxpoolWriteResponse {
/// A [`TxpoolWriteRequest::AddTransaction`] response.
/// Response to:
/// - [`TxpoolWriteRequest::RemoveTransaction`]
Ok,
/// Response to [`TxpoolWriteRequest::AddTransaction`].
///
/// If the inner value is [`Some`] the tx was not added to the pool as it double spends a tx with the given hash.
AddTransaction(Option<TransactionHash>),
Ok,
}

View file

@ -58,6 +58,7 @@ fn map_request(
match request {
TxpoolReadRequest::TxBlob(tx_hash) => tx_blob(env, &tx_hash),
TxpoolReadRequest::TxVerificationData(tx_hash) => tx_verification_data(env, &tx_hash),
TxpoolReadRequest::Backlog | TxpoolReadRequest::Size => todo!(),
}
}