Skip to content

Commit

Permalink
Merge branch 'dev' into sb-argent-sub
Browse files Browse the repository at this point in the history
  • Loading branch information
StanislavBreadless committed Dec 7, 2021
2 parents 1e24856 + e7bb896 commit bddc616
Show file tree
Hide file tree
Showing 43 changed files with 1,342 additions and 461 deletions.
1 change: 1 addition & 0 deletions core/bin/data_restore/src/storage_interactor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pub struct CachedTreeState {
pub nfts: HashMap<TokenId, NFT>,
}

#[allow(clippy::large_enum_variant)]
pub enum StorageInteractor<'a> {
Database(DatabaseStorageInteractor<'a>),
InMemory(InMemoryStorageInteractor),
Expand Down
4 changes: 1 addition & 3 deletions core/bin/prover/src/dummy_prover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,14 @@ impl ProverConfig for DummyProverConfig {

#[derive(Debug)]
pub struct DummyProver {
config: DummyProverConfig,
precomputed_proofs: PrecomputedSampleProofs,
}

impl ProverImpl for DummyProver {
type Config = DummyProverConfig;

fn create_from_config(config: Self::Config) -> Self {
fn create_from_config(_config: Self::Config) -> Self {
Self {
config,
precomputed_proofs: load_precomputed_proofs()
.expect("Failed to load precomputed proofs"),
}
Expand Down
2 changes: 1 addition & 1 deletion core/bin/prover/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ fn test_data_for_prover() -> JobRequestData {
account_id: empty_account_id,
};

let deposit_witness = DepositWitness::apply_tx(&mut witness_accum.account_tree, &deposit_op);
let deposit_witness = DepositWitness::apply_tx(witness_accum.account_tree, &deposit_op);
let deposit_operations = deposit_witness.calculate_operations(());
let pub_data_from_witness = deposit_witness.get_pubdata();
let offset_commitment = deposit_witness.get_offset_commitment_data();
Expand Down
3 changes: 3 additions & 0 deletions core/bin/zksync_api/src/api_server/rest/v02/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,10 @@ mod tests {
})))
}

// While the values of the PendingOpsFlattenRequest's fields are never directly
// used in the tests, we still need them to specify the JSON format of the `unconfirmed_ops` endpoint input in tests.
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct PendingOpsFlattenRequest {
pub address: Address,
pub account_id: Option<AccountId>,
Expand Down
7 changes: 0 additions & 7 deletions core/bin/zksync_api/src/api_server/rpc_server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@ use ip_insert_middleware::IpInsertMiddleWare;

#[derive(Clone)]
pub struct RpcApp {
runtime_handle: tokio::runtime::Handle,

cache_of_executed_priority_operations: AsyncLruCache<u32, StoredExecutedPriorityOperation>,
cache_of_transaction_receipts: AsyncLruCache<Vec<u8>, TxReceiptResponse>,
cache_of_complete_withdrawal_tx_hashes: AsyncLruCache<TxHash, String>,
Expand All @@ -63,9 +61,6 @@ impl RpcApp {
private_url: String,
confirmations_for_eth_event: u64,
) -> Self {
let runtime_handle = tokio::runtime::Handle::try_current()
.expect("RpcApp must be created from the context of Tokio Runtime");

let api_requests_caches_size = config.caches_size;

let tx_sender = TxSender::new(
Expand All @@ -77,8 +72,6 @@ impl RpcApp {
);

RpcApp {
runtime_handle,

cache_of_executed_priority_operations: AsyncLruCache::new(api_requests_caches_size),
cache_of_transaction_receipts: AsyncLruCache::new(api_requests_caches_size),
cache_of_complete_withdrawal_tx_hashes: AsyncLruCache::new(api_requests_caches_size),
Expand Down
4 changes: 0 additions & 4 deletions core/bin/zksync_api/src/api_server/web3/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ pub const NFT_FACTORY_ADDRESS: &str = "2000000000000000000000000000000000000000"

#[derive(Clone)]
pub struct Web3RpcApp {
runtime_handle: tokio::runtime::Handle,
connection_pool: ConnectionPool,
logs_helper: LogsHelper,
calls_helper: CallsHelper,
Expand All @@ -37,10 +36,7 @@ pub struct Web3RpcApp {

impl Web3RpcApp {
pub fn new(connection_pool: ConnectionPool, config: &Web3Config) -> Self {
let runtime_handle = tokio::runtime::Handle::try_current()
.expect("Web3RpcApp must be created from the context of Tokio Runtime");
Web3RpcApp {
runtime_handle,
connection_pool,
logs_helper: LogsHelper::new(),
calls_helper: CallsHelper::new(),
Expand Down
3 changes: 3 additions & 0 deletions core/bin/zksync_api/src/bin/dev-ticker-server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ async fn handle_coinmarketcap_token_price_query(
#[derive(Debug, Deserialize)]
struct Token {
pub address: Address,
// While never used directly, it is better to keep this field here so that it is easy to know what fields are
// available for the test tokens.
#[allow(dead_code)]
pub decimals: u8,
pub symbol: String,
}
Expand Down
16 changes: 6 additions & 10 deletions core/bin/zksync_api/src/fee_ticker/ticker_api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,11 @@ pub trait FeeTickerAPI {
#[derive(Debug, Clone)]
pub(crate) struct TokenCacheEntry {
price: TokenPrice,
creation_time: Instant,
}

impl TokenCacheEntry {
fn new(price: TokenPrice, creation_time: Instant) -> Self {
Self {
price,
creation_time,
}
fn new(price: TokenPrice) -> Self {
Self { price }
}

fn is_cache_entry_expired(&self) -> bool {
Expand Down Expand Up @@ -135,10 +131,10 @@ impl<T: TokenPriceAPI> TickerApi<T> {
}

async fn update_stored_value(&self, token_id: TokenId, price: TokenPrice) {
self.price_cache.lock().await.insert(
token_id,
TokenCacheEntry::new(price.clone(), Instant::now()),
);
self.price_cache
.lock()
.await
.insert(token_id, TokenCacheEntry::new(price.clone()));
self._update_stored_value(token_id, price)
.await
.map_err(|e| vlog::warn!("Failed to update historical ticker price: {}", e))
Expand Down
116 changes: 116 additions & 0 deletions core/bin/zksync_core/src/genesis.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
use std::time::Instant;

// External uses
// Workspace uses
use zksync_crypto::{
ff,
params::{MIN_NFT_TOKEN_ID, NFT_STORAGE_ACCOUNT_ADDRESS, NFT_STORAGE_ACCOUNT_ID, NFT_TOKEN_ID},
};
use zksync_state::state::ZkSyncState;
use zksync_storage::ConnectionPool;
use zksync_types::{Account, AccountId, AccountUpdate, Address, BlockNumber, Token, TokenKind};
// Local uses

pub async fn create_genesis_block(pool: ConnectionPool, fee_account_address: &Address) {
let start = Instant::now();
let mut storage = pool
.access_storage()
.await
.expect("db connection failed for statekeeper");
let mut transaction = storage
.start_transaction()
.await
.expect("unable to create db transaction in statekeeper");

let (last_committed, mut accounts) = transaction
.chain()
.state_schema()
.load_committed_state(None)
.await
.expect("db failed");

assert!(
*last_committed == 0 && accounts.is_empty(),
"db should be empty"
);

vlog::info!("Adding special token");
transaction
.tokens_schema()
.store_token(Token::new(
NFT_TOKEN_ID,
*NFT_STORAGE_ACCOUNT_ADDRESS,
"SPECIAL",
18,
TokenKind::NFT,
))
.await
.expect("failed to store special token");
vlog::info!("Special token added");

let fee_account = Account::default_with_address(fee_account_address);
let db_create_fee_account = AccountUpdate::Create {
address: *fee_account_address,
nonce: fee_account.nonce,
};
accounts.insert(AccountId(0), fee_account);

let (mut special_account, db_create_special_account) =
Account::create_account(NFT_STORAGE_ACCOUNT_ID, *NFT_STORAGE_ACCOUNT_ADDRESS);
special_account.set_balance(NFT_TOKEN_ID, num::BigUint::from(MIN_NFT_TOKEN_ID));
let db_set_special_account_balance = AccountUpdate::UpdateBalance {
old_nonce: special_account.nonce,
new_nonce: special_account.nonce,
balance_update: (
NFT_TOKEN_ID,
num::BigUint::from(0u64),
num::BigUint::from(MIN_NFT_TOKEN_ID),
),
};
accounts.insert(NFT_STORAGE_ACCOUNT_ID, special_account);

transaction
.chain()
.state_schema()
.commit_state_update(
BlockNumber(0),
&[
(AccountId(0), db_create_fee_account),
db_create_special_account[0].clone(),
(NFT_STORAGE_ACCOUNT_ID, db_set_special_account_balance),
],
0,
)
.await
.expect("db fail");
transaction
.chain()
.state_schema()
.apply_state_update(BlockNumber(0))
.await
.expect("db fail");

let state = ZkSyncState::from_acc_map(accounts, last_committed + 1);
let root_hash = state.root_hash();
transaction
.chain()
.block_schema()
.save_genesis_block(root_hash)
.await
.expect("db fail");

transaction
.commit()
.await
.expect("Unable to commit transaction in statekeeper");
vlog::info!("Genesis block created, state: {}", state.root_hash());

// Below we are intentionally using `println`, because during genesis we parse the genesis root from
// the server output in order to save it into the config file.
// See `server.genesis()` in the `zk` tool for details.
// TODO: Find a better and a more intuitive approach (ZKS-816).
let genesis_root = format!("CONTRACTS_GENESIS_ROOT=0x{}", ff::to_hex(&root_hash));
println!("{}", &genesis_root);

metrics::histogram!("state_keeper.create_genesis_block", start.elapsed());
}
5 changes: 3 additions & 2 deletions core/bin/zksync_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ pub mod state_keeper;
pub mod token_handler;
pub mod tx_event_emitter;

mod genesis;

/// Waits for any of the tokio tasks to be finished.
/// Since the main tokio tasks are used as actors which should live as long
/// as application runs, any possible outcome (either `Ok` or `Err`) is considered
Expand All @@ -53,8 +55,7 @@ pub async fn genesis_init(config: &ChainConfig) {
let pool = ConnectionPool::new(Some(1));

vlog::info!("Generating genesis block.");
ZkSyncStateKeeper::create_genesis_block(pool.clone(), &config.state_keeper.fee_account_addr)
.await;
genesis::create_genesis_block(pool.clone(), &config.state_keeper.fee_account_addr).await;
vlog::info!("Adding initial tokens to db");
let genesis_tokens = get_genesis_token_list(&config.eth.network.to_string())
.expect("Initial token list not found");
Expand Down
Loading

0 comments on commit bddc616

Please sign in to comment.