Skip to content

Commit 22d6e10

Browse files
committed
ADD: block_stream
Signed-off-by: Stukalov-A-M <[email protected]>
1 parent 417c237 commit 22d6e10

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

Rust/examples/block_stream.rs

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
use iroha_client::client::Client;
2+
use std::num::NonZeroU64;
3+
4+
fn main() -> Result<(), Box<dyn Error>> {
5+
let config = get_config(get_config_path()?);
6+
let iroha_client: Client = Client::new(&config)?;
7+
8+
initiate_block_listener(&iroha_client, 1)?;
9+
10+
Ok(())
11+
}
12+
/// Auxiliary method for a block listener
13+
/// You shall implement it first
14+
fn non_zero_handler(number: u64) -> NonZeroU64 {
15+
NonZeroU64::new(number).map_or_else(
16+
|| {
17+
println!("The number must be > 0, using default value 1");
18+
NonZeroU64::new(1).unwrap()
19+
},
20+
|non_zero| non_zero,
21+
)
22+
}
23+
/// A block listener configuration
24+
/// iroha_client - Your iroha client implementation
25+
/// initial_block_number - The number of a block listener should start from.
26+
/// To get total quantity of blocks, you may use method iroha_client.get_status().
27+
fn initiate_block_listener(
28+
iroha_client: &Client,
29+
initial_block_number: u64,
30+
) -> Result<(), Box<dyn Error>> {
31+
// Processing the non zero value from the u64
32+
let block_number = non_zero_handler(initial_block_number);
33+
// Initiating the block listener object
34+
let block_iter = iroha_client.listen_for_blocks(block_number)?;
35+
// Initiating iteration by blocks. The iterator is infinite
36+
for block in block_iter {
37+
match &block {
38+
Ok(block) => println!("Received block: {block:?}"),
39+
Err(e) => println!("Error happened: {}", e),
40+
}
41+
}
42+
Ok(())
43+
}
44+
use iroha_config::client::Configuration;
45+
use std::env;
46+
use std::error::Error;
47+
use std::fs::File;
48+
use std::path::{Path, PathBuf};
49+
50+
pub fn get_config_path() -> Result<PathBuf, Box<dyn Error>> {
51+
let exe_path = env::current_exe();
52+
let binding = exe_path?;
53+
let ancestors = binding.ancestors();
54+
for ancestor in ancestors {
55+
if ancestor.file_name() == Some("target".as_ref()) {
56+
let source_path = Path::new(ancestor);
57+
let mut config_path = PathBuf::from(source_path.parent().unwrap());
58+
config_path.push("src");
59+
config_path.push("resources");
60+
config_path.push("config.json");
61+
return Ok(config_path);
62+
}
63+
}
64+
Err("The source directory was not found in the ancestor path.".into())
65+
}
66+
pub fn get_config(path_buf: PathBuf) -> Configuration {
67+
let file =
68+
File::open(&path_buf).unwrap_or_else(|_| panic!("Failed to read file at: {path_buf:?}"));
69+
serde_json::from_reader(file).unwrap_or_else(|_| panic!("Failed to read config at ?????"))
70+
}

0 commit comments

Comments
 (0)