Skip to content

Commit

Permalink
refactor: insert genesis hardfork to DB directly
Browse files Browse the repository at this point in the history
  • Loading branch information
Eason authored and driftluo committed Oct 11, 2023
1 parent 77d59f4 commit 535454d
Show file tree
Hide file tree
Showing 6 changed files with 46 additions and 42 deletions.
31 changes: 13 additions & 18 deletions common/config-parser/src/types/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,29 +209,24 @@ impl Genesis {
transactions_root: RLP_NULL,
signed_txs_hash: RLP_EMPTY_LIST,
timestamp: self.timestamp,
// todo: if Hardforkinput is empty, it must change to latest hardfork info to init
// genesis
extra_data: {
vec![ExtraData {
inner: {
let mut info = Into::<HardforkInfoInner>::into(HardforkInput {
hardforks: self.hardforks.clone(),
block_number: 0,
});

if info.flags.is_zero() {
info.flags = H256::from_low_u64_be(HardforkName::all().to_be());
}

info.encode().unwrap()
},
}]
},
base_fee_per_gas: self.base_fee_per_gas,
chain_id: self.chain_id,
..Default::default()
}
}

pub fn generate_hardfork_info(&self) -> HardforkInfoInner {
let mut info = Into::<HardforkInfoInner>::into(HardforkInput {
hardforks: self.hardforks.clone(),
block_number: 0,
});

if info.flags.is_zero() {
info.flags = H256::from_low_u64_be(HardforkName::all().to_be());
}

info
}
}

#[derive(Clone, Debug, Deserialize, Args)]
Expand Down
10 changes: 4 additions & 6 deletions core/executor/src/system_contract/metadata/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@ impl<Adapter: ExecutorAdapter + ApplyBackend> SystemContract<Adapter>

fn after_block_hook(&self, adapter: &mut Adapter) {
let block_number = adapter.block_number();
if block_number.is_zero() {
return;
}

let root = CURRENT_METADATA_ROOT.with(|r| *r.borrow());

let mut store = MetadataStore::new(root).unwrap();
Expand All @@ -128,12 +132,6 @@ impl<Adapter: ExecutorAdapter + ApplyBackend> SystemContract<Adapter>

HARDFORK_INFO.swap(Arc::new(hardfork));

if block_number.is_zero() {
let changes = generate_mpt_root_changes(adapter, Self::ADDRESS);
adapter.apply(changes, vec![], false);
return;
}

if let Err(e) = store.update_propose_count(block_number.as_u64(), &adapter.origin()) {
panic!("Update propose count at {:?} failed: {:?}", block_number, e)
}
Expand Down
9 changes: 5 additions & 4 deletions core/executor/src/system_contract/metadata/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use crate::{adapter::RocksTrieDB, MPTTrie, CURRENT_METADATA_ROOT};
/// | -------------------- | ------------------------ |
/// | EPOCH_SEGMENT_KEY | `EpochSegment.encode()` |
/// | CKB_RELATED_INFO_KEY | `CkbRelatedInfo.encode()`|
/// | HARDFORK_KEY | `HardforkInfo.encode()` |
/// | epoch_0.be_bytes() | `Metadata.encode()` |
/// | epoch_1.be_bytes() | `Metadata.encode()` |
/// | ... | ... |
Expand Down Expand Up @@ -120,10 +121,9 @@ impl MetadataStore {
)?;
self.trie
.insert(inner.epoch.to_be_bytes().to_vec(), inner.encode()?.to_vec())?;
self.trie.insert(
CONSENSUS_CONFIG.as_bytes().to_vec(),
encode_consensus_config(current_hardfork, config.encode()?.to_vec()),
)?;
let config = encode_consensus_config(current_hardfork, config.encode()?.to_vec());
self.trie
.insert(CONSENSUS_CONFIG.as_bytes().to_vec(), config)?;
let new_root = self.trie.commit()?;
CURRENT_METADATA_ROOT.with(|r| *r.borrow_mut() = new_root);

Expand Down Expand Up @@ -231,6 +231,7 @@ impl MetadataStore {
},
}
};

self.trie.insert(
HARDFORK_KEY.as_bytes().to_vec(),
current_info.encode()?.to_vec(),
Expand Down
11 changes: 8 additions & 3 deletions core/executor/src/system_contract/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ use parking_lot::RwLock;
use rocksdb::DB;

use protocol::traits::{CkbDataProvider, ExecutorAdapter};
use protocol::types::{Bytes, Hasher, Metadata, SignedTransaction, TxResp, H160, H256};
use protocol::types::{
Bytes, HardforkInfoInner, Hasher, Metadata, SignedTransaction, TxResp, H160, H256,
};
use protocol::{ckb_blake2b_256, ProtocolResult};

use crate::adapter::RocksTrieDB;
Expand Down Expand Up @@ -115,9 +117,10 @@ pub fn init<Adapter: ExecutorAdapter + ApplyBackend>(
db: Arc<DB>,
adapter: &mut Adapter,
metadata_list: &[Metadata],
hardfork: HardforkInfoInner,
) -> ProtocolResult<(H256, H256)> {
let ret = init_system_contract_db(db, adapter);
init_metadata(adapter, ret.0, metadata_list)?;
init_metadata_and_hardfork(adapter, ret.0, metadata_list, hardfork)?;

Ok(ret)
}
Expand Down Expand Up @@ -165,16 +168,18 @@ pub fn init_system_contract_db<Adapter: ExecutorAdapter + ApplyBackend>(

/// This method is used for insert the first two metadata, so the
/// `metadata_list.len()` should be equal to 2.
fn init_metadata<Adapter: ExecutorAdapter + ApplyBackend>(
fn init_metadata_and_hardfork<Adapter: ExecutorAdapter + ApplyBackend>(
adapter: &mut Adapter,
metadata_root: H256,
metadata_list: &[Metadata],
hardfork: HardforkInfoInner,
) -> ProtocolResult<()> {
debug_assert!(metadata_list.len() == 2);

let mut store = MetadataStore::new(metadata_root)?;
store.append_metadata(&metadata_list[0])?;
store.append_metadata(&metadata_list[1])?;
store.set_hardfork_info(hardfork.block_number, hardfork.flags)?;

let changes = generate_mpt_root_changes(adapter, METADATA_CONTRACT_ADDRESS);
adapter.apply(changes, vec![], false);
Expand Down
13 changes: 9 additions & 4 deletions core/run/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -456,9 +456,13 @@ async fn execute_genesis(
tmp
};

let resp = execute_genesis_transactions(&partial_genesis, db_group, &spec.accounts, &[
metadata_0, metadata_1,
])?;
let resp = execute_genesis_transactions(
&partial_genesis,
db_group,
&spec.accounts,
&[metadata_0, metadata_1],
spec.genesis.generate_hardfork_info(),
)?;

partial_genesis.block.header.state_root = resp.state_root;
partial_genesis.block.header.receipts_root = resp.receipt_root;
Expand Down Expand Up @@ -488,6 +492,7 @@ fn execute_genesis_transactions(
db_group: &DatabaseGroup,
accounts: &[InitialAccount],
metadata_list: &[Metadata],
hardfork: HardforkInfoInner,
) -> ProtocolResult<ExecResp> {
let state_root = MPTTrie::new(db_group.trie_db())
.insert_accounts(accounts)
Expand All @@ -500,7 +505,7 @@ fn execute_genesis_transactions(
Proposal::new_without_state_root(&rich.block.header).into(),
)?;

system_contract::init(db_group.inner_db(), &mut backend, metadata_list)?;
system_contract::init(db_group.inner_db(), &mut backend, metadata_list, hardfork)?;

let resp = AxonExecutor.exec(&mut backend, &rich.txs, &[]);

Expand Down
14 changes: 7 additions & 7 deletions core/run/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,10 +279,12 @@ fn generate_memory_mpt_root(metadata_0: Metadata, metadata_1: Metadata) -> Vec<u
memory_mpt
.insert(EPOCH_SEGMENT_KEY.as_bytes().to_vec(), seg.as_bytes())
.unwrap();

seg.append_endpoint(metadata_0.version.end).unwrap();
memory_mpt
.insert(EPOCH_SEGMENT_KEY.as_bytes().to_vec(), seg.as_bytes())
.unwrap();

seg.append_endpoint(metadata_1.version.end).unwrap();
memory_mpt
.insert(EPOCH_SEGMENT_KEY.as_bytes().to_vec(), seg.as_bytes())
Expand Down Expand Up @@ -325,15 +327,13 @@ fn generate_memory_mpt_root(metadata_0: Metadata, metadata_1: Metadata) -> Vec<u
flags: H256::from_low_u64_be(HardforkName::all().to_be()),
block_number: 0,
};
let hardfork = HardforkInfo { inner: vec![info] }
.encode()
.unwrap()
.to_vec();

memory_mpt
.insert(
HARDFORK_KEY.as_bytes().to_vec(),
HardforkInfo { inner: vec![info] }
.encode()
.unwrap()
.to_vec(),
)
.insert(HARDFORK_KEY.as_bytes().to_vec(), hardfork)
.unwrap();
memory_mpt.root().unwrap()
}
Expand Down

0 comments on commit 535454d

Please sign in to comment.