Skip to content

Commit

Permalink
refactor: Remove GenesisNetwork (#4693)
Browse files Browse the repository at this point in the history
Signed-off-by: Dmitry Murzin <[email protected]>
  • Loading branch information
dima74 authored Jun 6, 2024
1 parent 8157c45 commit e9557e5
Show file tree
Hide file tree
Showing 11 changed files with 45 additions and 85 deletions.
9 changes: 4 additions & 5 deletions cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ use iroha_core::{
IrohaNetwork,
};
use iroha_data_model::prelude::*;
use iroha_genesis::{GenesisNetwork, GenesisTransaction};
use iroha_genesis::GenesisTransaction;
use iroha_logger::{actor::LoggerHandle, InitConfig as LoggerInitConfig};
use iroha_primitives::addr::SocketAddr;
use iroha_torii::Torii;
Expand Down Expand Up @@ -241,7 +241,7 @@ impl Iroha<ToriiNotStarted> {
#[iroha_logger::log(name = "init", skip_all)] // This is actually easier to understand as a linear sequence of init statements.
pub async fn start_network(
config: Config,
genesis: Option<GenesisNetwork>,
genesis: Option<GenesisTransaction>,
logger: LoggerHandle,
) -> Result<Self, StartError> {
let network = IrohaNetwork::start(config.common.key_pair.clone(), config.network.clone())
Expand Down Expand Up @@ -631,10 +631,9 @@ pub enum ConfigError {
/// # Errors
/// - If failed to read the config
/// - If failed to load the genesis block
/// - If failed to build a genesis network
pub fn read_config_and_genesis(
args: &Args,
) -> Result<(Config, LoggerInitConfig, Option<GenesisNetwork>), ConfigError> {
) -> Result<(Config, LoggerInitConfig, Option<GenesisTransaction>), ConfigError> {
let mut reader = ConfigReader::new();

if let Some(path) = &args.config {
Expand All @@ -652,7 +651,7 @@ pub fn read_config_and_genesis(
let genesis = if let Some(signed_file) = &config.genesis.signed_file {
let genesis = read_genesis(&signed_file.resolve_relative_path())
.attach_printable(signed_file.clone().into_attachment().display_path())?;
Some(GenesisNetwork::new(genesis))
Some(genesis)
} else {
None
};
Expand Down
4 changes: 2 additions & 2 deletions client/benches/torii.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ fn query_requests(criterion: &mut Criterion) {

let builder = PeerBuilder::new()
.with_config(configuration)
.with_into_genesis(genesis);
.with_genesis(genesis);

rt.block_on(builder.start_with_peer(&mut peer));
rt.block_on(async {
Expand Down Expand Up @@ -132,7 +132,7 @@ fn instruction_submits(criterion: &mut Criterion) {
.build_and_sign(executor, chain_id, &genesis_key_pair);
let builder = PeerBuilder::new()
.with_config(configuration)
.with_into_genesis(genesis);
.with_genesis(genesis);
rt.block_on(builder.start_with_peer(&mut peer));
let mut group = criterion.benchmark_group("instruction-requests");
let domain_id: DomainId = "domain".parse().expect("Valid");
Expand Down
2 changes: 1 addition & 1 deletion client/examples/million_accounts_genesis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ fn main_genesis() {
let genesis = generate_genesis(1_000_000_u32, chain_id, &genesis_key_pair);

let builder = PeerBuilder::new()
.with_into_genesis(genesis)
.with_genesis(genesis)
.with_config(configuration);

// This only submits the genesis. It doesn't check if the accounts
Expand Down
2 changes: 1 addition & 1 deletion client/examples/register_1000_triggers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let genesis = generate_genesis(1_000_u32, chain_id, &genesis_key_pair)?;

let builder = PeerBuilder::new()
.with_into_genesis(genesis)
.with_genesis(genesis)
.with_config(configuration);

let rt = Runtime::test();
Expand Down
4 changes: 2 additions & 2 deletions client/tests/integration/permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use iroha_data_model::{
permission::Permission, role::RoleId, transaction::error::TransactionRejectionReason,
JsonString,
};
use iroha_genesis::GenesisNetwork;
use iroha_genesis::GenesisTransaction;
use serde_json::json;
use test_network::{PeerBuilder, *};
use test_samples::{gen_account_in, ALICE_ID, BOB_ID};
Expand All @@ -22,7 +22,7 @@ fn genesis_transactions_are_validated() {

// Setting up genesis

let genesis = GenesisNetwork::test_with_instructions([Grant::permission(
let genesis = GenesisTransaction::test_with_instructions([Grant::permission(
Permission::new("InvalidToken".parse().unwrap(), json!(null)),
ALICE_ID.clone(),
)
Expand Down
4 changes: 2 additions & 2 deletions client/tests/integration/triggers/by_call_trigger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use iroha::{
},
};
use iroha_crypto::KeyPair;
use iroha_genesis::GenesisNetwork;
use iroha_genesis::GenesisTransaction;
use iroha_logger::info;
use serde_json::json;
use test_network::*;
Expand Down Expand Up @@ -440,7 +440,7 @@ fn trigger_in_genesis_using_base64() -> Result<()> {
);

// Registering trigger in genesis
let genesis = GenesisNetwork::test_with_instructions([Register::trigger(trigger).into()]);
let genesis = GenesisTransaction::test_with_instructions([Register::trigger(trigger).into()]);

let (_rt, _peer, mut test_client) = <PeerBuilder>::new()
.with_genesis(genesis)
Expand Down
Binary file modified configs/swarm/executor.wasm
100755 → 100644
Binary file not shown.
15 changes: 8 additions & 7 deletions core/src/sumeragi/main_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ impl Sumeragi {

fn sumeragi_init_commit_genesis(
&mut self,
genesis_network: GenesisNetwork,
genesis_transaction: GenesisTransaction,
genesis_public_key: &PublicKey,
state: &State,
) {
Expand All @@ -272,12 +272,13 @@ impl Sumeragi {
assert_eq!(state_view.latest_block_hash(), None);
}

let transactions: Vec<_> = genesis_network
.into_transactions()
.into_iter()
.map(|tx| AcceptedTransaction::accept_genesis(tx, &self.chain_id, genesis_public_key))
.collect::<Result<_, _>>()
.expect("Genesis invalid");
let transaction = AcceptedTransaction::accept_genesis(
genesis_transaction,
&self.chain_id,
genesis_public_key,
)
.expect("Genesis invalid");
let transactions = vec![transaction];

let mut state_block = state.block();
let genesis = BlockBuilder::new(transactions, self.current_topology.clone(), vec![])
Expand Down
4 changes: 2 additions & 2 deletions core/src/sumeragi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use eyre::Result;
use iroha_config::parameters::actual::{Common as CommonConfig, Sumeragi as SumeragiConfig};
use iroha_crypto::{KeyPair, SignatureOf};
use iroha_data_model::{block::SignedBlock, prelude::*};
use iroha_genesis::GenesisNetwork;
use iroha_genesis::GenesisTransaction;
use iroha_logger::prelude::*;
use network_topology::{Role, Topology};

Expand Down Expand Up @@ -323,6 +323,6 @@ pub struct SumeragiMetrics {
/// Optional genesis paired with genesis public key for verification
#[allow(missing_docs)]
pub struct GenesisWithPubKey {
pub genesis: Option<GenesisNetwork>,
pub genesis: Option<GenesisTransaction>,
pub public_key: PublicKey,
}
51 changes: 22 additions & 29 deletions core/test_network/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use iroha_config::parameters::actual::{Root as Config, Sumeragi, TrustedPeers};
pub use iroha_core::state::StateReadOnly;
use iroha_crypto::{ExposedPrivateKey, KeyPair};
use iroha_data_model::{query::QueryOutputBox, ChainId};
use iroha_genesis::{GenesisNetwork, GenesisTransaction, RawGenesisTransaction};
use iroha_genesis::{GenesisTransaction, RawGenesisTransaction};
use iroha_logger::{warn, InstrumentFutures};
use iroha_primitives::{
addr::{socket_addr, SocketAddr},
Expand Down Expand Up @@ -68,16 +68,16 @@ pub enum Signatory {

/// Trait used to differentiate a test instance of `genesis`.
pub trait TestGenesis: Sized {
/// Construct Iroha genesis network
/// Construct Iroha genesis
fn test() -> Self {
Self::test_with_instructions([])
}

/// Construct genesis network with additional instructions
/// Construct genesis with additional instructions
fn test_with_instructions(extra_isi: impl IntoIterator<Item = InstructionBox>) -> Self;
}

impl TestGenesis for GenesisNetwork {
impl TestGenesis for GenesisTransaction {
fn test_with_instructions(extra_isi: impl IntoIterator<Item = InstructionBox>) -> Self {
let cfg = Config::test();

Expand Down Expand Up @@ -128,10 +128,9 @@ impl TestGenesis for GenesisNetwork {
if &cfg.genesis.public_key != genesis_key_pair.public_key() {
panic!("`Config::test` expected to use SAMPLE_GENESIS_ACCOUNT_KEYPAIR");
}
let genesis = genesis
genesis
.build_and_sign(&genesis_key_pair)
.expect("genesis should load fine");
GenesisNetwork::new(genesis)
.expect("genesis should load fine")
}
}

Expand Down Expand Up @@ -214,7 +213,7 @@ impl Network {

let peer = PeerBuilder::new()
.with_config(config)
.with_genesis(GenesisNetwork::test())
.with_test_genesis()
.start()
.await;

Expand Down Expand Up @@ -255,7 +254,7 @@ impl Network {
(n, builder)
}
})
.map(|(n, builder)| builder.with_into_genesis((n == 0).then(GenesisNetwork::test)))
.map(|(n, builder)| builder.with_into_genesis((n == 0).then(GenesisTransaction::test)))
.take(n_peers as usize)
.collect::<Vec<_>>();
let mut peers = builders
Expand Down Expand Up @@ -443,7 +442,7 @@ impl Peer {
async fn start(
&mut self,
config: Config,
genesis: Option<GenesisNetwork>,
genesis: Option<GenesisTransaction>,
temp_dir: Arc<TempDir>,
) {
let mut config = self.get_config(config);
Expand Down Expand Up @@ -520,30 +519,24 @@ impl Peer {

/// `WithGenesis` structure.
///
/// Options for setting up the genesis network for `PeerBuilder`.
/// Options for setting up the genesis for `PeerBuilder`.
#[derive(Default)]
pub enum WithGenesis {
/// Use the default genesis network.
/// Use the default genesis.
#[default]
Default,
/// Do not use any genesis networks.
/// Do not use any genesis.
None,
/// Use the given genesis network.
Has(GenesisNetwork),
/// Use the given genesis.
Has(GenesisTransaction),
}

impl From<Option<GenesisNetwork>> for WithGenesis {
fn from(genesis: Option<GenesisNetwork>) -> Self {
impl From<Option<GenesisTransaction>> for WithGenesis {
fn from(genesis: Option<GenesisTransaction>) -> Self {
genesis.map_or(Self::None, Self::Has)
}
}

impl From<GenesisTransaction> for WithGenesis {
fn from(genesis: GenesisTransaction) -> Self {
Self::Has(GenesisNetwork::new(genesis))
}
}

/// `PeerBuilder`.
#[derive(Default)]
pub struct PeerBuilder {
Expand All @@ -569,24 +562,24 @@ impl PeerBuilder {
self
}

/// Set the optional genesis network.
/// Set the optional genesis.
#[must_use]
pub fn with_into_genesis(mut self, genesis: impl Into<WithGenesis>) -> Self {
self.genesis = genesis.into();
self
}

/// Set the genesis network.
/// Set the genesis.
#[must_use]
pub fn with_genesis(mut self, genesis: GenesisNetwork) -> Self {
pub fn with_genesis(mut self, genesis: GenesisTransaction) -> Self {
self.genesis = WithGenesis::Has(genesis);
self
}

/// Set the test genesis network.
/// Set the test genesis.
#[must_use]
pub fn with_test_genesis(self) -> Self {
self.with_genesis(GenesisNetwork::test())
self.with_genesis(GenesisTransaction::test())
}

/// Set Iroha configuration
Expand Down Expand Up @@ -628,7 +621,7 @@ impl PeerBuilder {
pub async fn start_with_peer(self, peer: &mut Peer) {
let config = self.config.unwrap_or_else(Config::test);
let genesis = match self.genesis {
WithGenesis::Default => Some(GenesisNetwork::test()),
WithGenesis::Default => Some(GenesisTransaction::test()),
WithGenesis::None => None,
WithGenesis::Has(genesis) => Some(genesis),
};
Expand Down
35 changes: 1 addition & 34 deletions genesis/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,28 +23,6 @@ pub static GENESIS_DOMAIN_ID: Lazy<DomainId> = Lazy::new(|| "genesis".parse().un
#[repr(transparent)]
pub struct GenesisTransaction(pub SignedTransaction);

/// [`GenesisNetwork`] contains initial transactions and genesis setup related parameters.
#[derive(Debug, Clone)]
pub struct GenesisNetwork {
/// Transactions from [`RawGenesisBlock`]. This vector is guaranteed to be non-empty,
/// unless [`GenesisNetwork::transactions_mut()`] is used.
transactions: Vec<GenesisTransaction>,
}

impl GenesisNetwork {
/// Constructor
pub fn new(genesis_transaction: GenesisTransaction) -> GenesisNetwork {
GenesisNetwork {
transactions: vec![genesis_transaction],
}
}

/// Transform into genesis transactions
pub fn into_transactions(self) -> Vec<GenesisTransaction> {
self.transactions
}
}

/// Format of genesis.json user file.
/// It should be signed and serialized to [`GenesisTransaction`]
/// in SCALE format before supplying to Iroha peer.
Expand Down Expand Up @@ -144,6 +122,7 @@ fn get_executor(file: &Path) -> Result<Executor> {
/// that does not perform any correctness checking on the block produced.
/// Use with caution in tests and other things to register domains and accounts.
#[must_use]
#[derive(Default)]
pub struct GenesisTransactionBuilder {
instructions: Vec<InstructionBox>,
}
Expand All @@ -157,18 +136,6 @@ pub struct GenesisDomainBuilder {
domain_id: DomainId,
}

impl Default for GenesisTransactionBuilder {
fn default() -> Self {
// Do not add `impl Default`. While it can technically be
// regarded as a default constructor, this builder should not
// be used in contexts where `Default::default()` is likely to
// be called.
Self {
instructions: Vec::new(),
}
}
}

impl GenesisTransactionBuilder {
/// Create a domain and return a domain builder which can
/// be used to create assets and accounts.
Expand Down

0 comments on commit e9557e5

Please sign in to comment.