bc -> blockchain

This commit is contained in:
Boog900 2024-08-05 15:57:56 +01:00
parent 072ae6f216
commit 5fd310288c
No known key found for this signature in database
GPG key ID: 42AB1287CB0041C2
19 changed files with 195 additions and 195 deletions

View file

@ -4,10 +4,10 @@ use clap::Parser;
use tower::{Service, ServiceExt};
use cuprate_blockchain::{
config::ConfigBuilder, cuprate_database::RuntimeError, service::BCReadHandle,
config::ConfigBuilder, cuprate_database::RuntimeError, service::BlockchainReadHandle,
};
use cuprate_types::{
blockchain::{BCReadRequest, BCResponse},
blockchain::{BlockchainReadRequest, BlockchainResponse},
Chain,
};
@ -16,18 +16,18 @@ use cuprate_fast_sync::{hash_of_hashes, BlockId, HashOfHashes};
const BATCH_SIZE: u64 = 512;
async fn read_batch(
handle: &mut BCReadHandle,
handle: &mut BlockchainReadHandle,
height_from: u64,
) -> Result<Vec<BlockId>, RuntimeError> {
let mut block_ids = Vec::<BlockId>::with_capacity(BATCH_SIZE as usize);
for height in height_from..(height_from + BATCH_SIZE) {
let request = BCReadRequest::BlockHash(height, Chain::Main);
let request = BlockchainReadRequest::BlockHash(height, Chain::Main);
let response_channel = handle.ready().await?.call(request);
let response = response_channel.await?;
match response {
BCResponse::BlockHash(block_id) => block_ids.push(block_id),
BlockchainResponse::BlockHash(block_id) => block_ids.push(block_id),
_ => unreachable!(),
}
}

View file

@ -4,7 +4,7 @@ use tower::ServiceExt;
use cuprate_consensus_rules::{blocks::BlockError, ConsensusError};
use cuprate_types::{
blockchain::{BCReadRequest, BCResponse},
blockchain::{BlockchainReadRequest, BlockchainResponse},
Chain, ChainId,
};
@ -100,8 +100,8 @@ impl AltChainMap {
}
// find the block with hash == prev_id.
let BCResponse::FindBlock(res) =
database.oneshot(BCReadRequest::FindBlock(prev_id)).await?
let BlockchainResponse::FindBlock(res) =
database.oneshot(BlockchainReadRequest::FindBlock(prev_id)).await?
else {
panic!("Database returned wrong response");
};
@ -130,10 +130,10 @@ pub async fn get_alt_chain_difficulty_cache<D: Database + Clone>(
mut database: D,
) -> Result<DifficultyCache, ExtendedConsensusError> {
// find the block with hash == prev_id.
let BCResponse::FindBlock(res) = database
let BlockchainResponse::FindBlock(res) = database
.ready()
.await?
.call(BCReadRequest::FindBlock(prev_id))
.call(BlockchainReadRequest::FindBlock(prev_id))
.await?
else {
panic!("Database returned wrong response");
@ -177,10 +177,10 @@ pub async fn get_alt_chain_weight_cache<D: Database + Clone>(
mut database: D,
) -> Result<BlockWeightsCache, ExtendedConsensusError> {
// find the block with hash == prev_id.
let BCResponse::FindBlock(res) = database
let BlockchainResponse::FindBlock(res) = database
.ready()
.await?
.call(BCReadRequest::FindBlock(prev_id))
.call(BlockchainReadRequest::FindBlock(prev_id))
.await?
else {
panic!("Database returned wrong response");

View file

@ -13,7 +13,7 @@ use tracing::instrument;
use cuprate_helper::num::median;
use cuprate_types::{
blockchain::{BCReadRequest, BCResponse},
blockchain::{BlockchainReadRequest, BlockchainResponse},
Chain,
};
@ -373,8 +373,8 @@ async fn get_blocks_in_pow_info<D: Database + Clone>(
) -> Result<(VecDeque<u64>, VecDeque<u128>), ExtendedConsensusError> {
tracing::info!("Getting blocks timestamps");
let BCResponse::BlockExtendedHeaderInRange(ext_header) = database
.oneshot(BCReadRequest::BlockExtendedHeaderInRange(
let BlockchainResponse::BlockExtendedHeaderInRange(ext_header) = database
.oneshot(BlockchainReadRequest::BlockExtendedHeaderInRange(
block_heights,
chain,
))

View file

@ -5,7 +5,7 @@ use tracing::instrument;
use cuprate_consensus_rules::{HFVotes, HFsInfo, HardFork};
use cuprate_types::{
blockchain::{BCReadRequest, BCResponse},
blockchain::{BlockchainReadRequest, BlockchainResponse},
Chain,
};
@ -90,10 +90,10 @@ impl HardForkState {
debug_assert_eq!(votes.total_votes(), config.window)
}
let BCResponse::BlockExtendedHeader(ext_header) = database
let BlockchainResponse::BlockExtendedHeader(ext_header) = database
.ready()
.await?
.call(BCReadRequest::BlockExtendedHeader(chain_height - 1))
.call(BlockchainReadRequest::BlockExtendedHeader(chain_height - 1))
.await?
else {
panic!("Database sent incorrect response!");
@ -214,8 +214,8 @@ async fn get_votes_in_range<D: Database>(
) -> Result<HFVotes, ExtendedConsensusError> {
let mut votes = HFVotes::new(window_size);
let BCResponse::BlockExtendedHeaderInRange(vote_list) = database
.oneshot(BCReadRequest::BlockExtendedHeaderInRange(
let BlockchainResponse::BlockExtendedHeaderInRange(vote_list) = database
.oneshot(BlockchainReadRequest::BlockExtendedHeaderInRange(
block_heights,
Chain::Main,
))

View file

@ -22,7 +22,7 @@ use cuprate_consensus_rules::{
};
use cuprate_helper::asynch::rayon_spawn_async;
use cuprate_types::{
blockchain::{BCReadRequest, BCResponse},
blockchain::{BlockchainReadRequest, BlockchainResponse},
Chain,
};
@ -138,8 +138,8 @@ impl RandomXVMCache {
) -> Result<Arc<RandomXVM>, ExtendedConsensusError> {
let seed_height = randomx_seed_height(height);
let BCResponse::BlockHash(seed_hash) = database
.oneshot(BCReadRequest::BlockHash(seed_height, chain))
let BlockchainResponse::BlockHash(seed_hash) = database
.oneshot(BlockchainReadRequest::BlockHash(seed_height, chain))
.await?
else {
panic!("Database returned wrong response!");
@ -273,9 +273,9 @@ async fn get_block_hashes<D: Database + Clone>(
for height in heights {
let db = database.clone();
fut.push_back(async move {
let BCResponse::BlockHash(hash) = db
let BlockchainResponse::BlockHash(hash) = db
.clone()
.oneshot(BCReadRequest::BlockHash(height, Chain::Main))
.oneshot(BlockchainReadRequest::BlockHash(height, Chain::Main))
.await?
else {
panic!("Database sent incorrect response!");

View file

@ -10,7 +10,7 @@ use tracing::Instrument;
use cuprate_consensus_rules::blocks::ContextToVerifyBlock;
use cuprate_types::{
blockchain::{BCReadRequest, BCResponse},
blockchain::{BlockchainReadRequest, BlockchainResponse},
Chain,
};
@ -76,19 +76,19 @@ impl<D: Database + Clone + Send + 'static> ContextTask<D> {
tracing::debug!("Initialising blockchain context");
let BCResponse::ChainHeight(chain_height, top_block_hash) = database
let BlockchainResponse::ChainHeight(chain_height, top_block_hash) = database
.ready()
.await?
.call(BCReadRequest::ChainHeight)
.call(BlockchainReadRequest::ChainHeight)
.await?
else {
panic!("Database sent incorrect response!");
};
let BCResponse::GeneratedCoins(already_generated_coins) = database
let BlockchainResponse::GeneratedCoins(already_generated_coins) = database
.ready()
.await?
.call(BCReadRequest::GeneratedCoins(chain_height - 1))
.call(BlockchainReadRequest::GeneratedCoins(chain_height - 1))
.await?
else {
panic!("Database sent incorrect response!");
@ -248,21 +248,21 @@ impl<D: Database + Clone + Send + 'static> ContextTask<D> {
self.chain_height -= numb_blocks;
let BCResponse::GeneratedCoins(already_generated_coins) = self
let BlockchainResponse::GeneratedCoins(already_generated_coins) = self
.database
.ready()
.await?
.call(BCReadRequest::GeneratedCoins(self.chain_height - 1))
.call(BlockchainReadRequest::GeneratedCoins(self.chain_height - 1))
.await?
else {
panic!("Database sent incorrect response!");
};
let BCResponse::BlockHash(top_block_hash) = self
let BlockchainResponse::BlockHash(top_block_hash) = self
.database
.ready()
.await?
.call(BCReadRequest::BlockHash(self.chain_height - 1, Chain::Main))
.call(BlockchainReadRequest::BlockHash(self.chain_height - 1, Chain::Main))
.await?
else {
panic!("Database returned incorrect response!");

View file

@ -17,7 +17,7 @@ use tracing::instrument;
use cuprate_consensus_rules::blocks::{penalty_free_zone, PENALTY_FREE_ZONE_5};
use cuprate_helper::{asynch::rayon_spawn_async, num::RollingMedian};
use cuprate_types::{
blockchain::{BCReadRequest, BCResponse},
blockchain::{BlockchainReadRequest, BlockchainResponse},
Chain,
};
@ -296,8 +296,8 @@ async fn get_blocks_weight_in_range<D: Database + Clone>(
) -> Result<Vec<usize>, ExtendedConsensusError> {
tracing::info!("getting block weights.");
let BCResponse::BlockExtendedHeaderInRange(ext_headers) = database
.oneshot(BCReadRequest::BlockExtendedHeaderInRange(range, chain))
let BlockchainResponse::BlockExtendedHeaderInRange(ext_headers) = database
.oneshot(BlockchainReadRequest::BlockExtendedHeaderInRange(range, chain))
.await?
else {
panic!("Database sent incorrect response!")
@ -318,8 +318,8 @@ async fn get_long_term_weight_in_range<D: Database + Clone>(
) -> Result<Vec<usize>, ExtendedConsensusError> {
tracing::info!("getting block long term weights.");
let BCResponse::BlockExtendedHeaderInRange(ext_headers) = database
.oneshot(BCReadRequest::BlockExtendedHeaderInRange(range, chain))
let BlockchainResponse::BlockExtendedHeaderInRange(ext_headers) = database
.oneshot(BlockchainReadRequest::BlockExtendedHeaderInRange(range, chain))
.await?
else {
panic!("Database sent incorrect response!")

View file

@ -7,8 +7,8 @@
//! - [`TxVerifierService`] Which handles transaction verification.
//!
//! This crate is generic over the database which is implemented as a [`tower::Service`]. To
//! implement a database you need to have a service which accepts [`BCReadRequest`] and responds
//! with [`BCResponse`].
//! implement a database you need to have a service which accepts [`BlockchainReadRequest`] and responds
//! with [`BlockchainResponse`].
//!
use cuprate_consensus_rules::{ConsensusError, HardFork};
@ -27,7 +27,7 @@ pub use context::{
pub use transactions::{TxVerifierService, VerifyTxRequest, VerifyTxResponse};
// re-export.
pub use cuprate_types::blockchain::{BCReadRequest, BCResponse};
pub use cuprate_types::blockchain::{BlockchainReadRequest, BlockchainResponse};
/// An Error returned from one of the consensus services.
#[derive(Debug, thiserror::Error)]
@ -83,7 +83,7 @@ use __private::Database;
pub mod __private {
use std::future::Future;
use cuprate_types::blockchain::{BCReadRequest, BCResponse};
use cuprate_types::blockchain::{BlockchainReadRequest, BlockchainResponse};
/// A type alias trait used to represent a database, so we don't have to write [`tower::Service`] bounds
/// everywhere.
@ -94,8 +94,8 @@ pub mod __private {
/// ```
pub trait Database:
tower::Service<
BCReadRequest,
Response = BCResponse,
BlockchainReadRequest,
Response =BlockchainResponse,
Error = tower::BoxError,
Future = Self::Future2,
>
@ -103,7 +103,7 @@ pub mod __private {
type Future2: Future<Output = Result<Self::Response, Self::Error>> + Send + 'static;
}
impl<T: tower::Service<BCReadRequest, Response = BCResponse, Error = tower::BoxError>>
impl<T: tower::Service<BlockchainReadRequest, Response =BlockchainResponse, Error = tower::BoxError>>
crate::Database for T
where
T::Future: Future<Output = Result<Self::Response, Self::Error>> + Send + 'static,

View file

@ -16,7 +16,7 @@ use proptest_derive::Arbitrary;
use tower::{BoxError, Service};
use cuprate_types::{
blockchain::{BCReadRequest, BCResponse},
blockchain::{BlockchainReadRequest, BlockchainResponse},
ExtendedBlockHeader,
};
@ -133,8 +133,8 @@ impl DummyDatabase {
}
}
impl Service<BCReadRequest> for DummyDatabase {
type Response = BCResponse;
impl Service<BlockchainReadRequest> for DummyDatabase {
type Response = BlockchainResponse;
type Error = BoxError;
type Future =
Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
@ -143,13 +143,13 @@ impl Service<BCReadRequest> for DummyDatabase {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: BCReadRequest) -> Self::Future {
fn call(&mut self, req: BlockchainReadRequest) -> Self::Future {
let blocks = self.blocks.clone();
let dummy_height = self.dummy_height;
async move {
Ok(match req {
BCReadRequest::BlockExtendedHeader(id) => {
BlockchainReadRequest::BlockExtendedHeader(id) => {
let mut id = usize::try_from(id).unwrap();
if let Some(dummy_height) = dummy_height {
let block_len = blocks.read().unwrap().len();
@ -157,7 +157,7 @@ impl Service<BCReadRequest> for DummyDatabase {
id -= dummy_height - block_len;
}
BCResponse::BlockExtendedHeader(
BlockchainResponse::BlockExtendedHeader(
blocks
.read()
.unwrap()
@ -167,12 +167,12 @@ impl Service<BCReadRequest> for DummyDatabase {
.ok_or("block not in database!")?,
)
}
BCReadRequest::BlockHash(id, _) => {
BlockchainReadRequest::BlockHash(id, _) => {
let mut hash = [0; 32];
hash[0..8].copy_from_slice(&id.to_le_bytes());
BCResponse::BlockHash(hash)
BlockchainResponse::BlockHash(hash)
}
BCReadRequest::BlockExtendedHeaderInRange(range, _) => {
BlockchainReadRequest::BlockExtendedHeaderInRange(range, _) => {
let mut end = usize::try_from(range.end).unwrap();
let mut start = usize::try_from(range.start).unwrap();
@ -183,7 +183,7 @@ impl Service<BCReadRequest> for DummyDatabase {
start -= dummy_height - block_len;
}
BCResponse::BlockExtendedHeaderInRange(
BlockchainResponse::BlockExtendedHeaderInRange(
blocks
.read()
.unwrap()
@ -195,7 +195,7 @@ impl Service<BCReadRequest> for DummyDatabase {
.collect(),
)
}
BCReadRequest::ChainHeight => {
BlockchainReadRequest::ChainHeight => {
let height: u64 = dummy_height
.unwrap_or(blocks.read().unwrap().len())
.try_into()
@ -204,9 +204,9 @@ impl Service<BCReadRequest> for DummyDatabase {
let mut top_hash = [0; 32];
top_hash[0..8].copy_from_slice(&height.to_le_bytes());
BCResponse::ChainHeight(height, top_hash)
BlockchainResponse::ChainHeight(height, top_hash)
}
BCReadRequest::GeneratedCoins(_) => BCResponse::GeneratedCoins(0),
BlockchainReadRequest::GeneratedCoins(_) => BlockchainResponse::GeneratedCoins(0),
_ => unimplemented!("the context svc should not need these requests!"),
})
}

View file

@ -28,7 +28,7 @@ use cuprate_consensus_rules::{
ConsensusError, HardFork, TxVersion,
};
use cuprate_helper::asynch::rayon_spawn_async;
use cuprate_types::blockchain::{BCReadRequest, BCResponse};
use cuprate_types::blockchain::{BlockchainReadRequest, BlockchainResponse};
use crate::{
batch_verifier::MultiThreadedBatchVerifier,
@ -308,10 +308,10 @@ where
})
})?;
let BCResponse::KeyImagesSpent(kis_spent) = database
let BlockchainResponse::KeyImagesSpent(kis_spent) = database
.ready()
.await?
.call(BCReadRequest::KeyImagesSpent(spent_kis))
.call(BlockchainReadRequest::KeyImagesSpent(spent_kis))
.await?
else {
panic!("Database sent incorrect response!");
@ -340,10 +340,10 @@ where
if !verified_at_block_hashes.is_empty() {
tracing::trace!("Filtering block hashes not in the main chain.");
let BCResponse::FilterUnknownHashes(known_hashes) = database
let BlockchainResponse::FilterUnknownHashes(known_hashes) = database
.ready()
.await?
.call(BCReadRequest::FilterUnknownHashes(verified_at_block_hashes))
.call(BlockchainReadRequest::FilterUnknownHashes(verified_at_block_hashes))
.await?
else {
panic!("Database returned wrong response!");

View file

@ -27,7 +27,7 @@ use cuprate_consensus_rules::{
ConsensusError, HardFork, TxVersion,
};
use cuprate_types::{
blockchain::{BCReadRequest, BCResponse},
blockchain::{BlockchainReadRequest, BlockchainResponse},
OutputOnChain,
};
@ -153,19 +153,19 @@ pub async fn batch_get_ring_member_info<D: Database>(
.map_err(ConsensusError::Transaction)?;
}
let BCResponse::Outputs(outputs) = database
let BlockchainResponse::Outputs(outputs) = database
.ready()
.await?
.call(BCReadRequest::Outputs(output_ids))
.call(BlockchainReadRequest::Outputs(output_ids))
.await?
else {
panic!("Database sent incorrect response!")
};
let BCResponse::NumberOutputsWithAmount(outputs_with_amount) = database
let BlockchainResponse::NumberOutputsWithAmount(outputs_with_amount) = database
.ready()
.await?
.call(BCReadRequest::NumberOutputsWithAmount(
.call(BlockchainReadRequest::NumberOutputsWithAmount(
outputs.keys().copied().collect(),
))
.await?
@ -234,10 +234,10 @@ pub async fn batch_get_decoy_info<'a, D: Database + Clone + Send + 'static>(
unique_input_amounts.len()
);
let BCResponse::NumberOutputsWithAmount(outputs_with_amount) = database
let BlockchainResponse::NumberOutputsWithAmount(outputs_with_amount) = database
.ready()
.await?
.call(BCReadRequest::NumberOutputsWithAmount(
.call(BlockchainReadRequest::NumberOutputsWithAmount(
unique_input_amounts.into_iter().collect(),
))
.await?

View file

@ -12,7 +12,7 @@ use cuprate_consensus::{
TxVerifierService, VerifyTxRequest, VerifyTxResponse, __private::Database,
};
use cuprate_types::{
blockchain::{BCReadRequest, BCResponse},
blockchain::{BlockchainReadRequest, BlockchainResponse},
OutputOnChain,
};
@ -23,12 +23,12 @@ use cuprate_test_utils::data::TX_E2D393;
fn dummy_database(outputs: BTreeMap<u64, OutputOnChain>) -> impl Database + Clone {
let outputs = Arc::new(outputs);
service_fn(move |req: BCReadRequest| {
service_fn(move |req: BlockchainReadRequest| {
ready(Ok(match req {
BCReadRequest::NumberOutputsWithAmount(_) => {
BCResponse::NumberOutputsWithAmount(HashMap::new())
BlockchainReadRequest::NumberOutputsWithAmount(_) => {
BlockchainResponse::NumberOutputsWithAmount(HashMap::new())
}
BCReadRequest::Outputs(outs) => {
BlockchainReadRequest::Outputs(outs) => {
let idxs = outs.get(&0).unwrap();
let mut ret = HashMap::new();
@ -40,9 +40,9 @@ fn dummy_database(outputs: BTreeMap<u64, OutputOnChain>) -> impl Database + Clon
.collect::<HashMap<_, _>>(),
);
BCResponse::Outputs(ret)
BlockchainResponse::Outputs(ret)
}
BCReadRequest::KeyImagesSpent(_) => BCResponse::KeyImagesSpent(false),
BlockchainReadRequest::KeyImagesSpent(_) => BlockchainResponse::KeyImagesSpent(false),
_ => panic!("Database request not needed for this test"),
}))
})

View file

@ -8,7 +8,7 @@ use cuprate_database::{ConcreteEnv, InitError};
use crate::service::{init_read_service, init_write_service};
use crate::{
config::Config,
service::types::{BCReadHandle, BCWriteHandle},
service::types::{BlockchainReadHandle, BlockchainWriteHandle},
};
//---------------------------------------------------------------------------------------------------- Init
@ -21,7 +21,7 @@ use crate::{
///
/// # Errors
/// This will forward the error if [`crate::open`] failed.
pub fn init(config: Config) -> Result<(BCReadHandle, BCWriteHandle, Arc<ConcreteEnv>), InitError> {
pub fn init(config: Config) -> Result<(BlockchainReadHandle, BlockchainWriteHandle, Arc<ConcreteEnv>), InitError> {
let reader_threads = config.reader_threads;
// Initialize the database itself.

View file

@ -14,8 +14,8 @@
//!
//! ## Handles
//! The 2 handles to the database are:
//! - [`BCReadHandle`]
//! - [`BCWriteHandle`]
//! - [`BlockchainReadHandle`]
//! - [`BlockchainWriteHandle`]
//!
//! The 1st allows any caller to send [`ReadRequest`][req_r]s.
//!
@ -33,8 +33,8 @@
//!
//! ## Shutdown
//! Upon the above handles being dropped, the corresponding thread(s) will automatically exit, i.e:
//! - The last [`BCReadHandle`] is dropped => reader thread-pool exits
//! - The last [`BCWriteHandle`] is dropped => writer thread exits
//! - The last [`BlockchainReadHandle`] is dropped => reader thread-pool exits
//! - The last [`BlockchainWriteHandle`] is dropped => writer thread exits
//!
//! TODO: update this when `ConcreteEnv` is removed
//! Upon dropping the [`cuprate_database::ConcreteEnv`]:
@ -51,11 +51,11 @@
//! This channel can be `.await`ed upon to (eventually) receive
//! the corresponding `Response` to your `Request`.
//!
//! [req_r]: cuprate_types::blockchain::BCReadRequest
//! [req_r]: cuprate_types::blockchain::BlockchainReadRequest
//!
//! [req_w]: cuprate_types::blockchain::BCWriteRequest
//! [req_w]: cuprate_types::blockchain::BlockchainWriteRequest
//!
//! [resp]: cuprate_types::blockchain::BCResponse
//! [resp]: cuprate_types::blockchain::BlockchainResponse
//!
//! # Example
//! Simple usage of `service`.
@ -64,7 +64,7 @@
//! use hex_literal::hex;
//! use tower::{Service, ServiceExt};
//!
//! use cuprate_types::{blockchain::{BCReadRequest, BCWriteRequest, BCResponse}, Chain};
//! use cuprate_types::{blockchain::{BlockchainReadRequest, BlockchainWriteRequest, BlockchainResponse}, Chain};
//! use cuprate_test_utils::data::block_v16_tx0;
//!
//! use cuprate_blockchain::{
@ -87,7 +87,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()`
//! let request = BCWriteRequest::WriteBlock(block);
//! let request = BlockchainWriteRequest::WriteBlock(block);
//!
//! // Send the request.
//! // We receive back an `async` channel that will
@ -97,16 +97,16 @@
//!
//! // Block write was OK.
//! let response = response_channel.await?;
//! assert_eq!(response, BCResponse::WriteBlockOk);
//! assert_eq!(response, BlockchainResponse::WriteBlockOk);
//!
//! // Now, let's try getting the block hash
//! // of the block we just wrote.
//! let request = BCReadRequest::BlockHash(0, Chain::Main);
//! let request = BlockchainReadRequest::BlockHash(0, Chain::Main);
//! let response_channel = read_handle.ready().await?.call(request);
//! let response = response_channel.await?;
//! assert_eq!(
//! response,
//! BCResponse::BlockHash(
//! BlockchainResponse::BlockHash(
//! hex!("43bd1f2b6556dcafa413d8372974af59e4e8f37dbf74dc6b2a9b7212d0577428")
//! )
//! );
@ -131,7 +131,7 @@ pub use write::init_write_service;
mod free;
pub use free::init;
mod types;
pub use types::{BCReadHandle, BCWriteHandle};
pub use types::{BlockchainReadHandle, BlockchainWriteHandle};
#[cfg(test)]
mod tests;

View file

@ -16,7 +16,7 @@ use cuprate_database::{ConcreteEnv, DatabaseRo, Env, EnvInner, RuntimeError};
use cuprate_database_service::{init_thread_pool, DatabaseReadService, ReaderThreads};
use cuprate_helper::map::combine_low_high_bits_to_u128;
use cuprate_types::{
blockchain::{BCReadRequest, BCResponse},
blockchain::{BlockchainReadRequest, BlockchainResponse},
Chain, ExtendedBlockHeader, OutputOnChain,
};
@ -31,14 +31,14 @@ use crate::{
},
service::{
free::{compact_history_genesis_not_included, compact_history_index_to_height_offset},
types::{BCReadHandle, ResponseResult},
types::{BlockchainReadHandle, ResponseResult},
},
tables::{BlockHeights, BlockInfos, OpenTables, Tables},
types::{Amount, AmountIndex, BlockHash, BlockHeight, KeyImage, PreRctOutputId},
};
//---------------------------------------------------------------------------------------------------- init_read_service
/// Initialize the [`BCReadHandle`] thread-pool backed by [`rayon`].
/// Initialize the [`BlockchainReadHandle`] thread-pool backed by [`rayon`].
///
/// This spawns `threads` amount of reader threads
/// attached to `env` and returns a handle to the pool.
@ -47,18 +47,18 @@ use crate::{
/// multiple unnecessary rayon thread-pools.
#[cold]
#[inline(never)] // Only called once.
pub fn init_read_service(env: Arc<ConcreteEnv>, threads: ReaderThreads) -> BCReadHandle {
pub fn init_read_service(env: Arc<ConcreteEnv>, threads: ReaderThreads) -> BlockchainReadHandle {
init_read_service_with_pool(env, init_thread_pool(threads))
}
/// Initialize the blockchain database read service, with a specific rayon thread-pool instead of
/// creating a new one.
///
/// Should be called _once_ per actual database, although nothing bad will happen, cloning the [`BCReadHandle`]
/// Should be called _once_ per actual database, although nothing bad will happen, cloning the [`BlockchainReadHandle`]
/// is the correct way to get multiple handles to the database.
#[cold]
#[inline(never)] // Only called once.
pub fn init_read_service_with_pool(env: Arc<ConcreteEnv>, pool: Arc<ThreadPool>) -> BCReadHandle {
pub fn init_read_service_with_pool(env: Arc<ConcreteEnv>, pool: Arc<ThreadPool>) -> BlockchainReadHandle {
DatabaseReadService::new(env, pool, map_request)
}
@ -72,12 +72,12 @@ pub fn init_read_service_with_pool(env: Arc<ConcreteEnv>, pool: Arc<ThreadPool>)
/// The basic structure is:
/// 1. `Request` is mapped to a handler function
/// 2. Handler function is called
/// 3. [`BCResponse`] is returned
/// 3. [`BlockchainResponse`] is returned
fn map_request(
env: &ConcreteEnv, // Access to the database
request: BCReadRequest, // The request we must fulfill
request: BlockchainReadRequest, // The request we must fulfill
) -> ResponseResult {
use BCReadRequest as R;
use BlockchainReadRequest as R;
/* SOMEDAY: pre-request handling, run some code for each request? */
@ -172,7 +172,7 @@ macro_rules! get_tables {
// TODO: The overhead of parallelism may be too much for every request, perfomace test to find optimal
// amount of parallelism.
/// [`BCReadRequest::BlockExtendedHeader`].
/// [`BlockchainReadRequest::BlockExtendedHeader`].
#[inline]
fn block_extended_header(env: &ConcreteEnv, block_height: BlockHeight) -> ResponseResult {
// Single-threaded, no `ThreadLocal` required.
@ -180,12 +180,12 @@ fn block_extended_header(env: &ConcreteEnv, block_height: BlockHeight) -> Respon
let tx_ro = env_inner.tx_ro()?;
let tables = env_inner.open_tables(&tx_ro)?;
Ok(BCResponse::BlockExtendedHeader(
Ok(BlockchainResponse::BlockExtendedHeader(
get_block_extended_header_from_height(&block_height, &tables)?,
))
}
/// [`BCReadRequest::BlockHash`].
/// [`BlockchainReadRequest::BlockHash`].
#[inline]
fn block_hash(env: &ConcreteEnv, block_height: BlockHeight, chain: Chain) -> ResponseResult {
// Single-threaded, no `ThreadLocal` required.
@ -198,10 +198,10 @@ fn block_hash(env: &ConcreteEnv, block_height: BlockHeight, chain: Chain) -> Res
Chain::Alt(_) => todo!("Add alt blocks to DB"),
};
Ok(BCResponse::BlockHash(block_hash))
Ok(BlockchainResponse::BlockHash(block_hash))
}
/// [`BCReadRequest::FilterUnknownHashes`].
/// [`BlockchainReadRequest::FilterUnknownHashes`].
#[inline]
fn filter_unknown_hashes(env: &ConcreteEnv, mut hashes: HashSet<BlockHash>) -> ResponseResult {
// Single-threaded, no `ThreadLocal` required.
@ -225,11 +225,11 @@ fn filter_unknown_hashes(env: &ConcreteEnv, mut hashes: HashSet<BlockHash>) -> R
if let Some(e) = err {
Err(e)
} else {
Ok(BCResponse::FilterUnknownHashes(hashes))
Ok(BlockchainResponse::FilterUnknownHashes(hashes))
}
}
/// [`BCReadRequest::BlockExtendedHeaderInRange`].
/// [`BlockchainReadRequest::BlockExtendedHeaderInRange`].
#[inline]
fn block_extended_header_in_range(
env: &ConcreteEnv,
@ -254,10 +254,10 @@ fn block_extended_header_in_range(
Chain::Alt(_) => todo!("Add alt blocks to DB"),
};
Ok(BCResponse::BlockExtendedHeaderInRange(vec))
Ok(BlockchainResponse::BlockExtendedHeaderInRange(vec))
}
/// [`BCReadRequest::ChainHeight`].
/// [`BlockchainReadRequest::ChainHeight`].
#[inline]
fn chain_height(env: &ConcreteEnv) -> ResponseResult {
// Single-threaded, no `ThreadLocal` required.
@ -270,10 +270,10 @@ fn chain_height(env: &ConcreteEnv) -> ResponseResult {
let block_hash =
get_block_info(&chain_height.saturating_sub(1), &table_block_infos)?.block_hash;
Ok(BCResponse::ChainHeight(chain_height, block_hash))
Ok(BlockchainResponse::ChainHeight(chain_height, block_hash))
}
/// [`BCReadRequest::GeneratedCoins`].
/// [`BlockchainReadRequest::GeneratedCoins`].
#[inline]
fn generated_coins(env: &ConcreteEnv, height: u64) -> ResponseResult {
// Single-threaded, no `ThreadLocal` required.
@ -281,13 +281,13 @@ fn generated_coins(env: &ConcreteEnv, height: u64) -> ResponseResult {
let tx_ro = env_inner.tx_ro()?;
let table_block_infos = env_inner.open_db_ro::<BlockInfos>(&tx_ro)?;
Ok(BCResponse::GeneratedCoins(cumulative_generated_coins(
Ok(BlockchainResponse::GeneratedCoins(cumulative_generated_coins(
&height,
&table_block_infos,
)?))
}
/// [`BCReadRequest::Outputs`].
/// [`BlockchainReadRequest::Outputs`].
#[inline]
fn outputs(env: &ConcreteEnv, outputs: HashMap<Amount, HashSet<AmountIndex>>) -> ResponseResult {
// Prepare tx/tables in `ThreadLocal`.
@ -325,10 +325,10 @@ fn outputs(env: &ConcreteEnv, outputs: HashMap<Amount, HashSet<AmountIndex>>) ->
})
.collect::<Result<HashMap<Amount, HashMap<AmountIndex, OutputOnChain>>, RuntimeError>>()?;
Ok(BCResponse::Outputs(map))
Ok(BlockchainResponse::Outputs(map))
}
/// [`BCReadRequest::NumberOutputsWithAmount`].
/// [`BlockchainReadRequest::NumberOutputsWithAmount`].
#[inline]
fn number_outputs_with_amount(env: &ConcreteEnv, amounts: Vec<Amount>) -> ResponseResult {
// Prepare tx/tables in `ThreadLocal`.
@ -370,10 +370,10 @@ fn number_outputs_with_amount(env: &ConcreteEnv, amounts: Vec<Amount>) -> Respon
})
.collect::<Result<HashMap<Amount, usize>, RuntimeError>>()?;
Ok(BCResponse::NumberOutputsWithAmount(map))
Ok(BlockchainResponse::NumberOutputsWithAmount(map))
}
/// [`BCReadRequest::KeyImagesSpent`].
/// [`BlockchainReadRequest::KeyImagesSpent`].
#[inline]
fn key_images_spent(env: &ConcreteEnv, key_images: HashSet<KeyImage>) -> ResponseResult {
// Prepare tx/tables in `ThreadLocal`.
@ -404,13 +404,13 @@ fn key_images_spent(env: &ConcreteEnv, key_images: HashSet<KeyImage>) -> Respons
// Else, `Ok(false)` will continue the iterator.
.find_any(|result| !matches!(result, Ok(false)))
{
None | Some(Ok(false)) => Ok(BCResponse::KeyImagesSpent(false)), // Key image was NOT found.
Some(Ok(true)) => Ok(BCResponse::KeyImagesSpent(true)), // Key image was found.
None | Some(Ok(false)) => Ok(BlockchainResponse::KeyImagesSpent(false)), // Key image was NOT found.
Some(Ok(true)) => Ok(BlockchainResponse::KeyImagesSpent(true)), // Key image was found.
Some(Err(e)) => Err(e), // A database error occurred.
}
}
/// [`BCReadRequest::CompactChainHistory`]
/// [`BlockchainReadRequest::CompactChainHistory`]
fn compact_chain_history(env: &ConcreteEnv) -> ResponseResult {
let env_inner = env.env_inner();
let tx_ro = env_inner.tx_ro()?;
@ -440,13 +440,13 @@ fn compact_chain_history(env: &ConcreteEnv) -> ResponseResult {
block_ids.push(get_block_info(&0, &table_block_infos)?.block_hash);
}
Ok(BCResponse::CompactChainHistory {
Ok(BlockchainResponse::CompactChainHistory {
cumulative_difficulty,
block_ids,
})
}
/// [`BCReadRequest::FindFirstUnknown`]
/// [`BlockchainReadRequest::FindFirstUnknown`]
///
/// # Invariant
/// `block_ids` must be sorted in chronological block order, or else
@ -478,12 +478,12 @@ fn find_first_unknown(env: &ConcreteEnv, block_ids: &[BlockHash]) -> ResponseRes
}
Ok(if idx == block_ids.len() {
BCResponse::FindFirstUnknown(None)
BlockchainResponse::FindFirstUnknown(None)
} else if idx == 0 {
BCResponse::FindFirstUnknown(Some((0, 0)))
BlockchainResponse::FindFirstUnknown(Some((0, 0)))
} else {
let last_known_height = get_block_height(&block_ids[idx - 1], &table_block_heights)?;
BCResponse::FindFirstUnknown(Some((idx, last_known_height + 1)))
BlockchainResponse::FindFirstUnknown(Some((idx, last_known_height + 1)))
})
}

View file

@ -18,7 +18,7 @@ use tower::{Service, ServiceExt};
use cuprate_database::{ConcreteEnv, DatabaseIter, DatabaseRo, Env, EnvInner, RuntimeError};
use cuprate_test_utils::data::{block_v16_tx0, block_v1_tx2, block_v9_tx3};
use cuprate_types::{
blockchain::{BCReadRequest, BCResponse, BCWriteRequest},
blockchain::{BlockchainReadRequest, BlockchainResponse, BlockchainWriteRequest},
Chain, OutputOnChain, VerifiedBlockInformation,
};
@ -29,7 +29,7 @@ use crate::{
blockchain::chain_height,
output::id_to_output_on_chain,
},
service::{init, BCReadHandle, BCWriteHandle},
service::{init, BlockchainReadHandle, BlockchainWriteHandle},
tables::{OpenTables, Tables, TablesIter},
tests::AssertTableLen,
types::{Amount, AmountIndex, PreRctOutputId},
@ -38,8 +38,8 @@ use crate::{
//---------------------------------------------------------------------------------------------------- Helper functions
/// Initialize the `service`.
fn init_service() -> (
BCReadHandle,
BCWriteHandle,
BlockchainReadHandle,
BlockchainWriteHandle,
Arc<ConcreteEnv>,
tempfile::TempDir,
) {
@ -81,10 +81,10 @@ async fn test_template(
block.height = i as u64;
// Request a block to be written, assert it was written.
let request = BCWriteRequest::WriteBlock(block);
let request = BlockchainWriteRequest::WriteBlock(block);
let response_channel = writer.call(request);
let response = response_channel.await.unwrap();
assert_eq!(response, BCResponse::WriteBlockOk);
assert_eq!(response, BlockchainResponse::WriteBlockOk);
}
//----------------------------------------------------------------------- Reset the transaction
@ -100,36 +100,36 @@ async fn test_template(
// Next few lines are just for preparing the expected responses,
// see further below for usage.
let extended_block_header_0 = Ok(BCResponse::BlockExtendedHeader(
let extended_block_header_0 = Ok(BlockchainResponse::BlockExtendedHeader(
get_block_extended_header_from_height(&0, &tables).unwrap(),
));
let extended_block_header_1 = if block_fns.len() > 1 {
Ok(BCResponse::BlockExtendedHeader(
Ok(BlockchainResponse::BlockExtendedHeader(
get_block_extended_header_from_height(&1, &tables).unwrap(),
))
} else {
Err(RuntimeError::KeyNotFound)
};
let block_hash_0 = Ok(BCResponse::BlockHash(
let block_hash_0 = Ok(BlockchainResponse::BlockHash(
get_block_info(&0, tables.block_infos()).unwrap().block_hash,
));
let block_hash_1 = if block_fns.len() > 1 {
Ok(BCResponse::BlockHash(
Ok(BlockchainResponse::BlockHash(
get_block_info(&1, tables.block_infos()).unwrap().block_hash,
))
} else {
Err(RuntimeError::KeyNotFound)
};
let range_0_1 = Ok(BCResponse::BlockExtendedHeaderInRange(vec![
let range_0_1 = Ok(BlockchainResponse::BlockExtendedHeaderInRange(vec![
get_block_extended_header_from_height(&0, &tables).unwrap(),
]));
let range_0_2 = if block_fns.len() >= 2 {
Ok(BCResponse::BlockExtendedHeaderInRange(vec![
Ok(BlockchainResponse::BlockExtendedHeaderInRange(vec![
get_block_extended_header_from_height(&0, &tables).unwrap(),
get_block_extended_header_from_height(&1, &tables).unwrap(),
]))
@ -142,13 +142,13 @@ async fn test_template(
let chain_height = {
let block_info =
get_block_info(&test_chain_height.saturating_sub(1), tables.block_infos()).unwrap();
Ok(BCResponse::ChainHeight(
Ok(BlockchainResponse::ChainHeight(
test_chain_height,
block_info.block_hash,
))
};
let cumulative_generated_coins = Ok(BCResponse::GeneratedCoins(cumulative_generated_coins));
let cumulative_generated_coins = Ok(BlockchainResponse::GeneratedCoins(cumulative_generated_coins));
let num_req = tables
.outputs_iter()
@ -158,7 +158,7 @@ async fn test_template(
.map(|key| key.amount)
.collect::<Vec<Amount>>();
let num_resp = Ok(BCResponse::NumberOutputsWithAmount(
let num_resp = Ok(BlockchainResponse::NumberOutputsWithAmount(
num_req
.iter()
.map(|amount| match tables.num_outputs().get(amount) {
@ -173,36 +173,36 @@ async fn test_template(
// Contains a fake non-spent key-image.
let ki_req = HashSet::from([[0; 32]]);
let ki_resp = Ok(BCResponse::KeyImagesSpent(false));
let ki_resp = Ok(BlockchainResponse::KeyImagesSpent(false));
//----------------------------------------------------------------------- Assert expected response
// Assert read requests lead to the expected responses.
for (request, expected_response) in [
(
BCReadRequest::BlockExtendedHeader(0),
BlockchainReadRequest::BlockExtendedHeader(0),
extended_block_header_0,
),
(
BCReadRequest::BlockExtendedHeader(1),
BlockchainReadRequest::BlockExtendedHeader(1),
extended_block_header_1,
),
(BCReadRequest::BlockHash(0, Chain::Main), block_hash_0),
(BCReadRequest::BlockHash(1, Chain::Main), block_hash_1),
(BlockchainReadRequest::BlockHash(0, Chain::Main), block_hash_0),
(BlockchainReadRequest::BlockHash(1, Chain::Main), block_hash_1),
(
BCReadRequest::BlockExtendedHeaderInRange(0..1, Chain::Main),
BlockchainReadRequest::BlockExtendedHeaderInRange(0..1, Chain::Main),
range_0_1,
),
(
BCReadRequest::BlockExtendedHeaderInRange(0..2, Chain::Main),
BlockchainReadRequest::BlockExtendedHeaderInRange(0..2, Chain::Main),
range_0_2,
),
(BCReadRequest::ChainHeight, chain_height),
(BlockchainReadRequest::ChainHeight, chain_height),
(
BCReadRequest::GeneratedCoins(test_chain_height),
BlockchainReadRequest::GeneratedCoins(test_chain_height),
cumulative_generated_coins,
),
(BCReadRequest::NumberOutputsWithAmount(num_req), num_resp),
(BCReadRequest::KeyImagesSpent(ki_req), ki_resp),
(BlockchainReadRequest::NumberOutputsWithAmount(num_req), num_resp),
(BlockchainReadRequest::KeyImagesSpent(ki_req), ki_resp),
] {
let response = reader.clone().oneshot(request).await;
println!("response: {response:#?}, expected_response: {expected_response:#?}");
@ -216,10 +216,10 @@ async fn test_template(
// Assert each key image we inserted comes back as "spent".
for key_image in tables.key_images_iter().keys().unwrap() {
let key_image = key_image.unwrap();
let request = BCReadRequest::KeyImagesSpent(HashSet::from([key_image]));
let request = BlockchainReadRequest::KeyImagesSpent(HashSet::from([key_image]));
let response = reader.clone().oneshot(request).await;
println!("response: {response:#?}, key_image: {key_image:#?}");
assert_eq!(response.unwrap(), BCResponse::KeyImagesSpent(true));
assert_eq!(response.unwrap(), BlockchainResponse::KeyImagesSpent(true));
}
//----------------------------------------------------------------------- Output checks
@ -280,10 +280,10 @@ async fn test_template(
.collect::<Vec<OutputOnChain>>();
// Send a request for every output we inserted before.
let request = BCReadRequest::Outputs(map.clone());
let request = BlockchainReadRequest::Outputs(map.clone());
let response = reader.clone().oneshot(request).await;
println!("Response::Outputs response: {response:#?}");
let Ok(BCResponse::Outputs(response)) = response else {
let Ok(BlockchainResponse::Outputs(response)) = response else {
panic!("{response:#?}")
};

View file

@ -3,16 +3,16 @@
//---------------------------------------------------------------------------------------------------- Use
use cuprate_database::RuntimeError;
use cuprate_database_service::{DatabaseReadService, DatabaseWriteHandle};
use cuprate_types::blockchain::{BCReadRequest, BCResponse, BCWriteRequest};
use cuprate_types::blockchain::{BlockchainReadRequest, BlockchainResponse, BlockchainWriteRequest};
//---------------------------------------------------------------------------------------------------- Types
/// The actual type of the response.
///
/// Either our [`BCResponse`], or a database error occurred.
pub(super) type ResponseResult = Result<BCResponse, RuntimeError>;
/// Either our [`BlockchainResponse`], or a database error occurred.
pub(super) type ResponseResult = Result<BlockchainResponse, RuntimeError>;
/// The blockchain database write service.
pub type BCWriteHandle = DatabaseWriteHandle<BCWriteRequest, BCResponse>;
pub type BlockchainWriteHandle = DatabaseWriteHandle<BlockchainWriteRequest, BlockchainResponse>;
/// The blockchain database read service.
pub type BCReadHandle = DatabaseReadService<BCReadRequest, BCResponse>;
pub type BlockchainReadHandle = DatabaseReadService<BlockchainReadRequest, BlockchainResponse>;

View file

@ -6,26 +6,26 @@ use std::sync::Arc;
use cuprate_database::{ConcreteEnv, Env, EnvInner, RuntimeError, TxRw};
use cuprate_database_service::DatabaseWriteHandle;
use cuprate_types::{
blockchain::{BCResponse, BCWriteRequest},
blockchain::{BlockchainResponse, BlockchainWriteRequest},
VerifiedBlockInformation,
};
use crate::{
service::types::{BCWriteHandle, ResponseResult},
service::types::{BlockchainWriteHandle, ResponseResult},
tables::OpenTables,
};
//---------------------------------------------------------------------------------------------------- init_write_service
/// Initialize the blockchain write service from a [`ConcreteEnv`].
pub fn init_write_service(env: Arc<ConcreteEnv>) -> BCWriteHandle {
DatabaseWriteHandle::init(env, handle_bc_request)
pub fn init_write_service(env: Arc<ConcreteEnv>) -> BlockchainWriteHandle {
DatabaseWriteHandle::init(env, handle_blockchain_request)
}
//---------------------------------------------------------------------------------------------------- handle_bc_request
/// Handle an incoming [`BCWriteRequest`], returning a [`BCResponse`].
fn handle_bc_request(env: &ConcreteEnv, req: &BCWriteRequest) -> Result<BCResponse, RuntimeError> {
/// Handle an incoming [`BlockchainWriteRequest`], returning a [`BlockchainResponse`].
fn handle_blockchain_request(env: &ConcreteEnv, req: &BlockchainWriteRequest) -> Result<BlockchainResponse, RuntimeError> {
match req {
BCWriteRequest::WriteBlock(block) => write_block(env, block),
BlockchainWriteRequest::WriteBlock(block) => write_block(env, block),
}
}
@ -38,7 +38,7 @@ fn handle_bc_request(env: &ConcreteEnv, req: &BCWriteRequest) -> Result<BCRespon
// Each function will return the [`Response`] that we
// should send back to the caller in [`map_request()`].
/// [`BCWriteRequest::WriteBlock`].
/// [`BlockchainWriteRequest::WriteBlock`].
#[inline]
fn write_block(env: &ConcreteEnv, block: &VerifiedBlockInformation) -> ResponseResult {
let env_inner = env.env_inner();
@ -52,7 +52,7 @@ fn write_block(env: &ConcreteEnv, block: &VerifiedBlockInformation) -> ResponseR
match result {
Ok(()) => {
TxRw::commit(tx_rw)?;
Ok(BCResponse::WriteBlockOk)
Ok(BlockchainResponse::WriteBlockOk)
}
Err(e) => {
// INVARIANT: ensure database atomicity by aborting

View file

@ -1,4 +1,4 @@
//! Database [`BCReadRequest`]s, [`BCWriteRequest`]s, and [`BCResponse`]s.
//! Database [`BlockchainReadRequest`]s, [`BlockchainWriteRequest`]s, and [`BlockchainResponse`]s.
//!
//! Tests that assert particular requests lead to particular
//! responses are also tested in Cuprate's blockchain database crate.
@ -14,14 +14,14 @@ use crate::types::{Chain, ExtendedBlockHeader, OutputOnChain, VerifiedBlockInfor
//---------------------------------------------------------------------------------------------------- ReadRequest
/// A read request to the blockchain database.
///
/// This pairs with [`BCResponse`], where each variant here
/// matches in name with a [`BCResponse`] variant. For example,
/// the proper response for a [`BCReadRequest::BlockHash`]
/// would be a [`BCResponse::BlockHash`].
/// This pairs with [`BlockchainResponse`], where each variant here
/// matches in name with a [`BlockchainResponse`] variant. For example,
/// the proper response for a [`BlockchainReadRequest::BlockHash`]
/// would be a [`BlockchainResponse::BlockHash`].
///
/// See `Response` for the expected responses per `Request`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BCReadRequest {
pub enum BlockchainReadRequest {
/// Request a block's extended header.
///
/// The input is the block's height.
@ -104,10 +104,10 @@ pub enum BCReadRequest {
/// A write request to the blockchain database.
///
/// There is currently only 1 write request to the database,
/// as such, the only valid [`BCResponse`] to this request is
/// the proper response for a [`BCResponse::WriteBlockOk`].
/// as such, the only valid [`BlockchainResponse`] to this request is
/// the proper response for a [`BlockchainResponse::WriteBlockOk`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BCWriteRequest {
pub enum BlockchainWriteRequest {
/// Request that a block be written to the database.
///
/// Input is an already verified block.
@ -119,60 +119,60 @@ pub enum BCWriteRequest {
///
/// These are the data types returned when using sending a `Request`.
///
/// This pairs with [`BCReadRequest`] and [`BCWriteRequest`],
/// This pairs with [`BlockchainReadRequest`] and [`BlockchainWriteRequest`],
/// see those two for more info.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BCResponse {
pub enum BlockchainResponse {
//------------------------------------------------------ Reads
/// Response to [`BCReadRequest::BlockExtendedHeader`].
/// Response to [`BlockchainReadRequest::BlockExtendedHeader`].
///
/// Inner value is the extended headed of the requested block.
BlockExtendedHeader(ExtendedBlockHeader),
/// Response to [`BCReadRequest::BlockHash`].
/// Response to [`BlockchainReadRequest::BlockHash`].
///
/// Inner value is the hash of the requested block.
BlockHash([u8; 32]),
/// Response to [`BCReadRequest::FindBlock`].
/// Response to [`BlockchainReadRequest::FindBlock`].
///
/// Inner value is the chain and height of the block if found.
FindBlock(Option<(Chain, u64)>),
/// Response to [`BCReadRequest::FilterUnknownHashes`].
/// Response to [`BlockchainReadRequest::FilterUnknownHashes`].
///
/// Inner value is the list of hashes that were in the main chain.
FilterUnknownHashes(HashSet<[u8; 32]>),
/// Response to [`BCReadRequest::BlockExtendedHeaderInRange`].
/// Response to [`BlockchainReadRequest::BlockExtendedHeaderInRange`].
///
/// Inner value is the list of extended header(s) of the requested block(s).
BlockExtendedHeaderInRange(Vec<ExtendedBlockHeader>),
/// Response to [`BCReadRequest::ChainHeight`].
/// Response to [`BlockchainReadRequest::ChainHeight`].
///
/// Inner value is the chain height, and the top block's hash.
ChainHeight(u64, [u8; 32]),
/// Response to [`BCReadRequest::GeneratedCoins`].
/// Response to [`BlockchainReadRequest::GeneratedCoins`].
///
/// Inner value is the total amount of generated coins up to and including the chosen height, in atomic units.
GeneratedCoins(u64),
/// Response to [`BCReadRequest::Outputs`].
/// Response to [`BlockchainReadRequest::Outputs`].
///
/// Inner value is all the outputs requested,
/// associated with their amount and amount index.
Outputs(HashMap<u64, HashMap<u64, OutputOnChain>>),
/// Response to [`BCReadRequest::NumberOutputsWithAmount`].
/// Response to [`BlockchainReadRequest::NumberOutputsWithAmount`].
///
/// Inner value is a `HashMap` of all the outputs requested where:
/// - Key = output amount
/// - Value = count of outputs with the same amount
NumberOutputsWithAmount(HashMap<u64, usize>),
/// Response to [`BCReadRequest::KeyImagesSpent`].
/// Response to [`BlockchainReadRequest::KeyImagesSpent`].
///
/// The inner value is `true` if _any_ of the key images
/// were spent (existed in the database already).
@ -180,7 +180,7 @@ pub enum BCResponse {
/// The inner value is `false` if _none_ of the key images were spent.
KeyImagesSpent(bool),
/// Response to [`BCReadRequest::CompactChainHistory`].
/// Response to [`BlockchainReadRequest::CompactChainHistory`].
CompactChainHistory {
/// A list of blocks IDs in our chain, starting with the most recent block, all the way to the genesis block.
///
@ -190,7 +190,7 @@ pub enum BCResponse {
cumulative_difficulty: u128,
},
/// The response for [`BCReadRequest::FindFirstUnknown`].
/// The response for [`BlockchainReadRequest::FindFirstUnknown`].
///
/// Contains the index of the first unknown block and its expected height.
///
@ -198,7 +198,7 @@ pub enum BCResponse {
FindFirstUnknown(Option<(usize, u64)>),
//------------------------------------------------------ Writes
/// Response to [`BCWriteRequest::WriteBlock`].
/// Response to [`BlockchainWriteRequest::WriteBlock`].
///
/// This response indicates that the requested block has
/// successfully been written to the database without error.