Skip to content

Commit 4ef2f56

Browse files
fix(storage): genesis receipts should be saved (#1302)
1 parent b8b7720 commit 4ef2f56

File tree

11 files changed

+92
-106
lines changed

11 files changed

+92
-106
lines changed

core/consensus/src/engine.rs

Lines changed: 3 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,11 @@ use common_logger::{json, log};
1818
use common_merkle::TrieMerkle;
1919
use protocol::traits::{ConsensusAdapter, Context, MessageTarget, NodeInfo};
2020
use protocol::types::{
21-
Block, Bytes, ExecResp, Hash, Hasher, Hex, Log, MerkleRoot, Metadata, Proof, Proposal, Receipt,
22-
SignedTransaction, ValidatorExtend, BASE_FEE_PER_GAS, MAX_BLOCK_GAS_LIMIT, RLP_NULL, U256,
21+
Block, Bytes, ExecResp, Hash, Hasher, Hex, Metadata, Proof, Proposal, SignedTransaction,
22+
ValidatorExtend, BASE_FEE_PER_GAS, MAX_BLOCK_GAS_LIMIT, RLP_NULL,
2323
};
2424
use protocol::{async_trait, tokio::sync::Mutex as AsyncMutex, ProtocolError, ProtocolResult};
2525

26-
use core_executor::logs_bloom;
27-
2826
use crate::message::{
2927
END_GOSSIP_AGGREGATED_VOTE, END_GOSSIP_SIGNED_CHOKE, END_GOSSIP_SIGNED_PROPOSAL,
3028
END_GOSSIP_SIGNED_VOTE,
@@ -591,13 +589,7 @@ impl<Adapter: ConsensusAdapter + 'static> ConsensusEngine<Adapter> {
591589
let block_number = block.header.number;
592590
let block_hash = block.hash();
593591

594-
let (receipts, _logs) = generate_receipts_and_logs(
595-
block_number,
596-
block_hash,
597-
block.header.state_root,
598-
&txs,
599-
&resp,
600-
);
592+
let (receipts, _logs) = block.generate_receipts_and_logs(&txs, &resp);
601593

602594
common_apm::metrics::consensus::ENGINE_ROUND_GAUGE.set(proof.round as i64);
603595

@@ -746,43 +738,6 @@ fn validate_timestamp(
746738
true
747739
}
748740

749-
pub fn generate_receipts_and_logs(
750-
block_number: u64,
751-
block_hash: Hash,
752-
state_root: MerkleRoot,
753-
txs: &[SignedTransaction],
754-
resp: &ExecResp,
755-
) -> (Vec<Receipt>, Vec<Vec<Log>>) {
756-
let mut log_index = 0;
757-
let receipts = txs
758-
.iter()
759-
.enumerate()
760-
.zip(resp.tx_resp.iter())
761-
.map(|((idx, tx), res)| {
762-
let receipt = Receipt {
763-
tx_hash: tx.transaction.hash,
764-
block_number,
765-
block_hash,
766-
tx_index: idx as u32,
767-
state_root,
768-
used_gas: U256::from(res.gas_used),
769-
logs_bloom: logs_bloom(res.logs.iter()),
770-
logs: res.logs.clone(),
771-
log_index,
772-
code_address: res.code_address,
773-
sender: tx.sender,
774-
ret: res.exit_reason.clone(),
775-
removed: res.removed,
776-
};
777-
log_index += res.logs.len() as u32;
778-
receipt
779-
})
780-
.collect::<Vec<_>>();
781-
let logs = receipts.iter().map(|r| r.logs.clone()).collect::<Vec<_>>();
782-
783-
(receipts, logs)
784-
}
785-
786741
fn gauge_txs_len(proposal: &Proposal) {
787742
common_apm::metrics::consensus::ENGINE_ORDER_TX_GAUGE.set(proposal.tx_hashes.len() as i64);
788743
}

core/consensus/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ use protocol::{Display, ProtocolError, ProtocolErrorKind};
2828

2929
pub use crate::adapter::OverlordConsensusAdapter;
3030
pub use crate::consensus::OverlordConsensus;
31-
pub use crate::synchronization::{OverlordSynchronization, RichBlock, SyncStatus, SYNC_STATUS};
31+
pub use crate::synchronization::{OverlordSynchronization, SyncStatus, SYNC_STATUS};
3232
pub use crate::wal::{ConsensusWal, SignedTxsWAL};
3333
pub use overlord::{types::Node, DurationConfig};
3434

core/consensus/src/synchronization.rs

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@ use common_apm::Instant;
77
use common_apm_derive::trace_span;
88
use protocol::tokio::{sync::Mutex, time::sleep};
99
use protocol::traits::{Context, Synchronization, SynchronizationAdapter};
10-
use protocol::types::{Block, Proof, Proposal, Receipt, SignedTransaction, U256};
10+
use protocol::types::{Block, Proof, Proposal, Receipt, RichBlock, SignedTransaction, U256};
1111
use protocol::{async_trait, ProtocolResult};
1212

1313
use crate::status::{CurrentStatus, StatusAgent};
1414
use crate::util::digest_signed_transactions;
15-
use crate::{engine::generate_receipts_and_logs, ConsensusError};
15+
use crate::ConsensusError;
1616

1717
const POLLING_BROADCAST: u64 = 2000;
1818
const ONCE_SYNC_BLOCK_LIMIT: u64 = 50;
@@ -21,12 +21,6 @@ lazy_static::lazy_static! {
2121
pub static ref SYNC_STATUS: RwLock<SyncStatus> = RwLock::new(SyncStatus::default());
2222
}
2323

24-
#[derive(Clone, Debug)]
25-
pub struct RichBlock {
26-
pub block: Block,
27-
pub txs: Vec<SignedTransaction>,
28-
}
29-
3024
pub struct OverlordSynchronization<Adapter: SynchronizationAdapter> {
3125
adapter: Arc<Adapter>,
3226
status: StatusAgent,
@@ -346,13 +340,7 @@ impl<Adapter: SynchronizationAdapter> OverlordSynchronization<Adapter> {
346340
.into());
347341
}
348342

349-
let (receipts, _logs) = generate_receipts_and_logs(
350-
block.header.number,
351-
block_hash,
352-
block.header.state_root,
353-
&rich_block.txs,
354-
&resp,
355-
);
343+
let (receipts, _logs) = rich_block.generate_receipts_and_logs(&resp);
356344

357345
let metadata = self
358346
.adapter

core/consensus/src/tests/synchronization.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,12 @@ use std::sync::Arc;
33
use protocol::{
44
tokio::{self, sync::Mutex as AsyncMutex},
55
traits::{Context, Synchronization},
6-
types::{Block, Header},
6+
types::{Block, Header, RichBlock},
77
};
88

99
use crate::{
1010
status::{CurrentStatus, StatusAgent},
11-
synchronization::{OverlordSynchronization, RichBlock},
11+
synchronization::OverlordSynchronization,
1212
tests::MockSyncAdapter,
1313
util::time_now,
1414
};

core/executor/src/lib.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,7 @@ mod utils;
1111

1212
pub use crate::adapter::{AxonExecutorAdapter, MPTTrie, RocksTrieDB};
1313
pub use crate::system_contract::{metadata::MetadataHandle, DataProvider};
14-
pub use crate::utils::{
15-
code_address, decode_revert_msg, logs_bloom, DefaultFeeAllocator, FeeInlet,
16-
};
14+
pub use crate::utils::{code_address, decode_revert_msg, DefaultFeeAllocator, FeeInlet};
1715

1816
use std::cell::RefCell;
1917
use std::collections::BTreeMap;
@@ -27,9 +25,9 @@ use common_merkle::TrieMerkle;
2725
use protocol::codec::ProtocolCodec;
2826
use protocol::traits::{Backend, Executor, ExecutorAdapter};
2927
use protocol::types::{
30-
data_gas_cost, Account, Config, ExecResp, Hasher, SignedTransaction, TransactionAction, TxResp,
31-
ValidatorExtend, GAS_CALL_TRANSACTION, GAS_CREATE_TRANSACTION, H160, H256, NIL_DATA, RLP_NULL,
32-
U256,
28+
data_gas_cost, logs_bloom, Account, Config, ExecResp, Hasher, SignedTransaction,
29+
TransactionAction, TxResp, ValidatorExtend, GAS_CALL_TRANSACTION, GAS_CREATE_TRANSACTION, H160,
30+
H256, NIL_DATA, RLP_NULL, U256,
3331
};
3432

3533
use crate::precompiles::build_precompile_set;

core/executor/src/utils.rs

Lines changed: 1 addition & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1-
use protocol::types::{Bloom, Hasher, Log, H160, H256, U256};
1+
use protocol::types::{Hasher, H160, H256, U256};
22

33
use crate::FeeAllocate;
44

55
const FUNC_SELECTOR_LEN: usize = 4;
66
const U256_BE_BYTES_LEN: usize = 32;
77
const REVERT_MSG_LEN_OFFSET: usize = FUNC_SELECTOR_LEN + U256_BE_BYTES_LEN;
88
const REVERT_EFFECT_MSG_OFFSET: usize = REVERT_MSG_LEN_OFFSET + U256_BE_BYTES_LEN;
9-
const BLOOM_BYTE_LENGTH: usize = 256;
109
const EXEC_REVERT: &str = "execution reverted: ";
1110

1211
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -73,29 +72,6 @@ pub fn decode_revert_msg(input: &[u8]) -> String {
7372
decode_reason(&input[REVERT_EFFECT_MSG_OFFSET..end_offset])
7473
}
7574

76-
pub fn logs_bloom<'a, I>(logs: I) -> Bloom
77-
where
78-
I: Iterator<Item = &'a Log>,
79-
{
80-
let mut bloom = Bloom::zero();
81-
82-
for log in logs {
83-
m3_2048(&mut bloom, log.address.as_bytes());
84-
for topic in log.topics.iter() {
85-
m3_2048(&mut bloom, topic.as_bytes());
86-
}
87-
}
88-
bloom
89-
}
90-
91-
fn m3_2048(bloom: &mut Bloom, x: &[u8]) {
92-
let hash = Hasher::digest(x).0;
93-
for i in [0, 2, 4] {
94-
let bit = (hash[i + 1] as usize + ((hash[i] as usize) << 8)) & 0x7FF;
95-
bloom.0[BLOOM_BYTE_LENGTH - 1 - bit / 8] |= 1 << (bit % 8);
96-
}
97-
}
98-
9975
#[cfg(test)]
10076
mod tests {
10177
use protocol::codec::{hex_decode, hex_encode};

core/run/src/lib.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ impl Axon {
173173

174174
log::info!("The genesis block is created {:?}", self.genesis.block);
175175

176-
save_block(storage, &self.genesis).await?;
176+
save_block(storage, &self.genesis, &resp).await?;
177177

178178
Ok(())
179179
}
@@ -1053,7 +1053,7 @@ where
10531053
Ok(resp)
10541054
}
10551055

1056-
async fn save_block<S>(storage: &Arc<S>, rich: &RichBlock) -> ProtocolResult<()>
1056+
async fn save_block<S>(storage: &Arc<S>, rich: &RichBlock, resp: &ExecResp) -> ProtocolResult<()>
10571057
where
10581058
S: Storage + 'static,
10591059
{
@@ -1066,6 +1066,9 @@ where
10661066
storage
10671067
.insert_transactions(Context::new(), rich.block.header.number, rich.txs.clone())
10681068
.await?;
1069-
1069+
let (receipts, _logs) = rich.generate_receipts_and_logs(resp);
1070+
storage
1071+
.insert_receipts(Context::new(), rich.block.header.number, receipts)
1072+
.await?;
10701073
Ok(())
10711074
}

protocol/src/types/block.rs

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ use crate::codec::ProtocolCodec;
55
#[cfg(feature = "hex-serialize")]
66
use crate::codec::{serialize_bytes, serialize_uint};
77
use crate::types::{
8-
Bloom, BloomInput, Bytes, ExecResp, Hash, Hasher, MerkleRoot, SignedTransaction, H160, H64,
9-
U256,
8+
logs_bloom, Bloom, BloomInput, Bytes, ExecResp, Hash, Hasher, Log, MerkleRoot, Receipt,
9+
SignedTransaction, H160, H64, U256,
1010
};
1111

1212
pub type BlockNumber = u64;
@@ -142,6 +142,40 @@ impl Block {
142142
pub fn hash(&self) -> Hash {
143143
self.header.hash()
144144
}
145+
146+
pub fn generate_receipts_and_logs(
147+
&self,
148+
txs: &[SignedTransaction],
149+
resp: &ExecResp,
150+
) -> (Vec<Receipt>, Vec<Vec<Log>>) {
151+
let mut log_index = 0;
152+
let receipts = txs
153+
.iter()
154+
.enumerate()
155+
.zip(resp.tx_resp.iter())
156+
.map(|((idx, tx), res)| {
157+
let receipt = Receipt {
158+
tx_hash: tx.transaction.hash,
159+
block_number: self.header.number,
160+
block_hash: self.hash(),
161+
tx_index: idx as u32,
162+
state_root: self.header.state_root,
163+
used_gas: U256::from(res.gas_used),
164+
logs_bloom: logs_bloom(res.logs.iter()),
165+
logs: res.logs.clone(),
166+
log_index,
167+
code_address: res.code_address,
168+
sender: tx.sender,
169+
ret: res.exit_reason.clone(),
170+
removed: res.removed,
171+
};
172+
log_index += res.logs.len() as u32;
173+
receipt
174+
})
175+
.collect::<Vec<_>>();
176+
let logs = receipts.iter().map(|r| r.logs.clone()).collect::<Vec<_>>();
177+
(receipts, logs)
178+
}
145179
}
146180

147181
#[derive(
@@ -205,6 +239,12 @@ pub struct RichBlock {
205239
pub txs: Vec<SignedTransaction>,
206240
}
207241

242+
impl RichBlock {
243+
pub fn generate_receipts_and_logs(&self, resp: &ExecResp) -> (Vec<Receipt>, Vec<Vec<Log>>) {
244+
self.block.generate_receipts_and_logs(&self.txs, resp)
245+
}
246+
}
247+
208248
#[cfg(test)]
209249
mod tests {
210250
use crate::types::{

protocol/src/types/executor.rs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ pub use evm::{backend::Log, Config, ExitError, ExitFatal, ExitReason, ExitRevert
33

44
use rlp_derive::{RlpDecodable, RlpEncodable};
55

6-
use crate::types::{Hash, Header, MerkleRoot, Proposal, H160, U256};
6+
use crate::types::{Bloom, Hash, Hasher, Header, MerkleRoot, Proposal, H160, U256};
7+
8+
const BLOOM_BYTE_LENGTH: usize = 256;
79

810
#[derive(Clone, Debug, PartialEq, Eq)]
911
pub struct ExecResp {
@@ -87,3 +89,26 @@ impl From<&Header> for ExecutorContext {
8789
}
8890
}
8991
}
92+
93+
pub fn logs_bloom<'a, I>(logs: I) -> Bloom
94+
where
95+
I: Iterator<Item = &'a Log>,
96+
{
97+
let mut bloom = Bloom::zero();
98+
99+
for log in logs {
100+
m3_2048(&mut bloom, log.address.as_bytes());
101+
for topic in log.topics.iter() {
102+
m3_2048(&mut bloom, topic.as_bytes());
103+
}
104+
}
105+
bloom
106+
}
107+
108+
fn m3_2048(bloom: &mut Bloom, x: &[u8]) {
109+
let hash = Hasher::digest(x).0;
110+
for i in [0, 2, 4] {
111+
let bit = (hash[i + 1] as usize + ((hash[i] as usize) << 8)) & 0x7FF;
112+
bloom.0[BLOOM_BYTE_LENGTH - 1 - bit / 8] |= 1 << (bit % 8);
113+
}
114+
}

protocol/src/types/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ pub use bytes::{Buf, BufMut, Bytes, BytesMut};
66
pub use ckb_client::*;
77
pub use evm::{backend::*, ExitError, ExitRevert, ExitSucceed};
88
pub use executor::{
9-
AccessList, AccessListItem, Account, Config, ExecResp, ExecutorContext, ExitReason, TxResp,
9+
logs_bloom, AccessList, AccessListItem, Account, Config, ExecResp, ExecutorContext, ExitReason,
10+
TxResp,
1011
};
1112
pub use interoperation::*;
1213
pub use primitive::*;

0 commit comments

Comments
 (0)