diff --git a/cli/src/lib.rs b/cli/src/lib.rs index 95030eecf89..996fc52a76a 100644 --- a/cli/src/lib.rs +++ b/cli/src/lib.rs @@ -559,7 +559,7 @@ mod tests { use super::*; fn config_factory() -> PartialUserConfig { - let (pubkey, privkey) = KeyPair::generate().into(); + let (pubkey, privkey) = KeyPair::random().into_parts(); let mut base = PartialUserConfig::default(); diff --git a/cli/src/samples.rs b/cli/src/samples.rs index 35fd25da53e..bf372d8f6c2 100644 --- a/cli/src/samples.rs +++ b/cli/src/samples.rs @@ -65,7 +65,7 @@ pub fn get_user_config( ) -> UserConfig { let chain_id = chain_id.unwrap_or_else(|| ChainId::from("0")); - let (public_key, private_key) = key_pair.unwrap_or_else(KeyPair::generate).into(); + let (public_key, private_key) = key_pair.unwrap_or_else(KeyPair::random).into_parts(); iroha_logger::info!(%public_key); let mut config = UserConfig::new(); diff --git a/client/benches/torii.rs b/client/benches/torii.rs index ad40f98e79f..f58096a6a29 100644 --- a/client/benches/torii.rs +++ b/client/benches/torii.rs @@ -63,7 +63,7 @@ fn query_requests(criterion: &mut Criterion) { let domain_id: DomainId = "domain".parse().expect("Valid"); let create_domain = Register::domain(Domain::new(domain_id.clone())); let account_id = AccountId::new(domain_id.clone(), "account".parse().expect("Valid")); - let (public_key, _) = KeyPair::generate().into(); + let (public_key, _) = KeyPair::random().into_parts(); let create_account = Register::account(Account::new(account_id.clone(), public_key)); let asset_definition_id = AssetDefinitionId::new(domain_id, "xor".parse().expect("Valid")); let create_asset = @@ -162,7 +162,7 @@ fn instruction_submits(criterion: &mut Criterion) { let domain_id: DomainId = "domain".parse().expect("Valid"); let create_domain: InstructionBox = Register::domain(Domain::new(domain_id.clone())).into(); let account_id = AccountId::new(domain_id.clone(), "account".parse().expect("Valid")); - let (public_key, _) = KeyPair::generate().into(); + let (public_key, _) = KeyPair::random().into_parts(); let create_account = Register::account(Account::new(account_id.clone(), public_key)).into(); let asset_definition_id = AssetDefinitionId::new(domain_id, "xor".parse().expect("Valid")); let client_config = iroha_client::samples::get_client_config( diff --git a/client/benches/tps/utils.rs b/client/benches/tps/utils.rs index 28db18337f8..c00aed40439 100644 --- a/client/benches/tps/utils.rs +++ b/client/benches/tps/utils.rs @@ -153,7 +153,7 @@ impl MeasurerUnit { /// Submit initial transactions for measurement fn ready(self) -> Result { - let keypair = iroha_client::crypto::KeyPair::generate(); + let keypair = iroha_client::crypto::KeyPair::random(); let account_id = account_id(self.name); let asset_id = asset_id(self.name); diff --git a/client/examples/million_accounts_genesis.rs b/client/examples/million_accounts_genesis.rs index 34ab2af07dc..26d22df1b25 100644 --- a/client/examples/million_accounts_genesis.rs +++ b/client/examples/million_accounts_genesis.rs @@ -80,7 +80,7 @@ fn create_million_accounts_directly() { let create_domain: InstructionBox = Register::domain(Domain::new(domain_id)).into(); let create_account = Register::account(Account::new( normal_account_id.clone(), - KeyPair::generate().into_raw_parts().0, + KeyPair::random().into_parts().0, )) .into(); if test_client diff --git a/client/examples/tutorial.rs b/client/examples/tutorial.rs index adb46ecf85b..f4b36283ac6 100644 --- a/client/examples/tutorial.rs +++ b/client/examples/tutorial.rs @@ -117,7 +117,7 @@ fn account_registration_test(config: Config) -> Result<(), Error> { // TODO: consider getting a key from white_rabbit // Generate a new public key for a new account - let (public_key, _) = KeyPair::generate().into(); + let (public_key, _) = KeyPair::random().into_parts(); // #region register_account_generate // Generate a new account diff --git a/client/src/client.rs b/client/src/client.rs index bfee9800b76..a9636e7866e 100644 --- a/client/src/client.rs +++ b/client/src/client.rs @@ -1552,7 +1552,7 @@ mod tests { fn config_factory() -> Config { Config { chain_id: ChainId::from("0"), - key_pair: KeyPair::generate(), + key_pair: KeyPair::random(), account_id: "alice@wonderland" .parse() .expect("This account ID should be valid"), diff --git a/client/tests/integration/asset.rs b/client/tests/integration/asset.rs index 2836e63fb0f..fe95e30f348 100644 --- a/client/tests/integration/asset.rs +++ b/client/tests/integration/asset.rs @@ -268,8 +268,8 @@ fn find_rate_and_make_exchange_isi_should_succeed() { let seller_btc: AssetId = "btc#crypto#seller@company".parse().expect("Valid."); let buyer_eth: AssetId = "eth#crypto#buyer@company".parse().expect("Valid."); - let seller_keypair = KeyPair::generate(); - let buyer_keypair = KeyPair::generate(); + let seller_keypair = KeyPair::random(); + let buyer_keypair = KeyPair::random(); let register_account = |account_id: AccountId, signature: PublicKey| { Register::account(Account::new(account_id, signature)) diff --git a/client/tests/integration/asset_propagation.rs b/client/tests/integration/asset_propagation.rs index fe2d5d96441..48129d2f3e1 100644 --- a/client/tests/integration/asset_propagation.rs +++ b/client/tests/integration/asset_propagation.rs @@ -31,7 +31,7 @@ fn client_add_asset_quantity_to_existing_asset_should_increase_asset_amount_on_a let create_domain: InstructionBox = Register::domain(Domain::new(DomainId::from_str("domain")?)).into(); let account_id = AccountId::from_str("account@domain")?; - let (public_key, _) = KeyPair::generate().into(); + let (public_key, _) = KeyPair::random().into_parts(); let create_account = Register::account(Account::new(account_id.clone(), public_key)).into(); let asset_definition_id = AssetDefinitionId::from_str("xor#domain")?; let create_asset = diff --git a/client/tests/integration/burn_public_keys.rs b/client/tests/integration/burn_public_keys.rs index f99cb7bb933..8d245051aea 100644 --- a/client/tests/integration/burn_public_keys.rs +++ b/client/tests/integration/burn_public_keys.rs @@ -47,7 +47,7 @@ fn public_keys_cannot_be_burned_to_nothing() { let (_rt, _peer, client) = ::new().with_port(10_045).start_with_runtime(); wait_for_genesis_committed(&vec![client.clone()], 0); - let charlie_initial_keypair = KeyPair::generate(); + let charlie_initial_keypair = KeyPair::random(); let register_charlie = Register::account(Account::new( charlie_id.clone(), charlie_initial_keypair.public_key().clone(), @@ -60,7 +60,7 @@ fn public_keys_cannot_be_burned_to_nothing() { assert_eq!(keys_count, 1); let mint_keys = (0..KEYS_COUNT - 1).map(|_| { - let (public_key, _) = KeyPair::generate().into(); + let (public_key, _) = KeyPair::random().into_parts(); Mint::account_public_key(public_key, charlie_id.clone()) }); diff --git a/client/tests/integration/domain_owner_permissions.rs b/client/tests/integration/domain_owner_permissions.rs index d04fbff1273..06892c6a3b3 100644 --- a/client/tests/integration/domain_owner_permissions.rs +++ b/client/tests/integration/domain_owner_permissions.rs @@ -24,7 +24,7 @@ fn domain_owner_domain_permissions() -> Result<()> { let kingdom = Domain::new(kingdom_id.clone()); test_client.submit_blocking(Register::domain(kingdom))?; - let bob_keypair = KeyPair::generate(); + let bob_keypair = KeyPair::random(); let bob = Account::new(bob_id.clone(), bob_keypair.public_key().clone()); test_client.submit_blocking(Register::account(bob))?; @@ -95,7 +95,7 @@ fn domain_owner_account_permissions() -> Result<()> { let kingdom = Domain::new(kingdom_id); test_client.submit_blocking(Register::domain(kingdom))?; - let mad_hatter_keypair = KeyPair::generate(); + let mad_hatter_keypair = KeyPair::random(); let mad_hatter = Account::new( mad_hatter_id.clone(), mad_hatter_keypair.public_key().clone(), @@ -103,7 +103,7 @@ fn domain_owner_account_permissions() -> Result<()> { test_client.submit_blocking(Register::account(mad_hatter))?; // check that "alice@wonderland" as owner of domain can burn and mint public keys for accounts in her domain - let mad_hatter_new_keypair = KeyPair::generate(); + let mad_hatter_new_keypair = KeyPair::random(); test_client.submit_blocking(Mint::account_public_key( mad_hatter_new_keypair.public_key().clone(), mad_hatter_id.clone(), @@ -159,7 +159,7 @@ fn domain_owner_asset_definition_permissions() -> Result<()> { let kingdom = Domain::new(kingdom_id.clone()); test_client.submit_blocking(Register::domain(kingdom))?; - let bob_keypair = KeyPair::generate(); + let bob_keypair = KeyPair::random(); let bob = Account::new(bob_id.clone(), bob_keypair.public_key().clone()); test_client.submit_blocking(Register::account(bob))?; @@ -229,7 +229,7 @@ fn domain_owner_asset_permissions() -> Result<()> { let kingdom = Domain::new(kingdom_id.clone()); test_client.submit_blocking(Register::domain(kingdom))?; - let bob_keypair = KeyPair::generate(); + let bob_keypair = KeyPair::random(); let bob = Account::new(bob_id.clone(), bob_keypair.public_key().clone()); test_client.submit_blocking(Register::account(bob))?; @@ -294,7 +294,7 @@ fn domain_owner_trigger_permissions() -> Result<()> { let kingdom = Domain::new(kingdom_id); test_client.submit_blocking(Register::domain(kingdom))?; - let bob_keypair = KeyPair::generate(); + let bob_keypair = KeyPair::random(); let bob = Account::new(bob_id.clone(), bob_keypair.public_key().clone()); test_client.submit_blocking(Register::account(bob))?; @@ -355,7 +355,7 @@ fn domain_owner_transfer() -> Result<()> { let kingdom = Domain::new(kingdom_id.clone()); test_client.submit_blocking(Register::domain(kingdom))?; - let bob_keypair = KeyPair::generate(); + let bob_keypair = KeyPair::random(); let bob = Account::new(bob_id.clone(), bob_keypair.public_key().clone()); test_client.submit_blocking(Register::account(bob))?; diff --git a/client/tests/integration/extra_functional/multiple_blocks_created.rs b/client/tests/integration/extra_functional/multiple_blocks_created.rs index bff603526fc..ee229fa1dfd 100644 --- a/client/tests/integration/extra_functional/multiple_blocks_created.rs +++ b/client/tests/integration/extra_functional/multiple_blocks_created.rs @@ -30,7 +30,7 @@ fn long_multiple_blocks_created() -> Result<()> { let create_domain: InstructionBox = Register::domain(Domain::new("domain".parse()?)).into(); let account_id: AccountId = "account@domain".parse()?; - let (public_key, _) = KeyPair::generate().into(); + let (public_key, _) = KeyPair::random().into_parts(); let create_account = Register::account(Account::new(account_id.clone(), public_key)).into(); let asset_definition_id: AssetDefinitionId = "xor#domain".parse()?; let create_asset = diff --git a/client/tests/integration/extra_functional/offline_peers.rs b/client/tests/integration/extra_functional/offline_peers.rs index f0c2d584c5a..988b0271acb 100644 --- a/client/tests/integration/extra_functional/offline_peers.rs +++ b/client/tests/integration/extra_functional/offline_peers.rs @@ -53,7 +53,7 @@ fn register_offline_peer() -> Result<()> { check_status(&peer_clients, 1); let address = socket_addr!(128.0.0.2:8085); - let key_pair = KeyPair::generate(); + let key_pair = KeyPair::random(); let public_key = key_pair.public_key().clone(); let peer_id = PeerId::new(address, public_key); let register_peer = Register::peer(DataModelPeer::new(peer_id)); diff --git a/client/tests/integration/extra_functional/unregister_peer.rs b/client/tests/integration/extra_functional/unregister_peer.rs index 8e8d6e9ffd8..f653e07890f 100644 --- a/client/tests/integration/extra_functional/unregister_peer.rs +++ b/client/tests/integration/extra_functional/unregister_peer.rs @@ -122,7 +122,7 @@ fn init() -> Result<( .into_set_parameters(); let create_domain = Register::domain(Domain::new("domain".parse()?)); let account_id: AccountId = "account@domain".parse()?; - let (public_key, _) = KeyPair::generate().into(); + let (public_key, _) = KeyPair::random().into_parts(); let create_account = Register::account(Account::new(account_id.clone(), public_key)); let asset_definition_id: AssetDefinitionId = "xor#domain".parse()?; let create_asset = diff --git a/client/tests/integration/mod.rs b/client/tests/integration/mod.rs index c6754a553db..ac94bb4e1c5 100644 --- a/client/tests/integration/mod.rs +++ b/client/tests/integration/mod.rs @@ -26,5 +26,5 @@ mod tx_rollback; mod upgrade; fn new_account_with_random_public_key(account_id: AccountId) -> NewAccount { - Account::new(account_id, KeyPair::generate().into_raw_parts().0) + Account::new(account_id, KeyPair::random().into_parts().0) } diff --git a/client/tests/integration/multisignature_account.rs b/client/tests/integration/multisignature_account.rs index 0b8e68f4248..bdb290f0bc4 100644 --- a/client/tests/integration/multisignature_account.rs +++ b/client/tests/integration/multisignature_account.rs @@ -20,7 +20,7 @@ fn transaction_signed_by_new_signatory_of_account_should_pass() -> Result<()> { let asset_definition_id: AssetDefinitionId = "xor#wonderland".parse().expect("Valid"); let create_asset = Register::asset_definition(AssetDefinition::numeric(asset_definition_id.clone())); - let key_pair = KeyPair::generate(); + let key_pair = KeyPair::random(); let add_signatory = Mint::account_public_key(key_pair.public_key().clone(), account_id.clone()); let instructions: [InstructionBox; 2] = [create_asset.into(), add_signatory.into()]; diff --git a/client/tests/integration/multisignature_transaction.rs b/client/tests/integration/multisignature_transaction.rs index d575905dd53..d319c4178f7 100644 --- a/client/tests/integration/multisignature_transaction.rs +++ b/client/tests/integration/multisignature_transaction.rs @@ -29,7 +29,7 @@ fn multisignature_transactions_should_be_accepted_after_fully_signed() -> Result let alice_id = AccountId::from_str("alice@wonderland")?; let alice_key_pair = get_key_pair(); - let key_pair_2 = KeyPair::generate(); + let key_pair_2 = KeyPair::random(); let asset_definition_id = AssetDefinitionId::from_str("camomile#wonderland")?; let create_asset = Register::asset_definition(AssetDefinition::numeric(asset_definition_id.clone())); diff --git a/client/tests/integration/permissions.rs b/client/tests/integration/permissions.rs index 1e47977f07f..e7fea53ac18 100644 --- a/client/tests/integration/permissions.rs +++ b/client/tests/integration/permissions.rs @@ -75,7 +75,7 @@ fn permissions_disallow_asset_transfer() { let asset_definition_id: AssetDefinitionId = "xor#wonderland".parse().expect("Valid"); let create_asset = Register::asset_definition(AssetDefinition::numeric(asset_definition_id.clone())); - let mouse_keypair = KeyPair::generate(); + let mouse_keypair = KeyPair::random(); let alice_start_assets = get_assets(&iroha_client, &alice_id); iroha_client @@ -130,7 +130,7 @@ fn permissions_disallow_asset_burn() { let asset_definition_id = AssetDefinitionId::from_str("xor#wonderland").expect("Valid"); let create_asset = Register::asset_definition(AssetDefinition::numeric(asset_definition_id.clone())); - let mouse_keypair = KeyPair::generate(); + let mouse_keypair = KeyPair::random(); let alice_start_assets = get_assets(&iroha_client, &alice_id); @@ -201,7 +201,7 @@ fn permissions_differ_not_only_by_names() { let alice_id: AccountId = "alice@wonderland".parse().expect("Valid"); let mouse_id: AccountId = "mouse@outfit".parse().expect("Valid"); - let mouse_keypair = KeyPair::generate(); + let mouse_keypair = KeyPair::random(); // Registering mouse let outfit_domain: DomainId = "outfit".parse().unwrap(); @@ -305,7 +305,7 @@ fn stored_vs_granted_token_payload() -> Result<()> { let create_asset = Register::asset_definition(AssetDefinition::store(asset_definition_id.clone())); let mouse_id: AccountId = "mouse@wonderland".parse().expect("Valid"); - let mouse_keypair = KeyPair::generate(); + let mouse_keypair = KeyPair::random(); let new_mouse_account = Account::new(mouse_id.clone(), mouse_keypair.public_key().clone()); let instructions: [InstructionBox; 2] = [ Register::account(new_mouse_account).into(), diff --git a/client/tests/integration/queries/asset.rs b/client/tests/integration/queries/asset.rs index 4a8c565fda6..5ef6115078c 100644 --- a/client/tests/integration/queries/asset.rs +++ b/client/tests/integration/queries/asset.rs @@ -30,7 +30,7 @@ fn find_asset_total_quantity() -> Result<()> { "white_rabbit@looking_glass".parse()?, ]; - let keys = core::iter::repeat_with(KeyPair::generate) + let keys = core::iter::repeat_with(KeyPair::random) .take(accounts.len() - 1) .collect::>(); diff --git a/client/tests/integration/roles.rs b/client/tests/integration/roles.rs index 1f6e49f63f9..12a03f333c1 100644 --- a/client/tests/integration/roles.rs +++ b/client/tests/integration/roles.rs @@ -57,7 +57,7 @@ fn register_and_grant_role_for_metadata_access() -> Result<()> { let mouse_id = AccountId::from_str("mouse@wonderland")?; // Registering Mouse - let mouse_key_pair = KeyPair::generate(); + let mouse_key_pair = KeyPair::random(); let register_mouse = Register::account(Account::new( mouse_id.clone(), mouse_key_pair.public_key().clone(), @@ -227,7 +227,7 @@ fn grant_revoke_role_permissions() -> Result<()> { let mouse_id = AccountId::from_str("mouse@wonderland")?; // Registering Mouse - let mouse_key_pair = KeyPair::generate(); + let mouse_key_pair = KeyPair::random(); let register_mouse = Register::account(Account::new( mouse_id.clone(), mouse_key_pair.public_key().clone(), diff --git a/client/tests/integration/transfer_asset.rs b/client/tests/integration/transfer_asset.rs index d13445c9ea3..31c2750068f 100644 --- a/client/tests/integration/transfer_asset.rs +++ b/client/tests/integration/transfer_asset.rs @@ -141,6 +141,6 @@ fn generate_two_ids() -> (AccountId, AccountId) { } fn create_mouse(mouse_id: AccountId) -> Register { - let (mouse_public_key, _) = KeyPair::generate().into(); + let (mouse_public_key, _) = KeyPair::random().into_parts(); Register::account(Account::new(mouse_id, mouse_public_key)) } diff --git a/client/tests/integration/tx_chain_id.rs b/client/tests/integration/tx_chain_id.rs index 9bda1ed32b2..ebd0bb26d90 100644 --- a/client/tests/integration/tx_chain_id.rs +++ b/client/tests/integration/tx_chain_id.rs @@ -13,9 +13,9 @@ fn send_tx_with_different_chain_id() { wait_for_genesis_committed(&[test_client.clone()], 0); // Given let sender_account_id = AccountId::from_str("sender@wonderland").unwrap(); - let sender_keypair = KeyPair::generate(); + let sender_keypair = KeyPair::random(); let receiver_account_id = AccountId::from_str("receiver@wonderland").unwrap(); - let receiver_keypair = KeyPair::generate(); + let receiver_keypair = KeyPair::random(); let asset_definition_id = AssetDefinitionId::from_str("test_asset#wonderland").unwrap(); let to_transfer = numeric!(1); diff --git a/client/tests/integration/upgrade.rs b/client/tests/integration/upgrade.rs index 239f681504a..32e169b25a4 100644 --- a/client/tests/integration/upgrade.rs +++ b/client/tests/integration/upgrade.rs @@ -23,7 +23,7 @@ fn executor_upgrade_should_work() -> Result<()> { client.submit_blocking(register_admin_domain)?; let admin_id: AccountId = "admin@admin".parse()?; - let admin_keypair = KeyPair::generate(); + let admin_keypair = KeyPair::random(); let admin_account = Account::new(admin_id.clone(), admin_keypair.public_key().clone()); let register_admin_account = Register::account(admin_account); client.submit_blocking(register_admin_account)?; diff --git a/config/src/parameters/user.rs b/config/src/parameters/user.rs index 6e2a330b47e..d4e523b4732 100644 --- a/config/src/parameters/user.rs +++ b/config/src/parameters/user.rs @@ -268,7 +268,7 @@ pub(crate) fn private_key_from_env( match (algorithm, payload) { (ParseEnvResult::Value(algorithm), ParseEnvResult::Value(payload)) => { - match PrivateKey::from_hex(algorithm, &payload).wrap_err_with(|| { + match PrivateKey::from_hex(algorithm, payload).wrap_err_with(|| { eyre!( "failed to construct `{}` from `{}` and `{}` environment variables", name_base.as_ref(), @@ -643,7 +643,7 @@ mod tests { .get() .expect("private key is provided, should not fail"); - let (algorithm, payload) = private_key.to_raw(); + let (algorithm, payload) = private_key.to_bytes(); assert_eq!(algorithm, "ed25519".parse().unwrap()); assert_eq!(hex::encode(payload), "8f4c15e5d664da3f13778801d23d4e89b76e94c1b94b389544168b6cb894f84f8ba62848cf767d72e7f7f4b9d2d7ba07fee33760f79abe5597a51520e292a0cb"); } diff --git a/core/benches/blocks/apply_blocks.rs b/core/benches/blocks/apply_blocks.rs index 8a09d3e886c..c16c16fd8cb 100644 --- a/core/benches/blocks/apply_blocks.rs +++ b/core/benches/blocks/apply_blocks.rs @@ -24,7 +24,7 @@ impl WsvApplyBlocks { let accounts_per_domain = 1000; let assets_per_domain = 1000; let account_id: AccountId = "alice@wonderland".parse()?; - let key_pair = KeyPair::generate(); + let key_pair = KeyPair::random(); let wsv = build_wsv(rt, &account_id, &key_pair); let nth = 100; diff --git a/core/benches/blocks/common.rs b/core/benches/blocks/common.rs index 89cd89b043c..ef489686047 100644 --- a/core/benches/blocks/common.rs +++ b/core/benches/blocks/common.rs @@ -74,7 +74,7 @@ pub fn populate_wsv( instructions.push(can_unregister_domain.into()); for j in 0..accounts_per_domain { let account_id = construct_account_id(j, domain_id.clone()); - let account = Account::new(account_id.clone(), KeyPair::generate().into_raw_parts().0); + let account = Account::new(account_id.clone(), KeyPair::random().into_parts().0); instructions.push(Register::account(account).into()); let can_unregister_account = Grant::permission( PermissionToken::new( @@ -147,8 +147,7 @@ pub fn restore_every_nth( for j in 0..accounts_per_domain { if j % nth == 0 || i % nth == 0 { let account_id = construct_account_id(j, domain_id.clone()); - let account = - Account::new(account_id.clone(), KeyPair::generate().into_raw_parts().0); + let account = Account::new(account_id.clone(), KeyPair::random().into_parts().0); instructions.push(Register::account(account).into()); } } diff --git a/core/benches/blocks/validate_blocks.rs b/core/benches/blocks/validate_blocks.rs index 80b53e209ce..f7a5e40b1b0 100644 --- a/core/benches/blocks/validate_blocks.rs +++ b/core/benches/blocks/validate_blocks.rs @@ -27,7 +27,7 @@ impl WsvValidateBlocks { let accounts_per_domain = 1000; let assets_per_domain = 1000; let account_id: AccountId = "alice@wonderland".parse()?; - let key_pair = KeyPair::generate(); + let key_pair = KeyPair::random(); let wsv = build_wsv(rt, &account_id, &key_pair); let nth = 100; diff --git a/core/benches/kura.rs b/core/benches/kura.rs index 69e2f8ed775..7d43b24b155 100644 --- a/core/benches/kura.rs +++ b/core/benches/kura.rs @@ -26,7 +26,7 @@ async fn measure_block_size_for_n_executors(n_executors: u32) { let xor_id = AssetDefinitionId::from_str("xor#test").expect("tested"); let alice_xor_id = AssetId::new(xor_id, alice_id); let transfer = Transfer::asset_numeric(alice_xor_id, 10u32, bob_id); - let keypair = KeyPair::generate(); + let keypair = KeyPair::random(); let tx = TransactionBuilder::new( chain_id.clone(), AccountId::from_str("alice@wonderland").expect("checked"), @@ -53,10 +53,10 @@ async fn measure_block_size_for_n_executors(n_executors: u32) { let topology = Topology::new(UniqueVec::new()); let mut block = BlockBuilder::new(vec![tx], topology, Vec::new()) .chain(0, &mut wsv) - .sign(&KeyPair::generate()); + .sign(&KeyPair::random()); for _ in 1..n_executors { - block = block.sign(&KeyPair::generate()); + block = block.sign(&KeyPair::random()); } let mut block_store = BlockStore::new(dir.path(), LockStatus::Unlocked); block_store.create_files_if_they_do_not_exist().unwrap(); diff --git a/core/benches/validation.rs b/core/benches/validation.rs index 6aba606b230..814e565fce0 100644 --- a/core/benches/validation.rs +++ b/core/benches/validation.rs @@ -28,7 +28,7 @@ fn build_test_transaction(keys: &KeyPair, chain_id: ChainId) -> SignedTransactio let domain_id = DomainId::from_str(domain_name).expect("does not panic"); let create_domain: InstructionBox = Register::domain(Domain::new(domain_id)).into(); let account_name = "account"; - let (public_key, _) = KeyPair::generate().into(); + let (public_key, _) = KeyPair::random().into_parts(); let create_account = Register::account(Account::new( AccountId::new( domain_name.parse().expect("Valid"), @@ -59,7 +59,7 @@ fn build_test_transaction(keys: &KeyPair, chain_id: ChainId) -> SignedTransactio fn build_test_and_transient_wsv(keys: KeyPair) -> WorldStateView { let kura = iroha_core::kura::Kura::blank_kura_for_testing(); let query_handle = LiveQueryStore::test().start(); - let (public_key, _) = keys.into(); + let (public_key, _) = keys.into_parts(); let mut wsv = WorldStateView::new( { @@ -95,7 +95,7 @@ fn build_test_and_transient_wsv(keys: KeyPair) -> WorldStateView { fn accept_transaction(criterion: &mut Criterion) { let chain_id = ChainId::from("0"); - let keys = KeyPair::generate(); + let keys = KeyPair::random(); let transaction = build_test_transaction(&keys, chain_id.clone()); let mut success_count = 0; let mut failures_count = 0; @@ -113,9 +113,9 @@ fn accept_transaction(criterion: &mut Criterion) { fn sign_transaction(criterion: &mut Criterion) { let chain_id = ChainId::from("0"); - let keys = KeyPair::generate(); + let keys = KeyPair::random(); let transaction = build_test_transaction(&keys, chain_id); - let key_pair = KeyPair::generate(); + let key_pair = KeyPair::random(); let mut count = 0; let _ = criterion.bench_function("sign", |b| { b.iter_batched( @@ -133,7 +133,7 @@ fn sign_transaction(criterion: &mut Criterion) { fn validate_transaction(criterion: &mut Criterion) { let chain_id = ChainId::from("0"); - let keys = KeyPair::generate(); + let keys = KeyPair::random(); let transaction = AcceptedTransaction::accept( build_test_transaction(&keys, chain_id.clone()), &chain_id, @@ -159,14 +159,14 @@ fn validate_transaction(criterion: &mut Criterion) { fn sign_blocks(criterion: &mut Criterion) { let chain_id = ChainId::from("0"); - let keys = KeyPair::generate(); + let keys = KeyPair::random(); let transaction = AcceptedTransaction::accept( build_test_transaction(&keys, chain_id.clone()), &chain_id, &TRANSACTION_LIMITS, ) .expect("Failed to accept transaction."); - let key_pair = KeyPair::generate(); + let key_pair = KeyPair::random(); let kura = iroha_core::kura::Kura::blank_kura_for_testing(); let query_handle = LiveQueryStore::test().start(); let mut wsv = WorldStateView::new(World::new(), kura, query_handle); diff --git a/core/src/block.rs b/core/src/block.rs index 8b2ae4c9801..7a044a6abdc 100644 --- a/core/src/block.rs +++ b/core/src/block.rs @@ -453,7 +453,7 @@ mod valid { commit_topology: UniqueVec::new(), event_recommendations: Vec::new(), })) - .sign(&KeyPair::generate()) + .sign(&KeyPair::random()) } /// Check if block's signatures meet requirements for given topology. @@ -525,7 +525,7 @@ mod valid { #[test] fn signature_verification_ok() { - let key_pairs = core::iter::repeat_with(KeyPair::generate) + let key_pairs = core::iter::repeat_with(KeyPair::random) .take(7) .collect::>(); let mut key_pairs_iter = key_pairs.iter(); @@ -545,7 +545,7 @@ mod valid { #[test] fn signature_verification_consensus_not_required_ok() { - let key_pairs = core::iter::repeat_with(KeyPair::generate) + let key_pairs = core::iter::repeat_with(KeyPair::random) .take(1) .collect::>(); let mut key_pairs_iter = key_pairs.iter(); @@ -567,7 +567,7 @@ mod valid { /// Check requirement of having at least $2f + 1$ signatures in $3f + 1$ network #[test] fn signature_verification_not_enough_signatures() { - let key_pairs = core::iter::repeat_with(KeyPair::generate) + let key_pairs = core::iter::repeat_with(KeyPair::random) .take(7) .collect::>(); let mut key_pairs_iter = key_pairs.iter(); @@ -593,7 +593,7 @@ mod valid { /// Check requirement of having leader signature #[test] fn signature_verification_miss_proxy_tail_signature() { - let key_pairs = core::iter::repeat_with(KeyPair::generate) + let key_pairs = core::iter::repeat_with(KeyPair::random) .take(7) .collect::>(); let mut key_pairs_iter = key_pairs.iter(); @@ -697,7 +697,7 @@ mod tests { // Predefined world state let alice_id = AccountId::from_str("alice@wonderland").expect("Valid"); - let alice_keys = KeyPair::generate(); + let alice_keys = KeyPair::random(); let account = Account::new(alice_id.clone(), alice_keys.public_key().clone()).build(&alice_id); let domain_id = DomainId::from_str("wonderland").expect("Valid"); @@ -740,7 +740,7 @@ mod tests { // Predefined world state let alice_id = AccountId::from_str("alice@wonderland").expect("Valid"); - let alice_keys = KeyPair::generate(); + let alice_keys = KeyPair::random(); let account = Account::new(alice_id.clone(), alice_keys.public_key().clone()).build(&alice_id); let domain_id = DomainId::from_str("wonderland").expect("Valid"); @@ -801,7 +801,7 @@ mod tests { // Predefined world state let alice_id = AccountId::from_str("alice@wonderland").expect("Valid"); - let alice_keys = KeyPair::generate(); + let alice_keys = KeyPair::random(); let account = Account::new(alice_id.clone(), alice_keys.public_key().clone()).build(&alice_id); let domain_id = DomainId::from_str("wonderland").expect("Valid"); diff --git a/core/src/queue.rs b/core/src/queue.rs index e6740741c46..b31171e6f71 100644 --- a/core/src/queue.rs +++ b/core/src/queue.rs @@ -412,7 +412,7 @@ mod tests { #[test] async fn push_tx() { - let key_pair = KeyPair::generate(); + let key_pair = KeyPair::random(); let kura = Kura::blank_kura_for_testing(); let query_handle = LiveQueryStore::test().start(); let wsv = Arc::new(WorldStateView::new( @@ -432,7 +432,7 @@ mod tests { async fn push_tx_overflow() { let capacity = NonZeroUsize::new(10).unwrap(); - let key_pair = KeyPair::generate(); + let key_pair = KeyPair::random(); let kura = Kura::blank_kura_for_testing(); let query_handle = LiveQueryStore::test().start(); let wsv = Arc::new(WorldStateView::new( @@ -467,7 +467,7 @@ mod tests { async fn push_multisignature_tx() { let chain_id = ChainId::from("0"); - let key_pairs = [KeyPair::generate(), KeyPair::generate()]; + let key_pairs = [KeyPair::random(), KeyPair::random()]; let kura = Kura::blank_kura_for_testing(); let wsv = { let domain_id = DomainId::from_str("wonderland").expect("Valid"); @@ -530,7 +530,7 @@ mod tests { #[test] async fn get_available_txs() { let max_txs_in_block = 2; - let alice_key = KeyPair::generate(); + let alice_key = KeyPair::random(); let kura = Kura::blank_kura_for_testing(); let query_handle = LiveQueryStore::test().start(); let wsv = Arc::new(WorldStateView::new( @@ -555,7 +555,7 @@ mod tests { #[test] async fn push_tx_already_in_blockchain() { - let alice_key = KeyPair::generate(); + let alice_key = KeyPair::random(); let kura = Kura::blank_kura_for_testing(); let query_handle = LiveQueryStore::test().start(); let mut wsv = WorldStateView::new( @@ -579,7 +579,7 @@ mod tests { #[test] async fn get_tx_drop_if_in_blockchain() { let max_txs_in_block = 2; - let alice_key = KeyPair::generate(); + let alice_key = KeyPair::random(); let kura = Kura::blank_kura_for_testing(); let query_handle = LiveQueryStore::test().start(); let mut wsv = WorldStateView::new( @@ -603,7 +603,7 @@ mod tests { #[test] async fn get_available_txs_with_timeout() { let max_txs_in_block = 6; - let alice_key = KeyPair::generate(); + let alice_key = KeyPair::random(); let kura = Kura::blank_kura_for_testing(); let query_handle = LiveQueryStore::test().start(); let wsv = Arc::new(WorldStateView::new( @@ -650,7 +650,7 @@ mod tests { #[test] async fn transactions_available_after_pop() { let max_txs_in_block = 2; - let alice_key = KeyPair::generate(); + let alice_key = KeyPair::random(); let kura = Kura::blank_kura_for_testing(); let query_handle = LiveQueryStore::test().start(); let wsv = Arc::new(WorldStateView::new( @@ -684,7 +684,7 @@ mod tests { let chain_id = ChainId::from("0"); let max_txs_in_block = 2; - let alice_key = KeyPair::generate(); + let alice_key = KeyPair::random(); let kura = Kura::blank_kura_for_testing(); let query_handle = LiveQueryStore::test().start(); let wsv = Arc::new(WorldStateView::new( @@ -724,7 +724,7 @@ mod tests { #[test] async fn concurrent_stress_test() { let max_txs_in_block = 10; - let alice_key = KeyPair::generate(); + let alice_key = KeyPair::random(); let kura = Kura::blank_kura_for_testing(); let query_handle = LiveQueryStore::test().start(); let wsv = WorldStateView::new( @@ -797,7 +797,7 @@ mod tests { let future_threshold = Duration::from_secs(1); let alice_id = "alice@wonderland"; - let alice_key = KeyPair::generate(); + let alice_key = KeyPair::random(); let kura = Kura::blank_kura_for_testing(); let query_handle = LiveQueryStore::test().start(); let wsv = Arc::new(WorldStateView::new( @@ -844,8 +844,8 @@ mod tests { #[test] async fn queue_throttling() { - let alice_key_pair = KeyPair::generate(); - let bob_key_pair = KeyPair::generate(); + let alice_key_pair = KeyPair::random(); + let bob_key_pair = KeyPair::random(); let kura = Kura::blank_kura_for_testing(); let world = { let domain_id = DomainId::from_str("wonderland").expect("Valid"); diff --git a/core/src/smartcontracts/isi/mod.rs b/core/src/smartcontracts/isi/mod.rs index 41b6d702c1f..5f36bb2208c 100644 --- a/core/src/smartcontracts/isi/mod.rs +++ b/core/src/smartcontracts/isi/mod.rs @@ -217,7 +217,7 @@ mod tests { let mut wsv = WorldStateView::new(world, kura.clone(), query_handle); let genesis_account_id = AccountId::from_str("genesis@genesis")?; let account_id = AccountId::from_str("alice@wonderland")?; - let (public_key, _) = KeyPair::generate().into(); + let (public_key, _) = KeyPair::random().into_parts(); let asset_definition_id = AssetDefinitionId::from_str("rose#wonderland")?; Register::domain(Domain::new(DomainId::from_str("wonderland")?)) .execute(&genesis_account_id, &mut wsv)?; @@ -367,7 +367,7 @@ mod tests { let trigger_id = TriggerId::from_str("test_trigger_id")?; // register fake account - let (public_key, _) = KeyPair::generate().into(); + let (public_key, _) = KeyPair::random().into_parts(); let register_account = Register::account(Account::new(fake_account_id.clone(), public_key)); register_account.execute(&account_id, &mut wsv)?; diff --git a/core/src/smartcontracts/isi/query.rs b/core/src/smartcontracts/isi/query.rs index 11414202d9d..9560c23c1b5 100644 --- a/core/src/smartcontracts/isi/query.rs +++ b/core/src/smartcontracts/isi/query.rs @@ -187,7 +187,7 @@ mod tests { sumeragi::network_topology::Topology, tx::AcceptedTransaction, wsv::World, PeersIds, }; - static ALICE_KEYS: Lazy = Lazy::new(KeyPair::generate); + static ALICE_KEYS: Lazy = Lazy::new(KeyPair::random); static ALICE_ID: Lazy = Lazy::new(|| AccountId::from_str("alice@wonderland").expect("Valid")); diff --git a/core/src/smartcontracts/wasm.rs b/core/src/smartcontracts/wasm.rs index d3a1c0b374f..71ed2b8b92a 100644 --- a/core/src/smartcontracts/wasm.rs +++ b/core/src/smartcontracts/wasm.rs @@ -1651,7 +1651,7 @@ mod tests { fn world_with_test_account(authority: &AccountId) -> World { let domain_id = authority.domain_id.clone(); - let (public_key, _) = KeyPair::generate().into(); + let (public_key, _) = KeyPair::random().into_parts(); let account = Account::new(authority.clone(), public_key).build(authority); let mut domain = Domain::new(domain_id).build(authority); assert!(domain.add_account(account).is_none()); @@ -1714,7 +1714,7 @@ mod tests { let new_authority = AccountId::from_str("mad_hatter@wonderland").expect("Valid"); let register_isi = Register::account(Account::new( new_authority, - KeyPair::generate().into_raw_parts().0, + KeyPair::random().into_parts().0, )); encode_hex(InstructionBox::from(register_isi)) }; @@ -1805,7 +1805,7 @@ mod tests { let new_authority = AccountId::from_str("mad_hatter@wonderland").expect("Valid"); let register_isi = Register::account(Account::new( new_authority, - KeyPair::generate().into_raw_parts().0, + KeyPair::random().into_parts().0, )); encode_hex(InstructionBox::from(register_isi)) }; @@ -1857,7 +1857,7 @@ mod tests { let new_authority = AccountId::from_str("mad_hatter@wonderland").expect("Valid"); let register_isi = Register::account(Account::new( new_authority, - KeyPair::generate().into_raw_parts().0, + KeyPair::random().into_parts().0, )); encode_hex(InstructionBox::from(register_isi)) }; diff --git a/core/src/sumeragi/main_loop.rs b/core/src/sumeragi/main_loop.rs index 326ee461828..90a4a5bef66 100644 --- a/core/src/sumeragi/main_loop.rs +++ b/core/src/sumeragi/main_loop.rs @@ -1196,7 +1196,7 @@ mod tests { ) -> (WorldStateView, Arc, SignedBlock) { // Predefined world state let alice_id: AccountId = "alice@wonderland".parse().expect("Valid"); - let alice_keys = KeyPair::generate(); + let alice_keys = KeyPair::random(); let account = Account::new(alice_id.clone(), alice_keys.public_key().clone()).build(&alice_id); let domain_id = "wonderland".parse().expect("Valid"); @@ -1273,7 +1273,7 @@ mod tests { async fn block_sync_invalid_block() { let chain_id = ChainId::from("0"); - let leader_key_pair = KeyPair::generate(); + let leader_key_pair = KeyPair::random(); let topology = Topology::new(unique_vec![PeerId::new( "127.0.0.1:8080".parse().unwrap(), leader_key_pair.public_key().clone(), @@ -1293,7 +1293,7 @@ mod tests { async fn block_sync_invalid_soft_fork_block() { let chain_id = ChainId::from("0"); - let leader_key_pair = KeyPair::generate(); + let leader_key_pair = KeyPair::random(); let topology = Topology::new(unique_vec![PeerId::new( "127.0.0.1:8080".parse().unwrap(), leader_key_pair.public_key().clone(), @@ -1325,7 +1325,7 @@ mod tests { let chain_id = ChainId::from("0"); let topology = Topology::new(UniqueVec::new()); - let leader_key_pair = KeyPair::generate(); + let leader_key_pair = KeyPair::random(); let (finalized_wsv, _, mut block) = create_data_for_test(&chain_id, &topology, &leader_key_pair); let wsv = finalized_wsv.clone(); @@ -1351,7 +1351,7 @@ mod tests { async fn block_sync_commit_block() { let chain_id = ChainId::from("0"); - let leader_key_pair = KeyPair::generate(); + let leader_key_pair = KeyPair::random(); let topology = Topology::new(unique_vec![PeerId::new( "127.0.0.1:8080".parse().unwrap(), leader_key_pair.public_key().clone(), @@ -1367,7 +1367,7 @@ mod tests { async fn block_sync_replace_top_block() { let chain_id = ChainId::from("0"); - let leader_key_pair = KeyPair::generate(); + let leader_key_pair = KeyPair::random(); let topology = Topology::new(unique_vec![PeerId::new( "127.0.0.1:8080".parse().unwrap(), leader_key_pair.public_key().clone(), @@ -1395,7 +1395,7 @@ mod tests { async fn block_sync_small_view_change_index() { let chain_id = ChainId::from("0"); - let leader_key_pair = KeyPair::generate(); + let leader_key_pair = KeyPair::random(); let topology = Topology::new(unique_vec![PeerId::new( "127.0.0.1:8080".parse().unwrap(), leader_key_pair.public_key().clone(), @@ -1437,7 +1437,7 @@ mod tests { let chain_id = ChainId::from("0"); let topology = Topology::new(UniqueVec::new()); - let leader_key_pair = KeyPair::generate(); + let leader_key_pair = KeyPair::random(); let (finalized_wsv, _, mut block) = create_data_for_test(&chain_id, &topology, &leader_key_pair); let wsv = finalized_wsv.clone(); diff --git a/core/src/sumeragi/network_topology.rs b/core/src/sumeragi/network_topology.rs index cb8f51089b5..dfa22fd9cc5 100644 --- a/core/src/sumeragi/network_topology.rs +++ b/core/src/sumeragi/network_topology.rs @@ -280,7 +280,7 @@ pub enum Role { #[cfg(test)] macro_rules! test_peers { ($($id:literal),+$(,)?) => {{ - let mut iter = ::core::iter::repeat_with(|| KeyPair::generate()); + let mut iter = ::core::iter::repeat_with(|| KeyPair::random()); test_peers![$($id),*: iter] }}; ($($id:literal),+$(,)?: $key_pair_iter:expr) => { @@ -353,7 +353,7 @@ mod tests { #[test] fn filter_by_role() { - let key_pairs = core::iter::repeat_with(KeyPair::generate) + let key_pairs = core::iter::repeat_with(KeyPair::random) .take(7) .collect::>(); let mut key_pairs_iter = key_pairs.iter(); @@ -395,7 +395,7 @@ mod tests { #[test] fn filter_by_role_empty() { - let key_pairs = core::iter::repeat_with(KeyPair::generate) + let key_pairs = core::iter::repeat_with(KeyPair::random) .take(7) .collect::>(); let peers = UniqueVec::new(); @@ -426,7 +426,7 @@ mod tests { #[test] fn filter_by_role_1() { - let key_pairs = core::iter::repeat_with(KeyPair::generate) + let key_pairs = core::iter::repeat_with(KeyPair::random) .take(7) .collect::>(); let mut key_pairs_iter = key_pairs.iter(); @@ -459,7 +459,7 @@ mod tests { #[test] fn filter_by_role_2() { - let key_pairs = core::iter::repeat_with(KeyPair::generate) + let key_pairs = core::iter::repeat_with(KeyPair::random) .take(7) .collect::>(); let mut key_pairs_iter = key_pairs.iter(); @@ -493,7 +493,7 @@ mod tests { #[test] fn filter_by_role_3() { - let key_pairs = core::iter::repeat_with(KeyPair::generate) + let key_pairs = core::iter::repeat_with(KeyPair::random) .take(7) .collect::>(); let mut key_pairs_iter = key_pairs.iter(); diff --git a/core/test_network/src/lib.rs b/core/test_network/src/lib.rs index 128df3827b2..1d1de7ac494 100644 --- a/core/test_network/src/lib.rs +++ b/core/test_network/src/lib.rs @@ -468,7 +468,7 @@ impl Peer { /// - `api_address` /// * If keypair generation fails pub fn new() -> Result { - let key_pair = KeyPair::generate(); + let key_pair = KeyPair::random(); let p2p_address = local_unique_port()?; let api_address = local_unique_port()?; let id = PeerId::new(p2p_address.clone(), key_pair.public_key().clone()); @@ -759,7 +759,7 @@ impl TestConfig for Config { ) .merge(RootPartial::from_env(&StdEnv).expect("test env variables should parse properly")); - let (public_key, private_key) = KeyPair::generate().into(); + let (public_key, private_key) = KeyPair::random().into_parts(); layer.public_key.set(public_key); layer.private_key.set(private_key); diff --git a/crypto/Cargo.toml b/crypto/Cargo.toml index 199ad0aca6c..19c9629cdfd 100644 --- a/crypto/Cargo.toml +++ b/crypto/Cargo.toml @@ -52,14 +52,14 @@ iroha_schema = { workspace = true } derive_more = { workspace = true, features = ["deref", "deref_mut", "display"] } parity-scale-codec = { workspace = true, features = ["derive", "full"] } serde = { workspace = true, features = ["derive"] } -serde_with = { workspace = true, features = ["macros"] } +serde_with = { workspace = true, features = ["macros", "hex"] } hex = { workspace = true, features = ["alloc", "serde"] } getset = { workspace = true } thiserror = { version = "1.0.50", optional = true } displaydoc = { version = "0.2.4", default-features = false } -digest = { version = "0.10.7", default-features = false, features = ["alloc"]} +digest = { version = "0.10.7", default-features = false, features = ["alloc"] } blake2 = { version = "0.10.6", default-features = false } sha2 = { version = "0.10.8", default-features = false } hkdf = { version = "0.12.3", default-features = false } @@ -70,8 +70,8 @@ ed25519-dalek = { version = "2.1.0", default-features = false, features = ["allo curve25519-dalek = { version = "4.1.1", default-features = false } x25519-dalek = { version = "2.0.0", default-features = false, features = ["static_secrets"] } -rand = { workspace = true, default-features = false, features = ["std_rng", "alloc"]} -rand_core = { version = "0.6.4", default-features = false, features = ["alloc"]} +rand = { workspace = true, default-features = false, features = ["std_rng", "alloc"] } +rand_core = { version = "0.6.4", default-features = false, features = ["alloc"] } rand_chacha = { version = "0.3.1", default-features = false } @@ -82,11 +82,11 @@ aead = { version = "0.5.2", default-features = false, features = ["alloc"] } chacha20poly1305 = { version = "0.10.1", default-features = false } elliptic-curve = { version = "0.13.6", default-features = false } -k256 = { version = "0.13.1", default-features = false, features = ["alloc", "ecdsa", "sha256"]} +k256 = { version = "0.13.1", default-features = false, features = ["alloc", "ecdsa", "sha256"] } [dev-dependencies] hex-literal = { workspace = true } -serde_json = { workspace = true, features = ["std"]} +serde_json = { workspace = true, features = ["std"] } # these crypto libraries are not used to implement actual crypto algorithms # but to test some of the primitives against them diff --git a/crypto/src/lib.rs b/crypto/src/lib.rs index 343b1c6ac8a..f1662780479 100755 --- a/crypto/src/lib.rs +++ b/crypto/src/lib.rs @@ -32,7 +32,8 @@ pub use base64; #[cfg(not(feature = "ffi_import"))] pub use blake2; use derive_more::Display; -use error::{Error, NoSuchAlgorithm, ParseError}; +pub use error::Error; +use error::{NoSuchAlgorithm, ParseError}; use getset::Getters; pub use hash::*; use iroha_macro::ffi_impl_opaque; @@ -41,7 +42,7 @@ use iroha_schema::{Declaration, IntoSchema, MetaMap, Metadata, NamedFieldsMeta, pub use merkle::MerkleTree; #[cfg(not(feature = "ffi_import"))] use parity_scale_codec::{Decode, Encode}; -use serde::{ser::SerializeStruct, Deserialize, Serialize}; +use serde::{Deserialize, Serialize}; use serde_with::{DeserializeFromStr, SerializeDisplay}; use w3f_bls::SerializableToBytes; @@ -110,69 +111,18 @@ impl FromStr for Algorithm { } } -/// Options for key generation -#[cfg(not(feature = "ffi_import"))] -#[derive(Debug, Clone)] -pub enum KeyGenOption { +/// Key pair generation option. Passed to a specific algorithm. +#[derive(Debug)] +pub enum KeyGenOption { /// Use random number generator #[cfg(feature = "rand")] Random, /// Use seed UseSeed(Vec), - /// Derive from private key + /// Derive from a private key FromPrivateKey(K), } -ffi::ffi_item! { - /// Configuration of key generation - #[derive(Clone)] - #[cfg_attr(not(feature="ffi_import"), derive(Debug))] - pub struct KeyGenConfiguration { - /// Options - key_gen_option: KeyGenOption, - /// Algorithm - algorithm: Algorithm, - } -} - -#[ffi_impl_opaque] -impl KeyGenConfiguration { - /// Construct using random number generation with [`Ed25519`](Algorithm::Ed25519) algorithm - #[cfg(feature = "rand")] - #[must_use] - pub fn from_random() -> Self { - Self { - key_gen_option: KeyGenOption::Random, - algorithm: Algorithm::default(), - } - } - - /// Construct using seed with [`Ed25519`](Algorithm::Ed25519) algorithm - #[must_use] - pub fn from_seed(seed: Vec) -> Self { - Self { - key_gen_option: KeyGenOption::UseSeed(seed), - algorithm: Algorithm::default(), - } - } - - /// Construct using private key with [`Ed25519`](Algorithm::Ed25519) algorithm - #[must_use] - pub fn from_private_key(private_key: impl Into) -> Self { - Self { - key_gen_option: KeyGenOption::FromPrivateKey(private_key.into()), - algorithm: Algorithm::default(), - } - } - - /// With algorithm - #[must_use] - pub fn with_algorithm(mut self, algorithm: Algorithm) -> Self { - self.algorithm = algorithm; - self - } -} - ffi::ffi_item! { /// Pair of Public and Private keys. #[derive(Clone, PartialEq, Eq, Getters)] @@ -186,27 +136,63 @@ ffi::ffi_item! { } } +#[cfg(feature = "rand")] impl KeyPair { - /// Generates a pair of Public and Private key with [`Algorithm::default()`] selected as generation algorithm. - #[cfg(feature = "rand")] - pub fn generate() -> Self { - Self::generate_with_configuration( - KeyGenConfiguration::from_random().with_algorithm(Algorithm::Ed25519), + /// Generate a random key pair using a default [`Algorithm`]. + pub fn random() -> Self { + Self::random_with_algorithm(Algorithm::default()) + } + + /// Generate a random key pair + pub fn random_with_algorithm(algorithm: Algorithm) -> Self { + macro_rules! with_algorithm_variations { + ($(($alg:ident, $alg_mod:path)),+) => { + match algorithm { + $(Algorithm::$alg => <$alg_mod>::keypair(KeyGenOption::Random).into()),* + } + } + } + + with_algorithm_variations!( + (Ed25519, ed25519::Ed25519Sha512), + (Secp256k1, secp256k1::EcdsaSecp256k1Sha256), + (BlsNormal, bls::BlsNormal), + (BlsSmall, bls::BlsSmall) ) } } #[ffi_impl_opaque] impl KeyPair { + /// Derive a key pair from a seed using pRNG + pub fn from_seed(seed: Vec, algorithm: Algorithm) -> Self { + macro_rules! with_algorithm_variations { + ($(($alg:ident, $alg_mod:path)),+) => { + match algorithm { + $(Algorithm::$alg => <$alg_mod>::keypair(KeyGenOption::UseSeed(seed)).into()),* + } + } + } + + with_algorithm_variations!( + (Ed25519, ed25519::Ed25519Sha512), + (Secp256k1, secp256k1::EcdsaSecp256k1Sha256), + (BlsNormal, bls::BlsNormal), + (BlsSmall, bls::BlsSmall) + ) + } + /// Algorithm pub fn algorithm(&self) -> Algorithm { self.private_key.algorithm() } - /// Construct a [`KeyPair`] + /// Construct a [`KeyPair`]. + /// + /// See [`Self::into_parts`] for an opposite conversion. /// /// # Errors - /// If public and private key don't match, i.e. if they don't make a pair + /// If public and private keys don't match, i.e. if they don't make a pair pub fn new(public_key: PublicKey, private_key: PrivateKey) -> Result { let algorithm = private_key.algorithm(); @@ -224,26 +210,36 @@ impl KeyPair { }) } - /// Generates a pair of Public and Private key with the corresponding [`KeyGenConfiguration`]. - pub fn generate_with_configuration( - KeyGenConfiguration { - key_gen_option, - algorithm, - }: KeyGenConfiguration, - ) -> Self { - match algorithm { - Algorithm::Ed25519 => signature::ed25519::Ed25519Sha512::keypair(key_gen_option).into(), - Algorithm::Secp256k1 => { - signature::secp256k1::EcdsaSecp256k1Sha256::keypair(key_gen_option).into() + /// Get [`PublicKey`] and [`PrivateKey`] contained in the [`KeyPair`]. + /// + /// See [`Self::from_raw_parts`] for an opposite conversion. + pub fn into_parts(self) -> (PublicKey, PrivateKey) { + (self.public_key, self.private_key) + } +} + +/// Derives full [`KeyPair`] from its [`PrivateKey`] only +// TODO: consider whether to use or not a method `KeyPair::from_private_key` instead/in addition. +impl From for KeyPair { + fn from(value: PrivateKey) -> Self { + macro_rules! with_algorithm_variations { + ($(($alg:ident, $alg_mod:path)),+) => { + match *value.0 { + $( + PrivateKeyInner::$alg(secret) => { + <$alg_mod>::keypair(KeyGenOption::FromPrivateKey(secret)).into() + } + )* + } } - Algorithm::BlsNormal => signature::bls::BlsNormal::keypair(key_gen_option).into(), - Algorithm::BlsSmall => signature::bls::BlsSmall::keypair(key_gen_option).into(), } - } - /// Get [`PublicKey`] and [`PrivateKey`] contained in the [`KeyPair`]. - pub fn into_raw_parts(self) -> (PublicKey, PrivateKey) { - (self.public_key, self.private_key) + with_algorithm_variations!( + (Ed25519, ed25519::Ed25519Sha512), + (Secp256k1, secp256k1::EcdsaSecp256k1Sha256), + (BlsNormal, bls::BlsNormal), + (BlsSmall, bls::BlsSmall) + ) } } @@ -305,14 +301,6 @@ impl<'de> Deserialize<'de> for KeyPair { } } -// TODO: enable in ffi_import? -#[cfg(not(feature = "ffi_import"))] -impl From for (PublicKey, PrivateKey) { - fn from(key_pair: KeyPair) -> Self { - key_pair.into_raw_parts() - } -} - #[derive(Clone, PartialEq, Eq)] #[cfg_attr( not(feature = "ffi_import"), @@ -396,7 +384,26 @@ impl PublicKeyInner { } ffi::ffi_item! { - /// Public Key used in signatures. + /// Public key used in signatures. + /// + /// Its serialized form ([`Serialize`], [`Deserialize`], [`Display`], [`FromStr`]) is + /// represented as a [multihash](https://www.multiformats.io/multihash/) string. + /// For example: + /// + /// ``` + /// use iroha_crypto::{PublicKey, Algorithm}; + /// + /// let key = PublicKey::from_hex( + /// Algorithm::Ed25519, + /// "1509A611AD6D97B01D871E58ED00C8FD7C3917B6CA61A8C2833A19E000AAC2E4", + /// ) + /// .unwrap(); + /// + /// assert_eq!( + /// format!("{key}"), + /// "ed01201509A611AD6D97B01D871E58ED00C8FD7C3917B6CA61A8C2833A19E000AAC2E4" + /// ); + /// ``` #[derive(Debug, Clone, PartialEq, Eq, TypeId)] #[cfg_attr(not(feature="ffi_import"), derive(Deserialize, Serialize, derive_more::Display))] #[cfg_attr(not(feature="ffi_import"), display(fmt = "{_0}"))] @@ -412,7 +419,7 @@ impl PublicKey { /// # Errors /// /// Fails if public key parsing fails - pub fn from_raw(algorithm: Algorithm, payload: &[u8]) -> Result { + pub fn from_bytes(algorithm: Algorithm, payload: &[u8]) -> Result { match algorithm { Algorithm::Ed25519 => { ed25519::Ed25519Sha512::parse_public_key(payload).map(PublicKeyInner::Ed25519) @@ -430,23 +437,24 @@ impl PublicKey { .map(PublicKey) } - /// Extracts the raw bytes from public key, copying the payload. + /// Extracts raw bytes from the public key, copying the payload. /// - /// `into_raw()` without copying is not provided because underlying crypto + /// `into_bytes()` without copying is not provided because underlying crypto /// libraries do not provide move functionality. - pub fn to_raw(&self) -> (Algorithm, Vec) { + pub fn to_bytes(&self) -> (Algorithm, Vec) { self.0.to_raw() } - /// Construct [`PublicKey`] from hex encoded string + /// Construct from hex encoded string. A shorthand over [`Self::from_bytes`]. + /// /// # Errors /// /// - If the given payload is not hex encoded /// - If the given payload is not a valid private key - pub fn from_hex(algorithm: Algorithm, payload: &str) -> Result { - let payload = hex_decode(payload)?; + pub fn from_hex(algorithm: Algorithm, payload: impl AsRef) -> Result { + let payload = hex_decode(payload.as_ref())?; - Self::from_raw(algorithm, &payload) + Self::from_bytes(algorithm, &payload) } /// Get the digital signature algorithm of the public key @@ -458,7 +466,7 @@ impl PublicKey { #[cfg(not(feature = "ffi_import"))] impl core::hash::Hash for PublicKey { fn hash(&self, state: &mut H) { - (self.to_raw()).hash(state) + (self.to_bytes()).hash(state) } } @@ -470,18 +478,18 @@ impl PartialOrd for PublicKey { impl Ord for PublicKey { fn cmp(&self, other: &Self) -> core::cmp::Ordering { - self.to_raw().cmp(&other.to_raw()) + self.to_bytes().cmp(&other.to_bytes()) } } #[cfg(not(feature = "ffi_import"))] impl Encode for PublicKey { fn size_hint(&self) -> usize { - self.to_raw().size_hint() + self.to_bytes().size_hint() } fn encode_to(&self, dest: &mut W) { - self.to_raw().encode_to(dest); + self.to_bytes().encode_to(dest); } } @@ -492,7 +500,7 @@ impl Decode for PublicKey { ) -> Result { let algorithm = Algorithm::decode(input)?; let payload = Vec::decode(input)?; - Self::from_raw(algorithm, &payload).map_err(|_| { + Self::from_bytes(algorithm, &payload).map_err(|_| { parity_scale_codec::Error::from( "Failed to construct public key from digest function and payload", ) @@ -543,24 +551,27 @@ impl FromStr for PublicKey { #[cfg(not(feature = "ffi_import"))] impl From for PublicKey { fn from(private_key: PrivateKey) -> Self { - let algorithm = private_key.algorithm(); - let key_gen_option = KeyGenOption::FromPrivateKey(private_key); - - let inner = match algorithm { - Algorithm::Ed25519 => { - PublicKeyInner::Ed25519(ed25519::Ed25519Sha512::keypair(key_gen_option).0) - } - Algorithm::Secp256k1 => PublicKeyInner::Secp256k1( - secp256k1::EcdsaSecp256k1Sha256::keypair(key_gen_option).0, - ), - Algorithm::BlsNormal => { - PublicKeyInner::BlsNormal(bls::BlsNormal::keypair(key_gen_option).0) - } - Algorithm::BlsSmall => { - PublicKeyInner::BlsSmall(bls::BlsSmall::keypair(key_gen_option).0) + macro_rules! with_algorithm_variations { + ($private_inner:expr, $(($alg:ident, $alg_mod:path)),+) => { + match $private_inner { + $( + PrivateKeyInner::$alg(secret) => { + PublicKeyInner::$alg(<$alg_mod>::keypair(KeyGenOption::FromPrivateKey(secret)).0) + } + )* + } } - }; - PublicKey(Box::new(inner)) + } + + let inner = with_algorithm_variations!( + *private_key.0, + (Ed25519, ed25519::Ed25519Sha512), + (Secp256k1, secp256k1::EcdsaSecp256k1Sha256), + (BlsNormal, bls::BlsNormal), + (BlsSmall, bls::BlsSmall) + ); + + Self(Box::new(inner)) } } @@ -575,9 +586,10 @@ enum PrivateKeyInner { ffi::ffi_item! { /// Private Key used in signatures. - #[derive(Clone)] + #[derive(Clone, Serialize, Deserialize)] #[cfg_attr(all(feature = "ffi_export", not(feature = "ffi_import")), ffi_type(opaque))] #[allow(missing_docs, variant_size_differences)] + #[serde(into = "PrivateKeySerialized", try_from = "PrivateKeySerialized")] pub struct PrivateKey(Box); } @@ -605,7 +617,7 @@ impl PrivateKey { /// # Errors /// /// - If the given payload is not a valid private key for the given digest function - pub fn from_raw(algorithm: Algorithm, payload: &[u8]) -> Result { + pub fn from_bytes(algorithm: Algorithm, payload: &[u8]) -> Result { match algorithm { Algorithm::Ed25519 => { ed25519::Ed25519Sha512::parse_private_key(payload).map(PrivateKeyInner::Ed25519) @@ -623,16 +635,17 @@ impl PrivateKey { .map(PrivateKey) } - /// Construct [`PrivateKey`] from hex encoded string + /// Construct [`PrivateKey`] from hex encoded string. + /// A shorthand over [`PrivateKey::from_bytes`] /// /// # Errors /// /// - If the given payload is not hex encoded /// - If the given payload is not a valid private key - pub fn from_hex(algorithm: Algorithm, payload: &str) -> Result { - let payload = hex_decode(payload)?; + pub fn from_hex(algorithm: Algorithm, payload: impl AsRef) -> Result { + let payload = hex_decode(payload.as_ref())?; - Self::from_raw(algorithm, &payload) + Self::from_bytes(algorithm, &payload) } /// Get the digital signature algorithm of the private key @@ -657,9 +670,9 @@ impl PrivateKey { /// Extracts the raw bytes from the private key, copying the payload. /// - /// `into_raw()` without copying is not provided because underlying crypto + /// `into_bytes()` without copying is not provided because underlying crypto /// libraries do not provide move functionality. - pub fn to_raw(&self) -> (Algorithm, Vec) { + pub fn to_bytes(&self) -> (Algorithm, Vec) { (self.algorithm(), self.payload()) } } @@ -680,33 +693,28 @@ impl core::fmt::Display for PrivateKey { } } -#[cfg(not(feature = "ffi_import"))] -impl Serialize for PrivateKey { - fn serialize(&self, serializer: S) -> Result { - let mut state = serializer.serialize_struct("PublicKey", 2)?; - state.serialize_field("algorithm", &self.algorithm())?; - state.serialize_field("payload", &hex::encode(self.payload()))?; - state.end() - } +#[serde_with::serde_as] +#[derive(Serialize, Deserialize)] +struct PrivateKeySerialized { + algorithm: Algorithm, + #[serde_as(as = "serde_with::hex::Hex")] + payload: Vec, } -impl<'de> Deserialize<'de> for PrivateKey { - fn deserialize(deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { - use serde::de::Error as _; +impl TryFrom for PrivateKey { + type Error = ParseError; - #[derive(Deserialize)] - struct PrivateKeyCandidate { - algorithm: Algorithm, - payload: String, - } + fn try_from(value: PrivateKeySerialized) -> Result { + Self::from_bytes(value.algorithm, &value.payload) + } +} - // NOTE: Verify that private key is valid - let private_key = PrivateKeyCandidate::deserialize(deserializer)?; - Self::from_hex(private_key.algorithm, private_key.payload.as_ref()) - .map_err(D::Error::custom) +impl From for PrivateKeySerialized { + fn from(value: PrivateKey) -> Self { + Self { + algorithm: value.algorithm(), + payload: value.payload(), + } } } @@ -818,7 +826,6 @@ mod ffi { #[cfg(any(feature = "ffi_export", feature = "ffi_import"))] iroha_ffi::handles! { - KeyGenConfiguration, PublicKey, PrivateKey, KeyPair, @@ -829,8 +836,8 @@ mod ffi { iroha_ffi::decl_ffi_fns! { link_prefix="iroha_crypto" Drop, Clone, Eq, Ord, Default } #[cfg(all(feature = "ffi_export", not(feature = "ffi_import")))] iroha_ffi::def_ffi_fns! { link_prefix="iroha_crypto" - Drop: { KeyGenConfiguration, PublicKey, PrivateKey, KeyPair, Signature }, - Clone: { KeyGenConfiguration, PublicKey, PrivateKey, KeyPair, Signature }, + Drop: { PublicKey, PrivateKey, KeyPair, Signature }, + Clone: { PublicKey, PrivateKey, KeyPair, Signature }, Eq: { PublicKey, PrivateKey, KeyPair, Signature }, Ord: { PublicKey, Signature }, } @@ -850,7 +857,7 @@ mod ffi { pub(crate) use ffi_item; } -/// The prelude re-exports most commonly used traits, structs and macros from this crate. +/// The prelude re-exports most commonly used items from this crate. pub mod prelude { pub use super::{Algorithm, Hash, KeyPair, PrivateKey, PublicKey, Signature}; } @@ -890,9 +897,7 @@ mod tests { Algorithm::BlsNormal, Algorithm::BlsSmall, ] { - let key_pair = KeyPair::generate_with_configuration( - KeyGenConfiguration::from_random().with_algorithm(algorithm), - ); + let key_pair = KeyPair::random_with_algorithm(algorithm); assert_eq!( key_pair, @@ -928,7 +933,7 @@ mod tests { KeyPair::new("ed012059C8A4DA1EBB5380F74ABA51F502714652FDCCE9611FAFB9904E4A3C4D382774" .parse() .expect("Public key not in mulithash format"), - PrivateKey::from_hex( + PrivateKey::from_hex( Algorithm::Ed25519, "93CA389FC2979F3F7D2A7F8B76C70DE6D5EAF5FA58D4F93CB8B0FB298D398ACC59C8A4DA1EBB5380F74ABA51F502714652FDCCE9611FAFB9904E4A3C4D382774" ).expect("Private key not hex encoded")).unwrap(); @@ -936,7 +941,7 @@ mod tests { KeyPair::new("ea01309060D021340617E9554CCBC2CF3CC3DB922A9BA323ABDF7C271FCC6EF69BE7A8DEBCA7D9E96C0F0089ABA22CDAADE4A2" .parse() .expect("Public key not in multihash format"), - PrivateKey::from_hex( + PrivateKey::from_hex( Algorithm::BlsNormal, "1ca347641228c3b79aa43839dedc85fa51c0e8b9b6a00f6b0d6b0423e902973f", ).expect("Private key not hex encoded")).unwrap(); @@ -951,10 +956,8 @@ mod tests { Algorithm::BlsNormal, Algorithm::BlsSmall, ] { - let key_pair = KeyPair::generate_with_configuration( - KeyGenConfiguration::from_random().with_algorithm(algorithm), - ); - let (public_key, _) = key_pair.into(); + let key_pair = KeyPair::random_with_algorithm(algorithm); + let (public_key, _) = key_pair.into_parts(); let encoded_public_key = public_key.encode(); @@ -987,7 +990,7 @@ mod tests { KeyPair::new("ed012059C8A4DA1EBB5380F74ABA51F502714652FDCCE9611FAFB9904E4A3C4D382774" .parse() .expect("Public key not in mulithash format"), - PrivateKey::from_hex( + PrivateKey::from_hex( Algorithm::Ed25519, "3A7991AF1ABB77F3FD27CC148404A6AE4439D095A63591B77C788D53F708A02A1509A611AD6D97B01D871E58ED00C8FD7C3917B6CA61A8C2833A19E000AAC2E4" ).expect("Private key not valid")).unwrap_err(); @@ -995,7 +998,7 @@ mod tests { KeyPair::new("ea01309060D021340617E9554CCBC2CF3CC3DB922A9BA323ABDF7C271FCC6EF69BE7A8DEBCA7D9E96C0F0089ABA22CDAADE4A2" .parse() .expect("Public key not in mulithash format"), - PrivateKey::from_hex( + PrivateKey::from_hex( Algorithm::BlsNormal, "CC176E44C41AA144FD1BEE4E0BCD2EF43F06D0C7BC2988E89A799951D240E503", ).expect("Private key not valid")).unwrap_err(); @@ -1075,7 +1078,7 @@ mod tests { "public_key": "ed01201509A611AD6D97B01D871E58ED00C8FD7C3917B6CA61A8C2833A19E000AAC2E4", "private_key": { "algorithm": "ed25519", - "payload": "3a7991af1abb77f3fd27cc148404a6ae4439d095a63591b77c788d53f708a02a1509a611ad6d97b01d871e58ed00c8fd7c3917b6ca61a8c2833a19e000aac2e4" + "payload": "3A7991AF1ABB77F3FD27CC148404A6AE4439D095A63591B77C788D53F708A02A1509A611AD6D97B01D871E58ED00C8FD7C3917B6CA61A8C2833A19E000AAC2E4" } }), TestJson { @@ -1099,7 +1102,7 @@ mod tests { "public_key": "e701210312273E8810581E58948D3FB8F9E8AD53AAA21492EBB8703915BBB565A21B7FCC", "private_key": { "algorithm": "secp256k1", - "payload": "4df4fca10762d4b529fe40a2188a60ca4469d2c50a825b5f33adc2cb78c69445" + "payload": "4DF4FCA10762D4B529FE40A2188A60CA4469D2C50A825B5F33ADC2CB78C69445" } }), TestJson { @@ -1125,7 +1128,7 @@ mod tests { "public_key": "ea01309060D021340617E9554CCBC2CF3CC3DB922A9BA323ABDF7C271FCC6EF69BE7A8DEBCA7D9E96C0F0089ABA22CDAADE4A2", "private_key": { "algorithm": "bls_normal", - "payload": "1ca347641228c3b79aa43839dedc85fa51c0e8b9b6a00f6b0d6b0423e902973f" + "payload": "1CA347641228C3B79AA43839DEDC85FA51C0E8B9B6A00F6B0D6B0423E902973F" } }), TestJson { @@ -1144,7 +1147,7 @@ mod tests { "public_key": "eb01609051D4A9C69402423413EBBA4C00BC82A0102AA2B783057BD7BCEE4DD17B37DE5D719EE84BE43783F2AE47A673A74B8315DD3E595ED1FBDFAC17DA1D7A36F642B423ED18275FAFD671B1D331439D22F12FB6EB436A47E8656F182A78DF29D310", "private_key": { "algorithm": "bls_small", - "payload": "8cb95072914cdd8e4cf682fdbe1189cdf4fc54d445e760b3446f896dbdbf5b2b" + "payload": "8CB95072914CDD8E4CF682FDBE1189CDF4FC54D445E760B3446F896DBDBF5B2B" } }), TestJson { diff --git a/crypto/src/multihash.rs b/crypto/src/multihash.rs index a2c8281b134..a7400063f00 100644 --- a/crypto/src/multihash.rs +++ b/crypto/src/multihash.rs @@ -151,7 +151,7 @@ impl TryFrom> for Multihash { } let payload = ConstVec::new(payload); - Ok(Self::from(*PublicKey::from_raw(algorithm, &payload)?.0)) + Ok(Self::from(*PublicKey::from_bytes(algorithm, &payload)?.0)) } } @@ -221,7 +221,7 @@ mod tests { #[test] fn multihash_to_bytes() { let multihash = Multihash( - *PublicKey::from_raw( + *PublicKey::from_bytes( Algorithm::Ed25519, &hex_decode("1509A611AD6D97B01D871E58ED00C8FD7C3917B6CA61A8C2833A19E000AAC2E4") .unwrap(), @@ -240,7 +240,7 @@ mod tests { #[test] fn multihash_from_bytes() { let multihash = Multihash( - *PublicKey::from_raw( + *PublicKey::from_bytes( Algorithm::Ed25519, &hex_decode("1509A611AD6D97B01D871E58ED00C8FD7C3917B6CA61A8C2833A19E000AAC2E4") .unwrap(), diff --git a/crypto/src/signature/bls/implementation.rs b/crypto/src/signature/bls/implementation.rs index 86156e66327..db12726b263 100644 --- a/crypto/src/signature/bls/implementation.rs +++ b/crypto/src/signature/bls/implementation.rs @@ -17,8 +17,6 @@ use crate::{Algorithm, Error, KeyGenOption, ParseError}; pub trait BlsConfiguration { const ALGORITHM: Algorithm; type Engine: w3f_bls::EngineBLS; - - fn extract_private_key(private_key: &crate::PrivateKey) -> Option<&SecretKey>; } pub struct BlsImpl(PhantomData); @@ -26,7 +24,9 @@ pub struct BlsImpl(PhantomData); impl BlsImpl { // the names are from an RFC, not a good idea to change them #[allow(clippy::similar_names)] - pub fn keypair(mut option: KeyGenOption) -> (PublicKey, SecretKey) { + pub fn keypair( + mut option: KeyGenOption>, + ) -> (PublicKey, SecretKey) { let private_key = match option { #[cfg(feature = "rand")] KeyGenOption::Random => SecretKey::generate(OsRng), @@ -44,14 +44,7 @@ impl BlsImpl { SecretKey::::from_seed(&okm) } - KeyGenOption::FromPrivateKey(ref key) => C::extract_private_key(key) - .unwrap_or_else(|| { - panic!( - "Wrong private key type for {} algorithm, got {key:?}", - C::ALGORITHM, - ) - }) - .clone(), + KeyGenOption::FromPrivateKey(ref key) => key.clone(), }; (private_key.into_public(), private_key) } diff --git a/crypto/src/signature/bls/mod.rs b/crypto/src/signature/bls/mod.rs index 8a69a3dd7a5..f8949073c76 100644 --- a/crypto/src/signature/bls/mod.rs +++ b/crypto/src/signature/bls/mod.rs @@ -14,8 +14,6 @@ mod implementation; /// with the public key group in G1 and signature group in G2. /// 192 byte signatures and 97 byte public keys mod normal { - use core::borrow::Borrow as _; - use super::{implementation, implementation::BlsConfiguration}; use crate::Algorithm; @@ -26,14 +24,6 @@ mod normal { const ALGORITHM: Algorithm = Algorithm::BlsNormal; type Engine = w3f_bls::ZBLS; - - fn extract_private_key(private_key: &crate::PrivateKey) -> Option<&NormalPrivateKey> { - if let crate::PrivateKeyInner::BlsNormal(key) = private_key.0.borrow() { - Some(key) - } else { - None - } - } } pub type NormalBls = implementation::BlsImpl; @@ -48,8 +38,6 @@ mod normal { /// /// This is good for situations where space is a consideration and verification is infrequent. mod small { - use core::borrow::Borrow as _; - use super::implementation::{self, BlsConfiguration}; use crate::Algorithm; @@ -59,14 +47,6 @@ mod small { const ALGORITHM: Algorithm = Algorithm::BlsSmall; type Engine = w3f_bls::TinyBLS381; - - fn extract_private_key(private_key: &crate::PrivateKey) -> Option<&SmallPrivateKey> { - if let crate::PrivateKeyInner::BlsSmall(key) = private_key.0.borrow() { - Some(key) - } else { - None - } - } } pub type SmallBls = implementation::BlsImpl; diff --git a/crypto/src/signature/ed25519.rs b/crypto/src/signature/ed25519.rs index 46ed5291fe7..3ab7ab4ab26 100644 --- a/crypto/src/signature/ed25519.rs +++ b/crypto/src/signature/ed25519.rs @@ -1,4 +1,4 @@ -use core::{borrow::Borrow as _, convert::TryFrom}; +use core::convert::TryFrom; use ed25519_dalek::Signature; #[cfg(feature = "rand")] @@ -17,17 +17,12 @@ use alloc::{string::ToString as _, vec::Vec}; pub struct Ed25519Sha512; impl Ed25519Sha512 { - pub fn keypair(option: KeyGenOption) -> (PublicKey, PrivateKey) { + pub fn keypair(option: KeyGenOption) -> (PublicKey, PrivateKey) { let signing_key = match option { #[cfg(feature = "rand")] KeyGenOption::Random => PrivateKey::generate(&mut OsRng), KeyGenOption::UseSeed(seed) => PrivateKey::generate(&mut super::rng_from_seed(seed)), - KeyGenOption::FromPrivateKey(ref s) => { - let crate::PrivateKeyInner::Ed25519(s) = s.0.borrow() else { - panic!("Wrong private key type, expected `Ed25519`, got {s:?}") - }; - PrivateKey::clone(s) - } + KeyGenOption::FromPrivateKey(ref s) => PrivateKey::clone(s), }; (signing_key.verifying_key(), signing_key) } @@ -64,13 +59,19 @@ mod test { use self::Ed25519Sha512; use super::*; - use crate::{Algorithm, KeyGenOption, PrivateKey, PublicKey}; + use crate::{signature::ed25519, Algorithm, KeyGenOption, PrivateKey, PublicKey}; const MESSAGE_1: &[u8] = b"This is a dummy message for use with tests"; const SIGNATURE_1: &str = "451b5b8e8725321541954997781de51f4142e4a56bab68d24f6a6b92615de5eefb74134138315859a32c7cf5fe5a488bc545e2e08e5eedfd1fb10188d532d808"; const PRIVATE_KEY: &str = "1c1179a560d092b90458fe6ab8291215a427fcd6b3927cb240701778ef55201927c96646f2d4632d4fc241f84cbc427fbc3ecaa95becba55088d6c7b81fc5bbf"; const PUBLIC_KEY: &str = "27c96646f2d4632d4fc241f84cbc427fbc3ecaa95becba55088d6c7b81fc5bbf"; + fn key_pair_factory() -> (ed25519::PublicKey, ed25519::PrivateKey) { + Ed25519Sha512::keypair(KeyGenOption::FromPrivateKey( + Ed25519Sha512::parse_private_key(&hex::decode(PRIVATE_KEY).unwrap()).unwrap(), + )) + } + #[test] #[ignore] fn create_new_keys() { @@ -82,8 +83,7 @@ mod test { #[test] fn ed25519_load_keys() { - let secret = PrivateKey::from_hex(Algorithm::Ed25519, PRIVATE_KEY).unwrap(); - let (p1, s1) = Ed25519Sha512::keypair(KeyGenOption::FromPrivateKey(secret)); + let (p1, s1) = key_pair_factory(); assert_eq!( PrivateKey(Box::new(crate::PrivateKeyInner::Ed25519(s1))), @@ -97,8 +97,7 @@ mod test { #[test] fn ed25519_verify() { - let secret = PrivateKey::from_hex(Algorithm::Ed25519, PRIVATE_KEY).unwrap(); - let (p, _) = Ed25519Sha512::keypair(KeyGenOption::FromPrivateKey(secret)); + let (p, _) = key_pair_factory(); Ed25519Sha512::verify(MESSAGE_1, hex::decode(SIGNATURE_1).unwrap().as_slice(), &p).unwrap(); @@ -118,8 +117,7 @@ mod test { #[test] fn ed25519_sign() { - let secret = PrivateKey::from_hex(Algorithm::Ed25519, PRIVATE_KEY).unwrap(); - let (p, s) = Ed25519Sha512::keypair(KeyGenOption::FromPrivateKey(secret)); + let (p, s) = key_pair_factory(); let sig = Ed25519Sha512::sign(MESSAGE_1, &s); Ed25519Sha512::verify(MESSAGE_1, &sig, &p).unwrap(); diff --git a/crypto/src/signature/mod.rs b/crypto/src/signature/mod.rs index e99b90239be..b22eac891a7 100644 --- a/crypto/src/signature/mod.rs +++ b/crypto/src/signature/mod.rs @@ -30,7 +30,7 @@ use serde::{Deserialize, Serialize}; use sha2::Digest as _; use zeroize::Zeroize as _; -use crate::{ffi, Error, HashOf, KeyPair, PublicKey}; +use crate::{error::ParseError, ffi, hex_decode, Error, HashOf, KeyPair, PublicKey}; /// Construct cryptographic RNG from seed. fn rng_from_seed(mut seed: Vec) -> impl CryptoRngCore { @@ -40,7 +40,8 @@ fn rng_from_seed(mut seed: Vec) -> impl CryptoRngCore { } ffi::ffi_item! { - /// Represents signature of the data (`Block` or `Transaction` for example). + /// Represents a signature of the data (`Block` or `Transaction` for example). + #[serde_with::serde_as] #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, getset::Getters)] #[cfg_attr(not(feature="ffi_import"), derive(derive_more::DebugCustom, Hash, Decode, Encode, Deserialize, Serialize, IntoSchema))] #[cfg_attr(not(feature="ffi_import"), debug( @@ -53,20 +54,18 @@ ffi::ffi_item! { #[getset(get = "pub")] public_key: PublicKey, /// Signature payload - payload: ConstVec, + #[serde_as(as = "serde_with::hex::Hex")] + payload: ConstVec, } } impl Signature { - /// Key payload + /// Access the signature's payload pub fn payload(&self) -> &[u8] { self.payload.as_ref() } - /// Creates new [`Signature`] by signing payload via [`KeyPair::private_key`]. - /// - /// # Errors - /// Fails if signing fails + /// Creates new signature by signing payload via [`KeyPair::private_key`]. pub fn new(key_pair: &KeyPair, payload: &[u8]) -> Self { let signature = match key_pair.private_key.0.borrow() { crate::PrivateKeyInner::Ed25519(sk) => ed25519::Ed25519Sha512::sign(payload, sk), @@ -82,10 +81,32 @@ impl Signature { } } + /// Creates new signature from its raw payload and public key. + /// + /// **This method does not sign the payload.** Use [`Signature::new`] for this purpose. + /// + /// This method exists to allow reproducing the signature in a more efficient way than through + /// deserialization. + pub fn from_bytes(public_key: PublicKey, payload: &[u8]) -> Self { + Self { + public_key, + payload: ConstVec::new(payload), + } + } + + /// A shorthand for [`Self::from_bytes`] accepting payload as hex. + /// + /// # Errors + /// If passed string is not a valid hex. + pub fn from_hex(public_key: PublicKey, payload: impl AsRef) -> Result { + let payload: Vec = hex_decode(payload.as_ref())?; + Ok(Self::from_bytes(public_key, &payload)) + } + /// Verify `payload` using signed data and [`KeyPair::public_key`]. /// /// # Errors - /// Fails if message didn't pass verification + /// Fails if the message doesn't pass verification pub fn verify(&self, payload: &[u8]) -> Result<(), Error> { match self.public_key.0.borrow() { crate::PublicKeyInner::Ed25519(pk) => { @@ -537,61 +558,57 @@ impl std::error::Error for SignatureVerificationFail {} #[cfg(test)] mod tests { + use core::str::FromStr; + + use serde_json::json; + use super::*; - use crate::KeyGenConfiguration; + use crate::Algorithm; #[test] #[cfg(feature = "rand")] fn create_signature_ed25519() { - let key_pair = KeyPair::generate_with_configuration( - KeyGenConfiguration::from_random().with_algorithm(crate::Algorithm::Ed25519), - ); + let key_pair = KeyPair::random_with_algorithm(crate::Algorithm::Ed25519); let message = b"Test message to sign."; let signature = Signature::new(&key_pair, message); - assert!(*signature.public_key() == *key_pair.public_key()); + assert_eq!(*signature.public_key(), *key_pair.public_key()); signature.verify(message).unwrap(); } #[test] #[cfg(feature = "rand")] fn create_signature_secp256k1() { - let key_pair = KeyPair::generate_with_configuration( - KeyGenConfiguration::from_random().with_algorithm(crate::Algorithm::Secp256k1), - ); + let key_pair = KeyPair::random_with_algorithm(Algorithm::Secp256k1); let message = b"Test message to sign."; let signature = Signature::new(&key_pair, message); - assert!(*signature.public_key() == *key_pair.public_key()); + assert_eq!(*signature.public_key(), *key_pair.public_key()); signature.verify(message).unwrap(); } #[test] #[cfg(feature = "rand")] fn create_signature_bls_normal() { - let key_pair = KeyPair::generate_with_configuration( - KeyGenConfiguration::from_random().with_algorithm(crate::Algorithm::BlsNormal), - ); + let key_pair = KeyPair::random_with_algorithm(Algorithm::BlsNormal); let message = b"Test message to sign."; let signature = Signature::new(&key_pair, message); - assert!(*signature.public_key() == *key_pair.public_key()); + assert_eq!(*signature.public_key(), *key_pair.public_key()); signature.verify(message).unwrap(); } #[test] #[cfg(all(feature = "rand", any(feature = "std", feature = "ffi_import")))] fn create_signature_bls_small() { - let key_pair = KeyPair::generate_with_configuration( - KeyGenConfiguration::from_random().with_algorithm(crate::Algorithm::BlsSmall), - ); + let key_pair = KeyPair::random_with_algorithm(Algorithm::BlsSmall); let message = b"Test message to sign."; let signature = Signature::new(&key_pair, message); - assert!(*signature.public_key() == *key_pair.public_key()); + assert_eq!(*signature.public_key(), *key_pair.public_key()); signature.verify(message).unwrap(); } #[test] #[cfg(all(feature = "rand", not(feature = "ffi_import")))] fn signatures_of_deduplication_by_public_key() { - let key_pair = KeyPair::generate(); + let key_pair = KeyPair::random(); let signatures = [ SignatureOf::new(&key_pair, &1), SignatureOf::new(&key_pair, &2), @@ -610,7 +627,7 @@ mod tests { let keys = 5; let signatures_per_key = 10; - let signatures = core::iter::repeat_with(KeyPair::generate) + let signatures = core::iter::repeat_with(KeyPair::random) .take(keys) .flat_map(|key| { core::iter::repeat_with(move || key.clone()) @@ -633,4 +650,27 @@ mod tests { } // From the above we can conclude that `SignatureWrapperOf` have consistent behavior for `HashSet` and `BTreeSet` } + + #[test] + fn signature_serialized_representation() { + let input = json!({ + "public_key": "e701210312273E8810581E58948D3FB8F9E8AD53AAA21492EBB8703915BBB565A21B7FCC", + "payload": "3A7991AF1ABB77F3FD27CC148404A6AE4439D095A63591B77C788D53F708A02A1509A611AD6D97B01D871E58ED00C8FD7C3917B6CA61A8C2833A19E000AAC2E4" + }); + + let signature: Signature = serde_json::from_value(input.clone()).unwrap(); + + assert_eq!(serde_json::to_value(signature).unwrap(), input); + } + + #[test] + fn signature_from_hex_simply_reproduces_the_data() { + let public_key = "e701210312273E8810581E58948D3FB8F9E8AD53AAA21492EBB8703915BBB565A21B7FCC"; + let payload = "3a7991af1abb77f3fd27cc148404a6ae4439d095a63591b77c788d53f708a02a1509a611ad6d97b01d871e58ed00c8fd7c3917b6ca61a8c2833a19e000aac2e4"; + + let value = Signature::from_hex(PublicKey::from_str(public_key).unwrap(), payload).unwrap(); + + assert_eq!(value.public_key().to_string(), public_key); + assert_eq!(value.payload(), hex::decode(payload).unwrap()); + } } diff --git a/crypto/src/signature/secp256k1.rs b/crypto/src/signature/secp256k1.rs index fc84c4adac2..c1522f7a72a 100644 --- a/crypto/src/signature/secp256k1.rs +++ b/crypto/src/signature/secp256k1.rs @@ -10,7 +10,7 @@ pub type PublicKey = k256::PublicKey; pub type PrivateKey = k256::SecretKey; impl EcdsaSecp256k1Sha256 { - pub fn keypair(option: KeyGenOption) -> (PublicKey, PrivateKey) { + pub fn keypair(option: KeyGenOption) -> (PublicKey, PrivateKey) { EcdsaSecp256k1Impl::keypair(option) } @@ -34,7 +34,6 @@ impl EcdsaSecp256k1Sha256 { mod ecdsa_secp256k1 { #[cfg(not(feature = "std"))] use alloc::{format, string::ToString as _, vec::Vec}; - use core::borrow::Borrow; #[cfg(feature = "rand")] use rand::rngs::OsRng; @@ -46,19 +45,14 @@ mod ecdsa_secp256k1 { pub struct EcdsaSecp256k1Impl; impl EcdsaSecp256k1Impl { - pub fn keypair(option: KeyGenOption) -> (PublicKey, PrivateKey) { + pub fn keypair(option: KeyGenOption) -> (PublicKey, PrivateKey) { let signing_key = match option { #[cfg(feature = "rand")] KeyGenOption::Random => PrivateKey::random(&mut OsRng), KeyGenOption::UseSeed(seed) => { PrivateKey::random(&mut super::super::rng_from_seed(seed)) } - KeyGenOption::FromPrivateKey(ref s) => { - let crate::PrivateKeyInner::Secp256k1(s) = s.0.borrow() else { - panic!("Wrong private key type, expected `Secp256k1`, got {s:?}") - }; - s.clone() - } + KeyGenOption::FromPrivateKey(ref s) => s.clone(), }; let public_key = signing_key.public_key(); @@ -139,9 +133,7 @@ mod test { #[test] fn secp256k1_compatibility() { let secret = private_key(); - let (p, s) = EcdsaSecp256k1Sha256::keypair(KeyGenOption::FromPrivateKey( - crate::PrivateKey(Box::new(crate::PrivateKeyInner::Secp256k1(secret))), - )); + let (p, s) = EcdsaSecp256k1Sha256::keypair(KeyGenOption::FromPrivateKey(secret)); let _sk = secp256k1::SecretKey::from_slice(&s.to_bytes()).unwrap(); let _pk = secp256k1::PublicKey::from_slice(&p.to_sec1_bytes()).unwrap(); @@ -191,9 +183,7 @@ mod test { #[test] fn secp256k1_sign() { let secret = private_key(); - let (pk, sk) = EcdsaSecp256k1Sha256::keypair(KeyGenOption::FromPrivateKey( - crate::PrivateKey(Box::new(crate::PrivateKeyInner::Secp256k1(secret))), - )); + let (pk, sk) = EcdsaSecp256k1Sha256::keypair(KeyGenOption::FromPrivateKey(secret)); let sig = EcdsaSecp256k1Sha256::sign(MESSAGE_1, &sk); EcdsaSecp256k1Sha256::verify(MESSAGE_1, &sig, &pk).unwrap(); diff --git a/data_model/src/account.rs b/data_model/src/account.rs index 0ac65442415..2383bdc21ac 100644 --- a/data_model/src/account.rs +++ b/data_model/src/account.rs @@ -439,7 +439,7 @@ mod tests { use crate::{domain::DomainId, name::Name}; fn make_key() -> PublicKey { - KeyPair::generate().public_key().clone() + KeyPair::random().public_key().clone() } fn check_signature_check_condition( diff --git a/data_model/src/events/data/filters.rs b/data_model/src/events/data/filters.rs index b54f1690330..2d497cd128c 100644 --- a/data_model/src/events/data/filters.rs +++ b/data_model/src/events/data/filters.rs @@ -220,7 +220,7 @@ mod tests { let account_id = AccountId::new(domain_id.clone(), account_name); let account = Account::new( account_id.clone(), - iroha_crypto::KeyPair::generate().into_raw_parts().0, + iroha_crypto::KeyPair::random().into_parts().0, ) .into_account(); let asset_id = AssetId::new( diff --git a/data_model/src/query/predicate.rs b/data_model/src/query/predicate.rs index 532243869d4..6421c164457 100644 --- a/data_model/src/query/predicate.rs +++ b/data_model/src/query/predicate.rs @@ -740,7 +740,7 @@ pub mod string { #[test] fn peer_id() { - let (public_key, _) = iroha_crypto::KeyPair::generate().into(); + let (public_key, _) = iroha_crypto::KeyPair::random().into_parts(); let id = IdBox::PeerId(PeerId::new(socket_addr!(127.0.0.1:123), public_key)); assert!(StringPredicate::contains("123").applies(&id)); } @@ -1250,7 +1250,7 @@ pub mod value { pred.applies(&QueryOutputBox::Identifiable(IdentifiableBox::NewAccount( Account::new( "alice@wonderland".parse().expect("Valid"), - KeyPair::generate().into_raw_parts().0 + KeyPair::random().into_parts().0 ) ))) ); @@ -1272,8 +1272,8 @@ pub mod value { ); } { - let key_pair = iroha_crypto::KeyPair::generate(); - let (public_key, _) = key_pair.into(); + let key_pair = iroha_crypto::KeyPair::random(); + let (public_key, _) = key_pair.into_parts(); let pred = QueryOutputPredicate::Display(string::StringPredicate::is("alice@wonderland")); println!("{pred:?}"); diff --git a/genesis/src/lib.rs b/genesis/src/lib.rs index e6c9dcaffc1..15b6b59883e 100644 --- a/genesis/src/lib.rs +++ b/genesis/src/lib.rs @@ -308,11 +308,7 @@ impl RawGenesisDomainBuilder { fn account_with_random_public_key(mut self, account_name: Name) -> Self { let account_id = AccountId::new(self.domain_id.clone(), account_name); self.transaction.isi.push( - Register::account(Account::new( - account_id, - KeyPair::generate().into_raw_parts().0, - )) - .into(), + Register::account(Account::new(account_id, KeyPair::random().into_parts().0)).into(), ); self } @@ -362,8 +358,8 @@ mod tests { fn load_new_genesis_block() -> Result<()> { let chain_id = ChainId::from("0"); - let genesis_key_pair = KeyPair::generate(); - let (alice_public_key, _) = KeyPair::generate().into(); + let genesis_key_pair = KeyPair::random(); + let (alice_public_key, _) = KeyPair::random().into_parts(); let _genesis_block = GenesisNetwork::new( RawGenesisBlockBuilder::default() @@ -411,7 +407,7 @@ mod tests { finished_genesis_block.transactions[0].isi[1], Register::account(Account::new( AccountId::new(domain_id.clone(), "alice".parse().unwrap()), - KeyPair::generate().into_raw_parts().0, + KeyPair::random().into_parts().0, )) .into() ); @@ -419,7 +415,7 @@ mod tests { finished_genesis_block.transactions[0].isi[2], Register::account(Account::new( AccountId::new(domain_id, "bob".parse().unwrap()), - KeyPair::generate().into_raw_parts().0, + KeyPair::random().into_parts().0, )) .into() ); @@ -434,7 +430,7 @@ mod tests { finished_genesis_block.transactions[0].isi[4], Register::account(Account::new( AccountId::new(domain_id, "Cheshire_Cat".parse().unwrap()), - KeyPair::generate().into_raw_parts().0, + KeyPair::random().into_parts().0, )) .into() ); diff --git a/p2p/tests/integration/p2p.rs b/p2p/tests/integration/p2p.rs index a1b688231e0..9f1ec520c87 100644 --- a/p2p/tests/integration/p2p.rs +++ b/p2p/tests/integration/p2p.rs @@ -36,7 +36,7 @@ async fn network_create() { setup_logger(); info!("Starting network tests..."); let address = socket_addr!(127.0.0.1:12_000); - let key_pair = KeyPair::generate(); + let key_pair = KeyPair::random(); let public_key = key_pair.public_key().clone(); let network = NetworkHandle::start(address.clone(), key_pair) .await @@ -140,9 +140,9 @@ impl TestActor { async fn two_networks() { let delay = Duration::from_millis(300); setup_logger(); - let key_pair1 = KeyPair::generate(); + let key_pair1 = KeyPair::random(); let public_key1 = key_pair1.public_key().clone(); - let key_pair2 = KeyPair::generate().clone(); + let key_pair2 = KeyPair::random().clone(); let public_key2 = key_pair2.public_key().clone(); info!("Starting first network..."); let address1 = socket_addr!(127.0.0.1:12_005); @@ -216,7 +216,7 @@ async fn multiple_networks() { let mut key_pairs = Vec::new(); for i in 0_u16..10_u16 { let address = socket_addr!(127.0.0.1: 12_015 + ( i * 5)); - let key_pair = KeyPair::generate(); + let key_pair = KeyPair::random(); let public_key = key_pair.public_key().clone(); peers.push(PeerId::new(address, public_key)); key_pairs.push(key_pair); diff --git a/tools/kagami/src/crypto.rs b/tools/kagami/src/crypto.rs index 2f4e519bfe6..2ebdb9550b2 100644 --- a/tools/kagami/src/crypto.rs +++ b/tools/kagami/src/crypto.rs @@ -1,6 +1,6 @@ use clap::{builder::PossibleValue, ArgGroup, ValueEnum}; use color_eyre::eyre::WrapErr as _; -use iroha_crypto::{Algorithm, KeyGenConfiguration, KeyPair, PrivateKey}; +use iroha_crypto::{Algorithm, KeyPair, PrivateKey}; use super::*; @@ -9,10 +9,13 @@ use super::*; #[command(group = ArgGroup::new("generate_from").required(false))] #[command(group = ArgGroup::new("format").required(false))] pub struct Args { - /// The algorithm to use for the key-pair generation + /// An algorithm to use for the key-pair generation #[clap(default_value_t, long, short)] algorithm: AlgorithmArg, - /// The `private_key` to generate the key-pair from + /// A private key to generate the key-pair from + /// + /// `--private-key` specifies the payload of the private key, while `--algorithm` + /// specifies its algorithm. #[clap(long, short, group = "generate_from")] private_key: Option, /// The Unicode `seed` string to generate the key-pair from @@ -79,23 +82,21 @@ impl Args { fn key_pair(self) -> color_eyre::Result { let algorithm = self.algorithm.0; - let configuration = match (self.seed, self.private_key) { - (None, None) => KeyGenConfiguration::from_random(), + let key_pair = match (self.seed, self.private_key) { + (None, None) => KeyPair::random_with_algorithm(algorithm), (None, Some(private_key_hex)) => { - let private_key = PrivateKey::from_hex(algorithm, private_key_hex.as_ref()) + let private_key = PrivateKey::from_hex(algorithm, private_key_hex) .wrap_err("Failed to decode private key")?; - KeyGenConfiguration::from_private_key(private_key) + KeyPair::from(private_key) } (Some(seed), None) => { let seed: Vec = seed.as_bytes().into(); - KeyGenConfiguration::from_seed(seed) + KeyPair::from_seed(seed, algorithm) } _ => unreachable!("Clap group invariant"), }; - Ok(KeyPair::generate_with_configuration( - configuration.with_algorithm(algorithm), - )) + Ok(key_pair) } } diff --git a/tools/kagami/src/genesis.rs b/tools/kagami/src/genesis.rs index 965b88d6609..2f485d121f5 100644 --- a/tools/kagami/src/genesis.rs +++ b/tools/kagami/src/genesis.rs @@ -251,7 +251,7 @@ fn generate_synthetic( let mut domain_builder = builder.domain(format!("domain_{domain}").parse()?); for account in 0..accounts_per_domain { - let (public_key, _) = iroha_crypto::KeyPair::generate().into(); + let (public_key, _) = iroha_crypto::KeyPair::random().into_parts(); domain_builder = domain_builder.account(format!("account_{account}").parse()?, public_key); } diff --git a/tools/swarm/src/compose.rs b/tools/swarm/src/compose.rs index a361e8710df..c7b3056383f 100644 --- a/tools/swarm/src/compose.rs +++ b/tools/swarm/src/compose.rs @@ -8,7 +8,7 @@ use std::{ }; use color_eyre::eyre::{eyre, Context, ContextCompat}; -use iroha_crypto::{Algorithm, KeyGenConfiguration, KeyPair, PrivateKey, PublicKey}; +use iroha_crypto::{Algorithm, KeyPair, PrivateKey, PublicKey}; use iroha_data_model::{prelude::PeerId, ChainId}; use iroha_primitives::addr::{socket_addr, SocketAddr}; use peer_generator::Peer; @@ -328,7 +328,7 @@ impl From for FullPeerEnv { let (genesis_private_key_algorithm, genesis_private_key_payload, genesis_file) = value .genesis_private_key .map_or((None, None, None), |private_key| { - let (algorithm, payload) = private_key.to_raw(); + let (algorithm, payload) = private_key.to_bytes(); ( Some(algorithm), Some(payload), @@ -337,7 +337,7 @@ impl From for FullPeerEnv { }); let (private_key_algorithm, private_key_payload) = { - let (algorithm, payload) = value.key_pair.private_key().clone().to_raw(); + let (algorithm, payload) = value.key_pair.private_key().clone().to_bytes(); (algorithm, payload) }; @@ -465,12 +465,10 @@ impl DockerComposeBuilder<'_> { } fn generate_key_pair(base_seed: Option<&[u8]>, additional_seed: &[u8]) -> KeyPair { - let cfg = base_seed.map_or_else(KeyGenConfiguration::from_random, |base| { + base_seed.map_or_else(KeyPair::random, |base| { let seed: Vec<_> = base.iter().chain(additional_seed).copied().collect(); - KeyGenConfiguration::from_seed(seed) - }); - - KeyPair::generate_with_configuration(cfg) + KeyPair::from_seed(seed, Algorithm::default()) + }) } mod peer_generator { @@ -564,7 +562,7 @@ mod tests { base::{FromEnv, TestEnv, UnwrapPartial}, parameters::user::{CliContext, RootPartial}, }; - use iroha_crypto::{KeyGenConfiguration, KeyPair}; + use iroha_crypto::KeyPair; use iroha_primitives::addr::{socket_addr, SocketAddr}; use path_absolutize::Absolutize; @@ -598,7 +596,7 @@ mod tests { #[test] fn default_config_with_swarm_env_is_exhaustive() { - let keypair = KeyPair::generate(); + let keypair = KeyPair::random(); let env: TestEnv = CompactPeerEnv { chain_id: ChainId::from("00000000-0000-0000-0000-000000000000"), key_pair: keypair.clone(), @@ -638,9 +636,7 @@ mod tests { let chain_id = ChainId::from("00000000-0000-0000-0000-000000000000"); let key_pair = - KeyPair::generate_with_configuration(KeyGenConfiguration::from_seed(vec![ - 1, 5, 1, 2, 2, 3, 4, 1, 2, 3, - ])); + KeyPair::from_seed(vec![1, 5, 1, 2, 2, 3, 4, 1, 2, 3], Algorithm::default()); map.insert( "iroha0".to_owned(), @@ -711,8 +707,7 @@ mod tests { fn empty_genesis_private_key_is_skipped_in_env() { let chain_id = ChainId::from("00000000-0000-0000-0000-000000000000"); - let key_pair = - KeyPair::generate_with_configuration(KeyGenConfiguration::from_seed(vec![0, 1, 2])); + let key_pair = KeyPair::from_seed(vec![0, 1, 2], Algorithm::default()); let env: FullPeerEnv = CompactPeerEnv { chain_id,