remove InstaFuture for Ready

Also renames some functions so it's clear as to what they do https://github.com/Cuprate/cuprate/pull/45#issuecomment-1859054439
This commit is contained in:
Boog900 2023-12-17 14:50:08 +00:00
parent cf5e909f1b
commit e264a40feb
No known key found for this signature in database
GPG key ID: 5401367FB7302004
7 changed files with 29 additions and 56 deletions

View file

@ -26,24 +26,3 @@ impl<T> Future for InfallibleOneshotReceiver<T> {
.map(|res| res.expect("Oneshot must not be cancelled before response!"))
}
}
/// A future that is ready straight away.
pub struct InstaFuture<T>(Option<T>);
impl<T: Unpin> From<T> for InstaFuture<T> {
fn from(value: T) -> Self {
InstaFuture(Some(value))
}
}
impl<T: Unpin> Future for InstaFuture<T> {
type Output = T;
fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Ready(
self.0
.take()
.expect("Can't call future twice after Poll::Ready"),
)
}
}

View file

@ -4,7 +4,7 @@ use primitive_types::U256;
use cryptonight_cuprate::*;
use crate::{
current_time,
current_unix_timestamp,
hard_forks::HardForkError,
miner_tx::{check_miner_tx, MinerTxError},
HardFork,
@ -125,7 +125,7 @@ fn check_prev_id(block: &Block, top_hash: &[u8; 32]) -> Result<(), BlockError> {
/// https://cuprate.github.io/monero-book/consensus_rules/blocks.html#timestamp
fn check_timestamp(block: &Block, median_timestamp: u64) -> Result<(), BlockError> {
if block.header.timestamp < median_timestamp
|| block.header.timestamp > current_time() + BLOCK_FUTURE_TIME_LIMIT
|| block.header.timestamp > current_unix_timestamp() + BLOCK_FUTURE_TIME_LIMIT
{
Err(BlockError::TimeStampInvalid)
} else {

View file

@ -22,10 +22,10 @@ pub enum ConsensusError {
Signatures(#[from] signatures::SignatureError),
}
/// Checks that a point is canonical.
/// Checks that a point is canonically encoded.
///
/// https://github.com/dalek-cryptography/curve25519-dalek/issues/380
fn check_point(point: &curve25519_dalek::edwards::CompressedEdwardsY) -> bool {
fn check_point_canonically_encoded(point: &curve25519_dalek::edwards::CompressedEdwardsY) -> bool {
let bytes = point.as_bytes();
point
@ -35,7 +35,7 @@ fn check_point(point: &curve25519_dalek::edwards::CompressedEdwardsY) -> bool {
.is_some()
}
pub(crate) fn current_time() -> u64 {
pub fn current_unix_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()

View file

@ -2,7 +2,7 @@ use std::{cmp::Ordering, collections::HashSet, sync::Arc};
use monero_serai::transaction::{Input, Output, Timelock};
use crate::{check_point, is_decomposed_amount, HardFork};
use crate::{check_point_canonically_encoded, is_decomposed_amount, HardFork};
mod contextual_data;
pub use contextual_data::*;
@ -67,12 +67,12 @@ impl TxVersion {
//----------------------------------------------------------------------------------------------------------- OUTPUTS
/// Checks the output keys are canonical points.
/// Checks the output keys are canonically encoded points.
///
/// https://cuprate.github.io/monero-book/consensus_rules/transactions.html#output-keys-canonical
fn check_output_keys(outputs: &[Output]) -> Result<(), TransactionError> {
for out in outputs {
if !check_point(&out.key) {
if !check_point_canonically_encoded(&out.key) {
return Err(TransactionError::OutputNotValidPoint);
}
}

View file

@ -14,17 +14,15 @@ use std::{
};
use futures::{
future::{ready, Ready},
lock::{Mutex, OwnedMutexGuard, OwnedMutexLockFuture},
FutureExt,
};
use tower::{Service, ServiceExt};
use cuprate_common::tower_utils::InstaFuture;
use monero_consensus::{blocks::ContextToVerifyBlock, HardFork};
use monero_consensus::{blocks::ContextToVerifyBlock, current_unix_timestamp, HardFork};
use crate::{
helper::current_time, Database, DatabaseRequest, DatabaseResponse, ExtendedConsensusError,
};
use crate::{Database, DatabaseRequest, DatabaseResponse, ExtendedConsensusError};
mod difficulty;
mod hardforks;
@ -166,7 +164,7 @@ impl RawBlockChainContext {
/// https://cuprate.github.io/monero-book/consensus_rules/transactions/unlock_time.html#getting-the-current-time
pub fn current_adjusted_timestamp_for_time_lock(&self) -> u64 {
if self.current_hf < HardFork::V13 || self.median_block_timestamp.is_none() {
current_time()
current_unix_timestamp()
} else {
// This is safe as we just checked if this was None.
let median = self.median_block_timestamp.unwrap();
@ -296,7 +294,7 @@ impl Clone for BlockChainContextService {
impl Service<BlockChainContextRequest> for BlockChainContextService {
type Response = BlockChainContextResponse;
type Error = tower::BoxError;
type Future = InstaFuture<Result<Self::Response, Self::Error>>;
type Future = Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
loop {
@ -332,11 +330,11 @@ impl Service<BlockChainContextRequest> for BlockChainContextService {
already_generated_coins,
} = internal_blockchain_context.deref_mut();
match req {
let res = match req {
BlockChainContextRequest::Get => {
let current_hf = hardfork_state.current_hardfork();
InstaFuture::from(Ok(BlockChainContextResponse::Context(BlockChainContext {
BlockChainContextResponse::Context(BlockChainContext {
validity_token: current_validity_token.clone(),
raw: RawBlockChainContext {
context_to_verify_block: ContextToVerifyBlock {
@ -358,7 +356,7 @@ impl Service<BlockChainContextRequest> for BlockChainContextService {
top_block_timestamp: difficulty_cache.top_block_timestamp(),
re_org_token: current_reorg_token.clone(),
},
})))
})
}
BlockChainContextRequest::Update(new) => {
// Cancel the validity token and replace it with a new one.
@ -375,8 +373,10 @@ impl Service<BlockChainContextRequest> for BlockChainContextService {
*already_generated_coins =
already_generated_coins.saturating_add(new.generated_coins);
InstaFuture::from(Ok(BlockChainContextResponse::Ok))
BlockChainContextResponse::Ok
}
}
};
ready(Ok(res))
}
}

View file

@ -1,7 +1,4 @@
use std::{
ops::{Add, Div, Mul, Sub},
time::{SystemTime, UNIX_EPOCH},
};
use std::ops::{Add, Div, Mul, Sub};
/// Spawns a task for the rayon thread pool and awaits the result without blocking the async runtime.
pub(crate) async fn rayon_spawn_async<F, R>(f: F) -> R
@ -45,10 +42,3 @@ where
array[mid]
}
}
pub(crate) fn current_time() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}

View file

@ -7,7 +7,11 @@ use std::{
time::Duration,
};
use futures::{stream::FuturesUnordered, FutureExt, StreamExt};
use futures::{
future::{ready, Ready},
stream::FuturesUnordered,
FutureExt, StreamExt,
};
use pin_project::pin_project;
use tokio::{
task::JoinHandle,
@ -15,7 +19,7 @@ use tokio::{
};
use tower::Service;
use cuprate_common::{tower_utils::InstaFuture, PruningSeed};
use cuprate_common::PruningSeed;
use monero_p2p::{
client::InternalPeerID,
handles::ConnectionHandle,
@ -363,7 +367,7 @@ impl<Z: NetworkZone> AddressBook<Z> {
impl<Z: NetworkZone> Service<AddressBookRequest<Z>> for AddressBook<Z> {
type Response = AddressBookResponse<Z>;
type Error = AddressBookError;
type Future = InstaFuture<Result<Self::Response, Self::Error>>;
type Future = Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.poll_unban_peers(cx);
@ -419,6 +423,6 @@ impl<Z: NetworkZone> Service<AddressBookRequest<Z>> for AddressBook<Z> {
}
};
InstaFuture::from(response)
ready(response)
}
}