Skip to content

Commit

Permalink
refactor!: Remove genesis signing from Iroha
Browse files Browse the repository at this point in the history
Signed-off-by: Dmitry Murzin <diralik@yandex.ru>
  • Loading branch information
dima74 committed May 30, 2024
1 parent 4779723 commit 1e6a90a
Show file tree
Hide file tree
Showing 31 changed files with 857 additions and 877 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ iroha_config = { workspace = true }
iroha_crypto = { workspace = true }
iroha_torii = { workspace = true }
iroha_genesis = { workspace = true }
iroha_version = { workspace = true }
iroha_wasm_builder = { workspace = true }

clap = { workspace = true, features = ["derive", "env", "string"] }
Expand Down
88 changes: 44 additions & 44 deletions cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
//! should be constructed externally: (see `main.rs`).
#[cfg(debug_assertions)]
use core::sync::atomic::{AtomicBool, Ordering};
use std::{path::PathBuf, sync::Arc};
use std::{
path::{Path, PathBuf},
sync::Arc,
};

use clap::Parser;
use error_stack::{IntoReportCompat, Report, Result, ResultExt};
Expand All @@ -33,10 +36,11 @@ use iroha_core::{
IrohaNetwork,
};
use iroha_data_model::prelude::*;
use iroha_genesis::{GenesisNetwork, RawGenesisBlock};
use iroha_genesis::{GenesisNetwork, GenesisTransaction};
use iroha_logger::{actor::LoggerHandle, InitConfig as LoggerInitConfig};
use iroha_primitives::addr::SocketAddr;
use iroha_torii::Torii;
use iroha_version::scale::DecodeVersioned;
use thiserror::Error;
use tokio::{
signal,
Expand Down Expand Up @@ -647,21 +651,10 @@ pub fn read_config_and_genesis(
.parse()
.change_context(ConfigError::ParseConfig)?;

let genesis = if let Genesis::Full { key_pair, file } = &config.genesis {
let raw_block = RawGenesisBlock::from_path(file.resolve_relative_path())
.into_report()
// https://github.com/hashintel/hash/issues/4295
.map_err(|report| {
report
.attach_printable(file.clone().into_attachment().display_path())
.change_context(ConfigError::ReadGenesis)
})?;

Some(GenesisNetwork::new(
raw_block,
&config.common.chain_id,
key_pair,
))
let genesis = if let Genesis::Full { signed_file, .. } = &config.genesis {
let genesis = read_genesis(&signed_file.resolve_relative_path())
.attach_printable(signed_file.clone().into_attachment().display_path())?;
Some(GenesisNetwork::new(genesis))
} else {
None
};
Expand All @@ -673,6 +666,13 @@ pub fn read_config_and_genesis(
Ok((config, logger_config, genesis))
}

fn read_genesis(path: &Path) -> Result<GenesisTransaction, ConfigError> {
let bytes = std::fs::read(path).change_context(ConfigError::ReadGenesis)?;
let genesis =
SignedTransaction::decode_all_versioned(&bytes).change_context(ConfigError::ReadGenesis)?;
Ok(GenesisTransaction(genesis))
}

fn validate_config(config: &Config, submit_genesis: bool) -> Result<(), ConfigError> {
let mut emitter = Emitter::new();

Expand All @@ -692,8 +692,8 @@ fn validate_config(config: &Config, submit_genesis: bool) -> Result<(), ConfigEr
emitter.emit(Report::new(ConfigError::LonePeer).attach_printable("\
Reason: the network consists from this one peer only (no `sumeragi.trusted_peers` provided).\n\
Since `--submit-genesis` is not set, there is no way to receive the genesis block.\n\
Either provide the genesis by setting `--submit-genesis` argument, `genesis.private_key`,\n\
and `genesis.file` configuration parameters, or increase the number of trusted peers in\n\
Either provide the genesis by setting `--submit-genesis` argument\n\
and `genesis.signed_file` configuration parameter, or increase the number of trusted peers in\n\
the network using `sumeragi.trusted_peers` configuration parameter.\
").attach_printable(config.sumeragi.trusted_peers.clone().into_attachment().display_as_debug()));
}
Expand Down Expand Up @@ -820,8 +820,8 @@ pub struct Args {
///
/// Only one peer in the network should submit the genesis block.
///
/// This argument must be set alongside with `genesis.file` and `genesis.private_key`
/// configuration options. If not, Iroha will exit with an error.
/// This argument must be set alongside with `genesis.signed_file` configuration option.
/// If not, Iroha will exit with an error.
///
/// In case when the network consists only of this one peer, i.e. the amount of trusted
/// peers in the configuration (`sumeragi.trusted_peers`) is less than 2, this peer must
Expand All @@ -833,7 +833,7 @@ pub struct Args {

#[cfg(test)]
mod tests {
use iroha_genesis::RawGenesisBlockBuilder;
use iroha_genesis::GenesisTransactionBuilder;

use super::*;

Expand Down Expand Up @@ -863,18 +863,16 @@ mod tests {
}

mod config_integration {
use std::path::PathBuf;

use assertables::{assert_contains, assert_contains_as_result};
use iroha_crypto::{ExposedPrivateKey, KeyPair};
use iroha_primitives::addr::socket_addr;
use iroha_version::Encode;
use path_absolutize::Absolutize as _;

use super::*;

fn config_factory() -> toml::Table {
fn config_factory(genesis_public_key: &PublicKey) -> toml::Table {
let (pubkey, privkey) = KeyPair::random().into_parts();
let (genesis_pubkey, genesis_privkey) = KeyPair::random().into_parts();

let mut table = toml::Table::new();
iroha_config::base::toml::Writer::new(&mut table)
Expand All @@ -883,37 +881,38 @@ mod tests {
.write("private_key", ExposedPrivateKey(privkey))
.write(["network", "address"], socket_addr!(127.0.0.1:1337))
.write(["torii", "address"], socket_addr!(127.0.0.1:8080))
.write(["genesis", "public_key"], genesis_pubkey)
.write(
["genesis", "private_key"],
ExposedPrivateKey(genesis_privkey),
);
.write(["genesis", "public_key"], genesis_public_key);
table
}

fn dummy_executor() -> Executor {
Executor::new(WasmSmartContract::from_compiled(vec![1, 2, 3]))
}

#[test]
fn relative_file_paths_resolution() -> eyre::Result<()> {
// Given

let genesis = RawGenesisBlockBuilder::default()
.executor_file(PathBuf::from("./executor.wasm"))
.build();
let genesis_key_pair = KeyPair::random();
let genesis = GenesisTransactionBuilder::default()
.executor_blob(dummy_executor())
.build_and_sign(ChainId::from("0"), &genesis_key_pair);

let mut config = config_factory();
let mut config = config_factory(genesis_key_pair.public_key());
iroha_config::base::toml::Writer::new(&mut config)
.write(["genesis", "file"], "./genesis/gen.json")
.write(["genesis", "signed_file"], "./genesis/gen.scale")
.write(["kura", "store_dir"], "../storage")
.write(["snapshot", "store_dir"], "../snapshots")
.write(["dev_telemetry", "out_file"], "../logs/telemetry");

let dir = tempfile::tempdir()?;
let genesis_path = dir.path().join("config/genesis/gen.json");
let genesis_path = dir.path().join("config/genesis/gen.scale");
let executor_path = dir.path().join("config/genesis/executor.wasm");
let config_path = dir.path().join("config/config.toml");
std::fs::create_dir(dir.path().join("config"))?;
std::fs::create_dir(dir.path().join("config/genesis"))?;
std::fs::write(config_path, toml::to_string(&config)?)?;
std::fs::write(genesis_path, json5::to_string(&genesis)?)?;
std::fs::write(genesis_path, genesis.0.encode())?;
std::fs::write(executor_path, "")?;

let config_path = dir.path().join("config/config.toml");
Expand Down Expand Up @@ -962,17 +961,18 @@ mod tests {
fn fails_with_no_trusted_peers_and_submit_role() -> eyre::Result<()> {
// Given

let genesis = RawGenesisBlockBuilder::default()
.executor_file(PathBuf::from("./executor.wasm"))
.build();
let genesis_key_pair = KeyPair::random();
let genesis = GenesisTransactionBuilder::default()
.executor_blob(dummy_executor())
.build_and_sign(ChainId::from("0"), &genesis_key_pair);

let mut config = config_factory();
let mut config = config_factory(genesis_key_pair.public_key());
iroha_config::base::toml::Writer::new(&mut config)
.write(["genesis", "file"], "./genesis.json");
.write(["genesis", "signed_file"], "./genesis.scale");

let dir = tempfile::tempdir()?;
std::fs::write(dir.path().join("config.toml"), toml::to_string(&config)?)?;
std::fs::write(dir.path().join("genesis.json"), json5::to_string(&genesis)?)?;
std::fs::write(dir.path().join("genesis.scale"), genesis.0.encode())?;
std::fs::write(dir.path().join("executor.wasm"), "")?;
let config_path = dir.path().join("config.toml");

Expand Down
12 changes: 5 additions & 7 deletions cli/src/samples.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,9 @@ pub fn get_config_toml(
peers: UniqueVec<PeerId>,
chain_id: ChainId,
peer_key_pair: KeyPair,
genesis_key_pair: KeyPair,
genesis_public_key: &PublicKey,
) -> toml::Table {
let (public_key, private_key) = peer_key_pair.into_parts();
let (genesis_public_key, genesis_private_key) = genesis_key_pair.into_parts();

iroha_logger::info!(%public_key, "sample configuration public key");

Expand All @@ -75,10 +74,9 @@ pub fn get_config_toml(
.write(["chain_wide", "max_transactions_in_block"], 2)
.write(["genesis", "public_key"], genesis_public_key)
.write(
["genesis", "private_key"],
ExposedPrivateKey(genesis_private_key),
["genesis", "signed_file"],
"NEVER READ ME; YOU FOUND A BUG!",
)
.write(["genesis", "file"], "NEVER READ ME; YOU FOUND A BUG!")
// There is no need in persistence in tests.
// If required to should be set explicitly not to overlap with other existing tests
.write(["snapshot", "mode"], "disabled");
Expand All @@ -94,13 +92,13 @@ pub fn get_config(
trusted_peers: UniqueVec<PeerId>,
chain_id: ChainId,
peer_key_pair: KeyPair,
genesis_key_pair: KeyPair,
genesis_public_key: &PublicKey,
) -> Config {
Config::from_toml_source(TomlSource::inline(get_config_toml(
trusted_peers,
chain_id,
peer_key_pair,
genesis_key_pair,
genesis_public_key,
)))
.expect("should be a valid config")
}
Expand Down
54 changes: 21 additions & 33 deletions client/benches/torii.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use iroha::{
client::{asset, Client},
data_model::prelude::*,
};
use iroha_genesis::{GenesisNetwork, RawGenesisBlockBuilder};
use iroha_genesis::GenesisTransactionBuilder;
use iroha_primitives::unique_vec;
use iroha_version::Encode;
use irohad::samples::{construct_executor, get_config};
Expand All @@ -21,29 +21,23 @@ fn query_requests(criterion: &mut Criterion) {
let mut peer = <TestPeer>::new().expect("Failed to create peer");

let chain_id = get_chain_id();
let genesis_key_pair = get_key_pair(test_network::Signatory::Genesis);
let configuration = get_config(
unique_vec![peer.id.clone()],
chain_id.clone(),
get_key_pair(test_network::Signatory::Peer),
get_key_pair(test_network::Signatory::Genesis),
genesis_key_pair.public_key(),
);

let rt = Runtime::test();
let genesis = GenesisNetwork::new(
RawGenesisBlockBuilder::default()
.domain("wonderland".parse().expect("Valid"))
.account(get_key_pair(test_network::Signatory::Alice).into_parts().0)
.finish_domain()
.executor_blob(
construct_executor("../default_executor").expect("Failed to construct executor"),
)
.build(),
&chain_id,
configuration
.genesis
.key_pair()
.expect("genesis config should be full, probably a bug"),
);
let genesis = GenesisTransactionBuilder::default()
.domain("wonderland".parse().expect("Valid"))
.account(get_key_pair(test_network::Signatory::Alice).into_parts().0)
.finish_domain()
.executor_blob(
construct_executor("../default_executor").expect("Failed to construct executor"),
)
.build_and_sign(chain_id, &genesis_key_pair);

let builder = PeerBuilder::new()
.with_config(configuration)
Expand Down Expand Up @@ -125,27 +119,21 @@ fn instruction_submits(criterion: &mut Criterion) {
let mut peer = <TestPeer>::new().expect("Failed to create peer");

let chain_id = get_chain_id();
let genesis_key_pair = get_key_pair(test_network::Signatory::Genesis);
let configuration = get_config(
unique_vec![peer.id.clone()],
chain_id.clone(),
get_key_pair(test_network::Signatory::Peer),
get_key_pair(test_network::Signatory::Genesis),
);
let genesis = GenesisNetwork::new(
RawGenesisBlockBuilder::default()
.domain("wonderland".parse().expect("Valid"))
.account(configuration.common.key_pair.public_key().clone())
.finish_domain()
.executor_blob(
construct_executor("../default_executor").expect("Failed to construct executor"),
)
.build(),
&chain_id,
configuration
.genesis
.key_pair()
.expect("config should be full; probably a bug"),
genesis_key_pair.public_key(),
);
let genesis = GenesisTransactionBuilder::default()
.domain("wonderland".parse().expect("Valid"))
.account(configuration.common.key_pair.public_key().clone())
.finish_domain()
.executor_blob(
construct_executor("../default_executor").expect("Failed to construct executor"),
)
.build_and_sign(chain_id, &genesis_key_pair);
let builder = PeerBuilder::new()
.with_config(configuration)
.with_into_genesis(genesis);
Expand Down
24 changes: 11 additions & 13 deletions client/examples/million_accounts_genesis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{thread, time::Duration};

use iroha::{crypto::KeyPair, data_model::prelude::*};
use iroha_data_model::isi::InstructionBox;
use iroha_genesis::{GenesisNetwork, RawGenesisBlock, RawGenesisBlockBuilder};
use iroha_genesis::{GenesisTransaction, GenesisTransactionBuilder};
use iroha_primitives::unique_vec;
use irohad::samples::{construct_executor, get_config};
use test_network::{
Expand All @@ -12,8 +12,12 @@ use test_network::{
};
use tokio::runtime::Runtime;

fn generate_genesis(num_domains: u32) -> RawGenesisBlock {
let mut builder = RawGenesisBlockBuilder::default();
fn generate_genesis(
num_domains: u32,
chain_id: ChainId,
genesis_key_pair: &KeyPair,
) -> GenesisTransaction {
let mut builder = GenesisTransactionBuilder::default();

let signatory_alice = get_key_pair(test_network::Signatory::Alice).into_parts().0;
for i in 0_u32..num_domains {
Expand All @@ -31,28 +35,22 @@ fn generate_genesis(num_domains: u32) -> RawGenesisBlock {
.executor_blob(
construct_executor("../default_executor").expect("Failed to construct executor"),
)
.build()
.build_and_sign(chain_id, genesis_key_pair)
}

fn main_genesis() {
let mut peer = <TestPeer>::new().expect("Failed to create peer");

let chain_id = get_chain_id();
let genesis_key_pair = get_key_pair(test_network::Signatory::Genesis);
let configuration = get_config(
unique_vec![peer.id.clone()],
chain_id.clone(),
get_key_pair(test_network::Signatory::Peer),
get_key_pair(test_network::Signatory::Genesis),
genesis_key_pair.public_key(),
);
let rt = Runtime::test();
let genesis = GenesisNetwork::new(
generate_genesis(1_000_000_u32),
&chain_id,
configuration
.genesis
.key_pair()
.expect("should be available in the config; probably a bug"),
);
let genesis = generate_genesis(1_000_000_u32, chain_id, &genesis_key_pair);

let builder = PeerBuilder::new()
.with_into_genesis(genesis)
Expand Down
Loading

0 comments on commit 1e6a90a

Please sign in to comment.