Skip to content

Commit

Permalink
[fix] #3162: Forbid 0 height in block streaming request
Browse files Browse the repository at this point in the history
Signed-off-by: Shanin Roman <shanin1000@yandex.ru>
  • Loading branch information
Erigara authored and mversic committed Oct 17, 2023
1 parent 7216c19 commit 0cebc16
Show file tree
Hide file tree
Showing 9 changed files with 54 additions and 14 deletions.
4 changes: 2 additions & 2 deletions cli/src/torii/routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,14 +317,14 @@ async fn handle_blocks_stream(kura: Arc<Kura>, mut stream: WebSocket) -> eyre::R
}
// This branch sends blocks
_ = interval.tick() => {
if let Some(block) = kura.get_block_by_height(from_height) {
if let Some(block) = kura.get_block_by_height(from_height.get()) {
stream
// TODO: to avoid clone `VersionedBlockMessage` could be split into sending and receiving parts
.send(VersionedBlockMessage::from(
BlockMessage(VersionedCommittedBlock::clone(&block)),
))
.await?;
from_height += 1;
from_height = from_height.checked_add(1).expect("Maximum block height is achieved.");
}
}
// Else branch to prevent panic i.e. I don't know what
Expand Down
16 changes: 10 additions & 6 deletions client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
clippy::std_instead_of_core,
clippy::std_instead_of_alloc
)]
use std::{collections::HashMap, fmt::Debug, marker::PhantomData, thread, time::Duration};
use std::{
collections::HashMap, fmt::Debug, marker::PhantomData, num::NonZeroU64, thread, time::Duration,
};

use derive_more::{DebugCustom, Display};
use eyre::{eyre, Result, WrapErr};
Expand Down Expand Up @@ -904,7 +906,7 @@ impl Client {
/// - Forwards from [`blocks_api::BlockIterator::new`]
pub fn listen_for_blocks(
&self,
height: u64,
height: NonZeroU64,
) -> Result<impl Iterator<Item = Result<VersionedCommittedBlock>>> {
blocks_api::BlockIterator::new(self.blocks_handler(height)?)
}
Expand All @@ -914,7 +916,7 @@ impl Client {
/// # Errors
/// - Forwards from [`Self::events_handler`]
/// - Forwards from [`blocks_api::BlockIterator::new`]
pub async fn listen_for_blocks_async(&self, height: u64) -> Result<AsyncBlockStream> {
pub async fn listen_for_blocks_async(&self, height: NonZeroU64) -> Result<AsyncBlockStream> {
blocks_api::AsyncBlockStream::new(self.blocks_handler(height)?).await
}

Expand All @@ -923,7 +925,7 @@ impl Client {
/// # Errors
/// - if handler construction fails
#[inline]
pub fn blocks_handler(&self, height: u64) -> Result<blocks_api::flow::Init> {
pub fn blocks_handler(&self, height: NonZeroU64) -> Result<blocks_api::flow::Init> {
blocks_api::flow::Init::new(
height,
self.headers.clone(),
Expand Down Expand Up @@ -1363,14 +1365,16 @@ mod blocks_api {

/// Blocks API flow. For documentation and usage examples, refer to [`crate::http::ws::conn_flow`].
pub mod flow {
use std::num::NonZeroU64;

use iroha_data_model::block::stream::*;

use super::*;

/// Initialization struct for Blocks API flow.
pub struct Init {
/// Block height from which to start streaming blocks
height: u64,
height: NonZeroU64,
/// HTTP request headers
headers: HashMap<String, String>,
/// TORII URL
Expand All @@ -1384,7 +1388,7 @@ mod blocks_api {
/// If [`transform_ws_url`] fails.
#[inline]
pub(in super::super) fn new(
height: u64,
height: NonZeroU64,
headers: HashMap<String, String>,
url: Url,
) -> Result<Self> {
Expand Down
6 changes: 4 additions & 2 deletions client_cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,8 @@ mod events {
}

mod blocks {
use std::num::NonZeroU64;

use iroha_client::client::Client;
use iroha_config::client::Configuration;

Expand All @@ -269,7 +271,7 @@ mod blocks {
#[derive(StructOpt, Debug, Clone, Copy)]
pub struct Args {
/// Block height from which to start streaming blocks
height: u64,
height: NonZeroU64,
}

impl RunArgs for Args {
Expand All @@ -279,7 +281,7 @@ mod blocks {
}
}

pub fn listen(height: u64, cfg: &Configuration) -> Result<Box<dyn Serialize>> {
pub fn listen(height: NonZeroU64, cfg: &Configuration) -> Result<Box<dyn Serialize>> {
let iroha_client = Client::new(cfg)?;
eprintln!("Listening to blocks from height: {height}");
let blocks = iroha_client
Expand Down
Binary file modified configs/peer/validator.wasm
Binary file not shown.
4 changes: 3 additions & 1 deletion data_model/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,13 +399,15 @@ pub mod stream {

#[model]
pub mod model {
use core::num::NonZeroU64;

use super::*;

/// Request sent to subscribe to blocks stream starting from the given height.
#[version_with_scale(n = 1, versioned = "VersionedBlockSubscriptionRequest")]
#[derive(Debug, Clone, Copy, Constructor, Decode, Encode, IntoSchema)]
#[repr(transparent)]
pub struct BlockSubscriptionRequest(pub u64);
pub struct BlockSubscriptionRequest(pub NonZeroU64);

/// Message sent by the stream producer
/// Block sent by the peer.
Expand Down
3 changes: 2 additions & 1 deletion docs/source/references/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -675,7 +675,7 @@
}
]
},
"BlockSubscriptionRequest": "u64",
"BlockSubscriptionRequest": "NonZero<u64>",
"BurnBox": {
"Struct": [
{
Expand Down Expand Up @@ -2912,6 +2912,7 @@
]
},
"NonTrivial<GenericPredicateBox<ValuePredicate>>": "Vec<GenericPredicateBox<ValuePredicate>>",
"NonZero<u64>": "u64",
"Not": {
"Struct": [
{
Expand Down
2 changes: 2 additions & 0 deletions schema/gen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -421,10 +421,12 @@ types!(
u32,
u64,
u8,
NonZeroU64,
);

#[cfg(test)]
mod tests {
use core::num::NonZeroU64;
use std::{
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
time::Duration,
Expand Down
32 changes: 30 additions & 2 deletions schema/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ use alloc::{
vec,
vec::Vec,
};
use core::ops::RangeInclusive;
use core::{
num::{NonZeroU32, NonZeroU64},
ops::RangeInclusive,
};

/// Derive schema. It will make your structure schemaable
pub use iroha_schema_derive::*;
Expand Down Expand Up @@ -259,9 +262,34 @@ macro_rules! impl_schema_int {
}
)*};
}

impl_schema_int!(u128, u64, u32, u16, u8, i128, i64, i32, i16, i8);

macro_rules! impl_schema_non_zero_int {
($($src:ty => $dst:ty),*) => {$(
impl TypeId for $src {
fn id() -> String {
format!("NonZero<{}>", <$dst as TypeId>::id())
}
}
impl IntoSchema for $src {
fn type_name() -> String {
format!("NonZero<{}>", <$dst as IntoSchema>::type_name())
}
fn update_schema_map(map: &mut MetaMap) {
if !map.contains_key::<Self>() {
map.insert::<Self>(Metadata::Tuple(UnnamedFieldsMeta {
types: vec![core::any::TypeId::of::<$dst>()],
}));

<$dst as IntoSchema>::update_schema_map(map);
}
}
}
)*};
}

impl_schema_non_zero_int!(NonZeroU64 => u64, NonZeroU32 => u32);

impl<I: TypeId, P: DecimalPlacesAware> TypeId for fixnum::FixedPoint<I, P> {
fn id() -> String {
format!("FixedPoint<{}>", I::id())
Expand Down
1 change: 1 addition & 0 deletions tools/parity_scale_decoder/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
)]
#![allow(clippy::print_stdout, clippy::use_debug, clippy::unnecessary_wraps)]

use core::num::NonZeroU64;
use std::{
collections::{BTreeMap, BTreeSet},
fmt::Debug,
Expand Down

0 comments on commit 0cebc16

Please # to comment.