Skip to content

Commit

Permalink
nits from suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
AnastasiiaVashchuk committed Oct 4, 2023
1 parent df062a7 commit 5a9ece4
Show file tree
Hide file tree
Showing 22 changed files with 125 additions and 79 deletions.
6 changes: 3 additions & 3 deletions core/bin/external_node/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -397,12 +397,12 @@ impl ExternalNodeConfig {

let l2_chain_id: L2ChainId = env_var("EN_L2_CHAIN_ID");
let l1_chain_id: u64 = env_var("EN_L1_CHAIN_ID");
if l2_chain_id.0 != remote.l2_chain_id.0 {
if l2_chain_id != remote.l2_chain_id {
anyhow::bail!(
"Configured L2 chain id doesn't match the one from main node.
Make sure your configuration is correct and you are corrected to the right main node.
Main node L2 chain id: {}. Local config value: {}",
remote.l2_chain_id.0, l2_chain_id.0
Main node L2 chain id: {:?}. Local config value: {:?}",
remote.l2_chain_id, l2_chain_id
);
}
if l1_chain_id != remote.l1_chain_id.0 {
Expand Down
3 changes: 2 additions & 1 deletion core/bin/system-constants-generator/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use once_cell::sync::Lazy;
use std::cell::RefCell;
use std::convert::TryFrom;
use std::rc::Rc;
use vm::constants::{BLOCK_GAS_LIMIT, BOOTLOADER_HEAP_PAGE};
use vm::{
Expand Down Expand Up @@ -92,7 +93,7 @@ pub(super) fn get_l2_tx(contract_address: Address, signer: &H256, pubdata_price:
gas_per_pubdata_limit: pubdata_price.into(),
},
U256::from(0),
L2ChainId::from(270),
L2ChainId::try_from(270).unwrap(),
signer,
None,
Default::default(),
Expand Down
43 changes: 27 additions & 16 deletions core/lib/basic_types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ mod macros;
pub mod network;

use serde::{de, Deserialize, Deserializer, Serialize};
use web3::ethabi::ethereum_types::FromStrRadixErr;

use std::{
convert::{Infallible, TryFrom, TryInto},
Expand Down Expand Up @@ -99,16 +98,19 @@ impl<'de> Deserialize<'de> for L2ChainId {
s.parse::<U256>().map_err(de::Error::custom)?
}
};
assert!(
u256 <= L2ChainId::MAX.into(),
"Too big chain ID. MAX: {}",
L2ChainId::MAX
);

if u256 > L2ChainId::MAX.into() {
return Err(de::Error::custom(format!(
"Too big chain ID. MAX: {}",
L2ChainId::MAX
)));
}
Ok(L2ChainId(u256))
}
}

impl FromStr for L2ChainId {
type Err = FromStrRadixErr;
type Err = String;

fn from_str(s: &str) -> Result<Self, Self::Err> {
// Parse the string as a U256
Expand All @@ -117,14 +119,14 @@ impl FromStr for L2ChainId {
Ok(u) => u,
Err(_) => {
// try to parse as hex
s.parse::<U256>().map_err(FromStrRadixErr::from)?
s.parse::<U256>()
.map_err(|err| format!("Failed to parse L2ChainId: Err {err}"))?
}
};
assert!(
u256 <= L2ChainId::MAX.into(),
"Too big chain ID. MAX: {}",
L2ChainId::MAX
);

if u256 > L2ChainId::MAX.into() {
return Err(format!("Too big chain ID. MAX: {}", L2ChainId::MAX));
}
Ok(L2ChainId(u256))
}
}
Expand All @@ -143,9 +145,18 @@ impl Default for L2ChainId {
}
}

impl From<u64> for L2ChainId {
fn from(val: u64) -> Self {
Self(U256::from(val))
impl TryFrom<u64> for L2ChainId {
type Error = String;

fn try_from(val: u64) -> Result<Self, Self::Error> {
if val > L2ChainId::MAX {
return Err(format!(
"Cannot convert given value {} into L2ChainId. It's greater than MAX: {},",
val,
L2ChainId::MAX,
));
}
Ok(Self(U256::from(val)))
}
}

Expand Down
4 changes: 3 additions & 1 deletion core/lib/config/src/configs/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,8 @@ impl MempoolConfig {

#[cfg(test)]
mod tests {
use std::convert::TryFrom;

use super::*;
use crate::configs::test_utils::{addr, EnvMutex};

Expand All @@ -202,7 +204,7 @@ mod tests {
network: NetworkConfig {
network: "localhost".parse().unwrap(),
zksync_network: "localhost".to_string(),
zksync_network_id: L2ChainId::from(270),
zksync_network_id: L2ChainId::try_from(270).unwrap(),
},
state_keeper: StateKeeperConfig {
transaction_slots: 50,
Expand Down
6 changes: 4 additions & 2 deletions core/lib/dal/src/blocks_web3_dal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,8 @@ impl BlocksWeb3Dal<'_, '_> {

#[cfg(test)]
mod tests {
use std::convert::TryFrom;

use db_test_macro::db_test;
use zksync_contracts::BaseSystemContractsHashes;
use zksync_types::{
Expand Down Expand Up @@ -623,7 +625,7 @@ mod tests {
for block_id in block_ids {
let block = conn
.blocks_web3_dal()
.get_block_by_web3_block_id(block_id, false, L2ChainId::from(270))
.get_block_by_web3_block_id(block_id, false, L2ChainId::try_from(270).unwrap())
.await;
let block = block.unwrap().unwrap();
assert!(block.transactions.is_empty());
Expand All @@ -650,7 +652,7 @@ mod tests {
for block_id in non_existing_block_ids {
let block = conn
.blocks_web3_dal()
.get_block_by_web3_block_id(block_id, false, L2ChainId::from(270))
.get_block_by_web3_block_id(block_id, false, L2ChainId::try_from(270).unwrap())
.await;
assert!(block.unwrap().is_none());

Expand Down
4 changes: 2 additions & 2 deletions core/lib/dal/src/tests/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::fs;
use std::time::Duration;
use std::{convert::TryFrom, fs};

use db_test_macro::db_test;
use zksync_contracts::BaseSystemContractsHashes;
Expand Down Expand Up @@ -59,7 +59,7 @@ pub(crate) fn mock_l2_transaction() -> L2Tx {
zksync_types::Nonce(0),
fee,
Default::default(),
L2ChainId::from(270),
L2ChainId::try_from(270).unwrap(),
&H256::random(),
None,
Default::default(),
Expand Down
8 changes: 5 additions & 3 deletions core/lib/dal/src/transactions_web3_dal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,8 @@ impl TransactionsWeb3Dal<'_, '_> {

#[cfg(test)]
mod tests {
use std::convert::TryFrom;

use db_test_macro::db_test;
use zksync_types::{
block::miniblock_hash, fee::TransactionExecutionMetrics, l2::L2Tx, ProtocolVersion,
Expand Down Expand Up @@ -417,7 +419,7 @@ mod tests {
for transaction_id in transaction_ids {
let web3_tx = conn
.transactions_web3_dal()
.get_transaction(transaction_id, L2ChainId::from(270))
.get_transaction(transaction_id, L2ChainId::try_from(270).unwrap())
.await;
let web3_tx = web3_tx.unwrap().unwrap();
assert_eq!(web3_tx.hash, tx_hash);
Expand All @@ -431,7 +433,7 @@ mod tests {
for transaction_id in transactions_with_bogus_index {
let web3_tx = conn
.transactions_web3_dal()
.get_transaction(transaction_id, L2ChainId::from(270))
.get_transaction(transaction_id, L2ChainId::try_from(270).unwrap())
.await;
assert!(web3_tx.unwrap().is_none());
}
Expand All @@ -448,7 +450,7 @@ mod tests {
for transaction_id in transactions_with_bogus_block {
let web3_tx = conn
.transactions_web3_dal()
.get_transaction(transaction_id, L2ChainId::from(270))
.get_transaction(transaction_id, L2ChainId::try_from(270).unwrap())
.await;
assert!(web3_tx.unwrap().is_none());
}
Expand Down
4 changes: 2 additions & 2 deletions core/lib/state/src/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use zksync_types::{
use zksync_utils::u256_to_h256;

/// Network ID we use by defailt for in memory storage.
pub const IN_MEMORY_STORAGE_DEFAULT_NETWORK_ID: u16 = 270;
pub const IN_MEMORY_STORAGE_DEFAULT_NETWORK_ID: u64 = 270;

/// In-memory storage.
#[derive(Debug, Default)]
Expand All @@ -22,7 +22,7 @@ impl InMemoryStorage {
/// Constructs a storage that contains system smart contracts.
pub fn with_system_contracts(bytecode_hasher: impl Fn(&[u8]) -> H256) -> Self {
Self::with_system_contracts_and_chain_id(
L2ChainId::from(u64::from(IN_MEMORY_STORAGE_DEFAULT_NETWORK_ID)),
L2ChainId::try_from(IN_MEMORY_STORAGE_DEFAULT_NETWORK_ID).unwrap(),
bytecode_hasher,
)
}
Expand Down
4 changes: 3 additions & 1 deletion core/lib/test_account/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::convert::TryFrom;

use ethabi::Token;
use zksync_config::constants::{
CONTRACT_DEPLOYER_ADDRESS, MAX_GAS_PER_PUBDATA_BYTE, REQUIRED_L1_TO_L2_GAS_PER_PUBDATA_BYTE,
Expand Down Expand Up @@ -77,7 +79,7 @@ impl Account {
nonce,
fee.unwrap_or_else(|| self.default_fee()),
value,
L2ChainId::from(270),
L2ChainId::try_from(270).unwrap(),
&self.private_key,
factory_deps,
Default::default(),
Expand Down
14 changes: 8 additions & 6 deletions core/lib/types/src/transaction_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1055,7 +1055,7 @@ mod tests {
};

let msg = PackedEthSignature::typed_data_to_signed_bytes(
&Eip712Domain::new(L2ChainId::from(270)),
&Eip712Domain::new(L2ChainId::try_from(270).unwrap()),
&tx,
);
let signature = PackedEthSignature::sign_raw(&private_key, &msg).unwrap();
Expand Down Expand Up @@ -1098,12 +1098,13 @@ mod tests {
chain_id: Some(U256::from(270)),
..Default::default()
};
let domain = Eip712Domain::new(L2ChainId::from(270));
let domain = Eip712Domain::new(L2ChainId::try_from(270).unwrap());
let signature =
PackedEthSignature::sign_typed_data(&private_key, &domain, &transaction_request)
.unwrap();

let encoded_tx = transaction_request.get_signed_bytes(&signature, L2ChainId::from(270));
let encoded_tx =
transaction_request.get_signed_bytes(&signature, L2ChainId::try_from(270).unwrap());

let (decoded_tx, _) =
TransactionRequest::from_bytes(encoded_tx.as_slice(), U256::from(270)).unwrap();
Expand Down Expand Up @@ -1138,12 +1139,13 @@ mod tests {
chain_id: Some(U256::from(270)),
..Default::default()
};
let domain = Eip712Domain::new(L2ChainId::from(270));
let domain = Eip712Domain::new(L2ChainId::try_from(270).unwrap());
let signature =
PackedEthSignature::sign_typed_data(&private_key, &domain, &transaction_request)
.unwrap();

let encoded_tx = transaction_request.get_signed_bytes(&signature, L2ChainId::from(270));
let encoded_tx =
transaction_request.get_signed_bytes(&signature, L2ChainId::try_from(270).unwrap());

let decoded_tx = TransactionRequest::from_bytes(encoded_tx.as_slice(), U256::from(272));
assert_eq!(
Expand Down Expand Up @@ -1426,7 +1428,7 @@ mod tests {
};

let msg = PackedEthSignature::typed_data_to_signed_bytes(
&Eip712Domain::new(L2ChainId::from(270)),
&Eip712Domain::new(L2ChainId::try_from(270).unwrap()),
&tx,
);
let signature = PackedEthSignature::sign_raw(&private_key, &msg).unwrap();
Expand Down
4 changes: 3 additions & 1 deletion core/lib/vm/src/tests/tester/vm_tester.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::convert::TryFrom;

use zksync_contracts::BaseSystemContracts;
use zksync_state::{InMemoryStorage, StoragePtr, StorageView, WriteStorage};

Expand Down Expand Up @@ -142,7 +144,7 @@ impl<H: HistoryMode> VmTesterBuilder<H> {
gas_limit: BLOCK_GAS_LIMIT,
execution_mode: TxExecutionMode::VerifyExecute,
default_validation_computational_gas_limit: BLOCK_GAS_LIMIT,
chain_id: L2ChainId::from(270),
chain_id: L2ChainId::try_from(270).unwrap(),
},
deployer: None,
rich_accounts: vec![],
Expand Down
12 changes: 7 additions & 5 deletions core/lib/zksync_core/src/genesis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,8 @@ pub(crate) async fn save_genesis_l1_batch_metadata(

#[cfg(test)]
mod tests {
use std::convert::TryFrom;

use db_test_macro::db_test;
use zksync_dal::ConnectionPool;
use zksync_types::{system_contracts::get_system_smart_contracts, U256};
Expand All @@ -389,7 +391,7 @@ mod tests {
first_l1_verifier_config: L1VerifierConfig::default(),
first_verifier_address: Address::random(),
};
ensure_genesis_state(&mut conn, L2ChainId::from(270), &params)
ensure_genesis_state(&mut conn, L2ChainId::try_from(270).unwrap(), &params)
.await
.unwrap();

Expand All @@ -403,14 +405,14 @@ mod tests {
assert_ne!(root_hash, H256::zero());

// Check that `ensure_genesis_state()` doesn't panic on repeated runs.
ensure_genesis_state(&mut conn, L2ChainId::from(270), &params)
ensure_genesis_state(&mut conn, L2ChainId::try_from(270).unwrap(), &params)
.await
.unwrap();
}

#[db_test]
async fn running_genesis_with_big_chain_id(pool: ConnectionPool) {
let mut conn = pool.access_storage().await;
let mut conn = pool.access_storage().await.unwrap();
conn.blocks_dal().delete_genesis().await;

let params = GenesisParams {
Expand All @@ -425,12 +427,12 @@ mod tests {
.await
.unwrap();

assert!(!conn.blocks_dal().is_genesis_needed().await);
assert!(!conn.blocks_dal().is_genesis_needed().await.unwrap());
let metadata = conn
.blocks_dal()
.get_l1_batch_metadata(L1BatchNumber(0))
.await;
let root_hash = metadata.unwrap().metadata.root_hash;
let root_hash = metadata.unwrap().unwrap().metadata.root_hash;
assert_ne!(root_hash, H256::zero());
}
}
Loading

0 comments on commit 5a9ece4

Please sign in to comment.