Skip to content

Commit

Permalink
execute_block_and_save function add param ChainId
Browse files Browse the repository at this point in the history
block_executor function add param WriteSet
  • Loading branch information
nkysg committed Apr 7, 2024
1 parent 224ee92 commit 7c55a44
Show file tree
Hide file tree
Showing 6 changed files with 95 additions and 20 deletions.
45 changes: 40 additions & 5 deletions chain/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,13 @@ use starcoin_types::{
transaction::{SignedUserTransaction, Transaction},
U256,
};
use starcoin_vm_types::access_path::AccessPath;
use starcoin_vm_types::account_config::genesis_address;
use starcoin_vm_types::genesis_config::ConsensusStrategy;
use starcoin_vm_types::on_chain_resource::Epoch;
use starcoin_vm_types::{
access_path::AccessPath,
account_config::genesis_address,
genesis_config::{ChainId, ConsensusStrategy},
on_chain_resource::Epoch,
write_set::WriteSet,
};
use std::cmp::min;
use std::iter::Extend;
use std::option::Option::{None, Some};
Expand All @@ -49,6 +52,8 @@ use std::{
sync::Arc,
};

pub const MAIN_FORCE_UPGRADE_BLOCK_NUMBER: BlockNumber = 17000000;

static MAIN_DIRECT_SAVE_BLOCK_HASH_MAP: Lazy<BTreeMap<HashValue, (BlockExecutedData, BlockInfo)>> =
Lazy::new(|| {
let mut maps = BTreeMap::new();
Expand Down Expand Up @@ -573,6 +578,13 @@ static MAIN_DIRECT_SAVE_BLOCK_HASH_MAP: Lazy<BTreeMap<HashValue, (BlockExecutedD
maps
});

/// XXX FIXME YSG FORCE_UPGRADE
static MAIN_FORCE_UPGRADE_BLOCK_MAP: Lazy<BTreeMap<BlockNumber, WriteSet>> = Lazy::new(|| {
let mut maps = BTreeMap::new();
maps.insert(MAIN_FORCE_UPGRADE_BLOCK_NUMBER, WriteSet::default());
maps
});

static OUTPUT_BLOCK: AtomicBool = AtomicBool::new(false);

pub struct ChainStatusWithBlock {
Expand Down Expand Up @@ -672,6 +684,7 @@ impl BlockChain {
storage.get_accumulator_store(AccumulatorStoreType::Block),
);
let statedb = ChainStateDB::new(storage.clone().into_super_arc(), None);
let chain_id = genesis_block.header().chain_id();
let executed_block = Self::execute_block_and_save(
storage.as_ref(),
statedb,
Expand All @@ -681,6 +694,7 @@ impl BlockChain {
None,
genesis_block,
None,
chain_id,
)?;
Self::new(time_service, executed_block.block.id(), storage, None)
}
Expand Down Expand Up @@ -897,6 +911,7 @@ impl BlockChain {
parent_status: Option<ChainStatus>,
block: Block,
vm_metrics: Option<VMMetrics>,
chain_id: ChainId,
) -> Result<ExecutedBlock> {
let header = block.header();
debug_assert!(header.is_genesis() || parent_status.is_some());
Expand All @@ -920,13 +935,19 @@ impl BlockChain {
);
t
};

watch(CHAIN_WATCH_NAME, "n21");
let mut extra_set = WriteSet::default();
if chain_id.is_main() {
if let Some(write_set) = MAIN_FORCE_UPGRADE_BLOCK_MAP.get(&block.header().number()) {
extra_set = write_set.clone();
}
}
let executed_data = starcoin_executor::block_execute(
&statedb,
transactions.clone(),
epoch.block_gas_limit(),
vm_metrics,
extra_set,
)?;
watch(CHAIN_WATCH_NAME, "n22");
let state_root = executed_data.state_root;
Expand Down Expand Up @@ -1203,6 +1224,7 @@ impl BlockChain {
OUTPUT_BLOCK.store(true, Ordering::Relaxed);
}

// XXX FIXME YSG REFACTOR
fn execute_block_without_save(
statedb: ChainStateDB,
txn_accumulator: MerkleAccumulator,
Expand All @@ -1211,6 +1233,7 @@ impl BlockChain {
parent_status: Option<ChainStatus>,
block: Block,
vm_metrics: Option<VMMetrics>,
chain_id: ChainId,
) -> Result<ExecutedBlock> {
let header = block.header();
debug_assert!(header.is_genesis() || parent_status.is_some());
Expand All @@ -1236,11 +1259,21 @@ impl BlockChain {
};

watch(CHAIN_WATCH_NAME, "n21");

// XXX FIXME YSG REFACTOR
let mut extra_set = WriteSet::default();
if chain_id.is_main() {
if let Some(write_set) = MAIN_FORCE_UPGRADE_BLOCK_MAP.get(&block.header().number()) {
extra_set = write_set.clone();
}
}

let executed_data = starcoin_executor::block_execute(
&statedb,
transactions.clone(),
epoch.block_gas_limit(),
vm_metrics,
extra_set,
)?;
watch(CHAIN_WATCH_NAME, "n22");
let state_root = executed_data.state_root;
Expand Down Expand Up @@ -1581,6 +1614,7 @@ impl ChainReader for BlockChain {
Some(self.status.status.clone()),
verified_block.0,
self.vm_metrics.clone(),
self.info().chain_id(),
)
}
}
Expand All @@ -1594,6 +1628,7 @@ impl ChainReader for BlockChain {
Some(self.status.status.clone()),
verified_block.0,
self.vm_metrics.clone(),
self.info().chain_id(),
)
}

Expand Down
11 changes: 9 additions & 2 deletions chain/tests/block_test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use starcoin_types::{
block_metadata::BlockMetadata,
U256,
};
use starcoin_vm_types::write_set::WriteSet;
use std::convert::TryFrom;
use std::sync::Arc;

Expand Down Expand Up @@ -222,7 +223,13 @@ fn gen_root_hashes(
//state_db
let chain_state = ChainStateDB::new(storage.clone(), Some(pre_state_root));

match block_execute(&chain_state, block_txns, block_gat_limit, None) {
match block_execute(
&chain_state,
block_txns,
block_gat_limit,
None,
WriteSet::default(),
) {
Ok(executed_data) => {
let txn_accumulator = MerkleAccumulator::new(
pre_accumulator_root,
Expand Down Expand Up @@ -276,7 +283,7 @@ proptest! {
let chain_state = ChainStateDB::new(Arc::new(storage), None);
let mut account = AccountInfoUniverse::default();
let txns = txn_transfer(&mut account, gens);
let result = block_execute(&chain_state, txns, 0, None);
let result = block_execute(&chain_state, txns, 0, None,WriteSet::default());
info!("execute result: {:?}", result);
}
}
19 changes: 12 additions & 7 deletions executor/benchmark/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ use starcoin_types::{
block_metadata::BlockMetadata,
transaction::{Transaction, TransactionPayload},
};
use starcoin_vm_types::genesis_config::StdlibVersion;
use starcoin_vm_types::token::stc;
use starcoin_vm_types::transaction::authenticator::AuthenticationKey;
use starcoin_vm_types::transaction::ScriptFunction;
use starcoin_vm_types::{
genesis_config::StdlibVersion, token::stc, transaction::authenticator::AuthenticationKey,
transaction::ScriptFunction, write_set::WriteSet,
};
use std::sync::mpsc;
use std::sync::Arc;

Expand Down Expand Up @@ -222,9 +222,14 @@ impl<'test, S: ChainStateReader + ChainStateWriter> TxnExecutor<'test, S> {
let num_txns = transactions.len();
version += num_txns as u64;

let _ =
starcoin_executor::block_execute(self.chain_state, transactions, u64::MAX, None)
.expect("Execute transactions fail.");
let _ = starcoin_executor::block_execute(
self.chain_state,
transactions,
u64::MAX,
None,
WriteSet::default(),
)
.expect("Execute transactions fail.");
self.chain_state.flush().expect("flush state should be ok");

let execute_time = std::time::Instant::now().duration_since(execute_start);
Expand Down
9 changes: 9 additions & 0 deletions executor/src/block_executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ pub fn block_execute<S: ChainStateReader + ChainStateWriter>(
txns: Vec<Transaction>,
block_gas_limit: u64,
vm_metrics: Option<VMMetrics>,
extra_set: WriteSet,
) -> ExecutorResult<BlockExecutedData> {
let txn_outputs =
crate::execute_block_transactions(chain_state, txns.clone(), block_gas_limit, vm_metrics)
Expand Down Expand Up @@ -85,6 +86,14 @@ pub fn block_execute<S: ChainStateReader + ChainStateWriter>(
};
}

if !extra_set.is_empty() {
chain_state
.apply_write_set(extra_set)
.map_err(BlockExecutorError::BlockChainStateErr)?;
chain_state
.commit()
.map_err(BlockExecutorError::BlockChainStateErr)?;
}
executed_data.state_root = chain_state.state_root();
Ok(executed_data)
}
21 changes: 16 additions & 5 deletions executor/tests/executor_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ use starcoin_types::account_config::G_STC_TOKEN_CODE;
use starcoin_vm_runtime::starcoin_vm::{chunk_block_transactions, StarcoinVM};
use starcoin_vm_types::account_config::core_code_address;
use starcoin_vm_types::state_store::state_key::StateKey;
use starcoin_vm_types::write_set::WriteSet;
use test_helper::txn::create_account_txn_sent_as_association;

#[derive(Default)]
Expand Down Expand Up @@ -403,8 +404,13 @@ fn test_block_execute_gas_limit() -> Result<()> {
assert_eq!(max_include_txn_num, txns.len() as u64);

txns.insert(0, Transaction::BlockMetadata(block_meta));
let executed_data =
starcoin_executor::block_execute(&chain_state, txns, block_gas_limit, None)?;
let executed_data = starcoin_executor::block_execute(
&chain_state,
txns,
block_gas_limit,
None,
WriteSet::default(),
)?;
let txn_infos = executed_data.txn_infos;

// all user txns can be included
Expand Down Expand Up @@ -450,9 +456,14 @@ fn test_block_execute_gas_limit() -> Result<()> {
})
.collect();
txns.insert(0, Transaction::BlockMetadata(block_meta2));
let txn_infos =
starcoin_executor::block_execute(&chain_state, txns, max_block_gas_limit, None)?
.txn_infos;
let txn_infos = starcoin_executor::block_execute(
&chain_state,
txns,
max_block_gas_limit,
None,
WriteSet::default(),
)?
.txn_infos;

// not all user txns can be included
assert_eq!(txn_infos.len() as u64, max_txn_num + 1);
Expand Down
10 changes: 9 additions & 1 deletion txpool/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use starcoin_state_api::ChainStateWriter;
use starcoin_statedb::ChainStateDB;
use starcoin_storage::BlockStore;
use starcoin_txpool_api::{TxPoolSyncService, TxnStatusFullEvent};
use starcoin_types::write_set::WriteSet;
use starcoin_types::{
account_address::{self, AccountAddress},
account_config,
Expand Down Expand Up @@ -259,7 +260,14 @@ async fn test_rollback() -> Result<()> {
0,
Transaction::BlockMetadata(enacted_block.to_metadata(parent_block_header.gas_used())),
);
let root = starcoin_executor::block_execute(&chain_state, txns, u64::MAX, None)?.state_root;
let root = starcoin_executor::block_execute(
&chain_state,
txns,
u64::MAX,
None,
WriteSet::default(),
)?
.state_root;

assert_eq!(root, enacted_block.header().state_root());
chain_state.flush()?;
Expand Down

0 comments on commit 7c55a44

Please sign in to comment.