Skip to content

Commit

Permalink
perf: use constant values as default values
Browse files Browse the repository at this point in the history
  • Loading branch information
yangby-cryptape committed Aug 15, 2023
1 parent 4ef2f56 commit 885aea6
Show file tree
Hide file tree
Showing 8 changed files with 89 additions and 26 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions core/consensus/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use common_logger::{json, log};
use common_merkle::TrieMerkle;
use protocol::traits::{ConsensusAdapter, Context, MessageTarget, NodeInfo};
use protocol::types::{
Block, Bytes, ExecResp, Hash, Hasher, Hex, Metadata, Proof, Proposal, SignedTransaction,
Block, Bytes, ExecResp, Hash, Hex, Metadata, Proof, Proposal, SignedTransaction,
ValidatorExtend, BASE_FEE_PER_GAS, MAX_BLOCK_GAS_LIMIT, RLP_NULL,
};
use protocol::{async_trait, tokio::sync::Mutex as AsyncMutex, ProtocolError, ProtocolResult};
Expand Down Expand Up @@ -550,7 +550,7 @@ impl<Adapter: ConsensusAdapter + 'static> ConsensusEngine<Adapter> {
})
};

let stxs_hash = Hasher::digest(rlp::encode_list(signed_txs));
let stxs_hash = digest_signed_transactions(signed_txs);

if stxs_hash != proposal.signed_txs_hash {
return Err(ConsensusError::InvalidOrderSignedTransactionsHash {
Expand Down
10 changes: 8 additions & 2 deletions core/consensus/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,17 @@ use common_crypto::{
BlsPrivateKey, BlsPublicKey, BlsSignature, BlsSignatureVerify, HashValue, PrivateKey, Signature,
};
use protocol::traits::Context;
use protocol::types::{Address, Bytes, Hash, Hasher, Hex, MerkleRoot, SignedTransaction};
use protocol::types::{
Address, Bytes, Hash, Hasher, Hex, MerkleRoot, SignedTransaction, RLP_EMPTY_LIST,
};
use protocol::{ProtocolError, ProtocolResult};

pub fn digest_signed_transactions(stxs: &[SignedTransaction]) -> Hash {
Hasher::digest(rlp::encode_list(stxs))
if stxs.is_empty() {
RLP_EMPTY_LIST
} else {
Hasher::digest(rlp::encode_list(stxs))
}
}

pub fn time_now() -> u64 {
Expand Down
20 changes: 14 additions & 6 deletions core/executor/benches/revm_adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,12 +331,20 @@ where
tx_outputs.push(resp);
});

ExecResp {
state_root: evm.db().unwrap().trie.commit().unwrap(),
receipt_root: TrieMerkle::from_iter(hashes.iter().enumerate())
let receipt_root = if hashes.is_empty() {
RLP_NULL
} else {
TrieMerkle::from_iter(hashes.iter().enumerate())
.root_hash()
.unwrap_or_default(),
gas_used: total_gas_used,
tx_resp: tx_outputs,
.unwrap_or_else(|err| {
panic!("failed to calculate trie root hash for receipts since {err}")
})
};

ExecResp {
state_root: evm.db().unwrap().trie.commit().unwrap(),
receipt_root,
gas_used: total_gas_used,
tx_resp: tx_outputs,
}
}
17 changes: 13 additions & 4 deletions core/executor/src/adapter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,11 @@ where
res.unwrap_or_default().to_vec()
}

// ### Notes
//
// - If a MPT tree is empty, the root should be `RLP_NULL`.
// - In this function, when returns `H256::default()`, that means the tree is
// not initialized.
fn storage(&self, address: H160, index: H256) -> H256 {
if let Ok(raw) = self.trie.get(address.as_bytes()) {
if raw.is_none() {
Expand Down Expand Up @@ -326,11 +331,15 @@ where
let _ = storage_trie.insert(k.as_bytes(), v.as_bytes());
});

let storage_root = storage_trie
.commit()
.unwrap_or_else(|err| panic!("failed to update the trie storage since {err}"));

let mut new_account = Account {
nonce: basic.nonce,
balance: basic.balance,
code_hash: old_account.code_hash,
storage_root: storage_trie.commit().unwrap_or(RLP_NULL),
nonce: basic.nonce,
balance: basic.balance,
code_hash: old_account.code_hash,
storage_root,
};

if let Some(c) = code {
Expand Down
29 changes: 18 additions & 11 deletions core/executor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,12 +187,15 @@ impl Executor for AxonExecutor {

// self.update_system_contract_roots_for_external_module();

// TODO When fixes receipt_root, set to RLP_NULL when empty
let receipt_root = TrieMerkle::from_iter(hashes.iter().enumerate())
.root_hash()
.unwrap_or_else(|err| {
panic!("failed to calculate trie root hash for receipts since {err}")
});
let receipt_root = if hashes.is_empty() {
RLP_NULL
} else {
TrieMerkle::from_iter(hashes.iter().enumerate())
.root_hash()
.unwrap_or_else(|err| {
panic!("failed to calculate trie root hash for receipts since {err}")
})
};

ExecResp {
state_root: new_state_root,
Expand Down Expand Up @@ -381,11 +384,15 @@ impl AxonExecutor {
// commit changes by all txs included in this block only once
let new_state_root = adapter.commit();

let receipt_root = TrieMerkle::from_iter(hashes.iter().enumerate())
.root_hash()
.unwrap_or_else(|err| {
panic!("failed to calculate trie root hash for receipts since {err}")
});
let receipt_root = if hashes.is_empty() {
RLP_NULL
} else {
TrieMerkle::from_iter(hashes.iter().enumerate())
.root_hash()
.unwrap_or_else(|err| {
panic!("failed to calculate trie root hash for receipts since {err}")
})
};

ExecResp {
state_root: new_state_root,
Expand Down
2 changes: 2 additions & 0 deletions protocol/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ hex = "0.4"
serde_json = "1.0"
toml = "0.7"

common-merkle = { path = "../common/merkle" }

[features]
default = ["hex-serialize"]
hex-serialize = []
32 changes: 31 additions & 1 deletion protocol/src/types/primitive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,19 @@ pub const NIL_DATA: H256 = H256([
0xe5, 0x00, 0xb6, 0x53, 0xca, 0x82, 0x27, 0x3b, 0x7b, 0xfa, 0xd8, 0x04, 0x5d, 0x85, 0xa4, 0x70,
]);

// Same value as `hash(rlp(null))`.
// Also be same value as the `root_hash` of an empty `TrieMerkle`.
pub const RLP_NULL: H256 = H256([
0x56, 0xe8, 0x1f, 0x17, 0x1b, 0xcc, 0x55, 0xa6, 0xff, 0x83, 0x45, 0xe6, 0x92, 0xc0, 0xf8, 0x6e,
0x5b, 0x48, 0xe0, 0x1b, 0x99, 0x6c, 0xad, 0xc0, 0x01, 0x62, 0x2f, 0xb5, 0xe3, 0x63, 0xb4, 0x21,
]);

// Same value as `hash(rlp([]))`.
pub const RLP_EMPTY_LIST: H256 = H256([
0x1d, 0xcc, 0x4d, 0xe8, 0xde, 0xc7, 0x5d, 0x7a, 0xab, 0x85, 0xb5, 0x67, 0xb6, 0xcc, 0xd4, 0x1a,
0xd3, 0x12, 0x45, 0x1b, 0x94, 0x8a, 0x74, 0x13, 0xf0, 0xa1, 0x42, 0xfd, 0x40, 0xd4, 0x93, 0x47,
]);

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DBBytes(pub Bytes);

Expand Down Expand Up @@ -481,6 +489,8 @@ mod tests {
use super::*;
use std::fs;

use common_merkle::TrieMerkle;

#[test]
fn test_eip55() {
let addr = "0x35e70c3f5a794a77efc2ec5ba964bffcc7fd2c0a";
Expand Down Expand Up @@ -510,10 +520,30 @@ mod tests {
}

#[test]
fn test_hash_empty() {
fn test_default_values() {
let bytes = Hex::empty();
let hash = Hasher::digest(bytes.as_bytes());
assert_eq!(hash, NIL_DATA);

let h256_default = H256::default();
assert!(h256_default.is_zero());

let null_data: &[u8] = &[];
let rlp_null_data = rlp::encode(&null_data);
assert_eq!(&rlp_null_data, &rlp::NULL_RLP[..]);

let empty_list: Vec<u8> = vec![];
let rlp_empty_list = rlp::encode_list(&empty_list);
assert_eq!(&rlp_empty_list, &rlp::EMPTY_LIST_RLP[..]);

let hash = Hasher::digest(rlp::NULL_RLP);
assert_eq!(hash, RLP_NULL);

let hash = Hasher::digest(rlp::EMPTY_LIST_RLP);
assert_eq!(hash, RLP_EMPTY_LIST);

let root = TrieMerkle::default().root_hash().unwrap();
assert_eq!(root, RLP_NULL);
}

#[test]
Expand Down

0 comments on commit 885aea6

Please sign in to comment.