1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
// Copyright 2019 Conflux Foundation. All rights reserved.
// Conflux is free software and distributed under GNU General Public License.
// See http://www.gnu.org/licenses/
use crate::{
consensus::SharedConsensusGraph,
light_protocol::{message::WitnessInfoWithHeight, Error},
};
use cfx_internal_common::StateRootWithAuxInfo;
use cfx_parameters::consensus::DEFERRED_STATE_EPOCH_COUNT;
use cfx_storage::{
state::{State, StateDbGetOriginalMethods, StateTrait},
StateProof, StorageRootProof,
};
use cfx_types::{Address, AddressSpaceUtil, Bloom, H256};
use primitives::{
Block, BlockHeader, BlockHeaderBuilder, BlockReceipts, CheckInput,
EpochNumber, StorageKeyWithSpace, StorageRoot,
};
pub struct LedgerInfo {
// shared consensus graph
consensus: SharedConsensusGraph,
}
/// NOTE: we use `height` when we talk about headers on the pivot chain
/// we use `epoch` when we talk about execution results
///
/// example: the roots of epoch=5 are stored in the header at height=10
/// (or later, if there is blaming involved)
impl LedgerInfo {
pub fn new(consensus: SharedConsensusGraph) -> Self {
LedgerInfo { consensus }
}
/// Get block `hash`, if it exists.
#[inline]
pub fn block(&self, hash: H256) -> Result<Block, Error> {
self.consensus
.get_data_manager()
.block_by_hash(&hash, false /* update_cache */)
.map(|b| (*b).clone())
.ok_or_else(|| {
Error::InternalError(format!("Block {:?} not found", hash))
.into()
})
}
/// Get header `hash`, if it exists.
#[inline]
pub fn header(&self, hash: H256) -> Result<BlockHeader, Error> {
self.consensus
.get_data_manager()
.block_header_by_hash(&hash)
.map(|h| (*h).clone())
.ok_or_else(|| {
Error::InternalError(format!("Header {:?} not found", hash))
.into()
})
}
/// Get hash of block at `height` on the pivot chain, if it exists.
#[inline]
fn pivot_hash_of(&self, height: u64) -> Result<H256, Error> {
let epoch = EpochNumber::Number(height);
Ok(self.consensus.get_hash_from_epoch_number(epoch)?)
}
/// Get header at `height` on the pivot chain, if it exists.
#[inline]
pub fn pivot_header_of(&self, height: u64) -> Result<BlockHeader, Error> {
let pivot = self.pivot_hash_of(height)?;
self.header(pivot)
}
/// Get all block hashes corresponding to the pivot block at `height`.
/// The hashes are returned in the deterministic execution order.
#[inline]
pub fn block_hashes_in(&self, height: u64) -> Result<Vec<H256>, Error> {
let epoch = EpochNumber::Number(height);
Ok(self.consensus.get_block_hashes_by_epoch(epoch)?)
}
/// Get the correct deferred state root of the block at `height` on the
/// pivot chain based on local execution information.
#[inline]
fn correct_deferred_state_root_hash_of(
&self, height: u64,
) -> Result<H256, Error> {
let epoch = height.saturating_sub(DEFERRED_STATE_EPOCH_COUNT);
let pivot = self.pivot_hash_of(epoch)?;
let commitments = self
.consensus
.get_data_manager()
.get_epoch_execution_commitment_with_db(&pivot)
.ok_or_else(|| {
Error::from(Error::InternalError(format!(
"Execution commitments for {:?} not found",
pivot
)))
})?;
Ok(commitments
.state_root_with_aux_info
.state_root
.compute_state_root_hash())
}
/// Get the correct deferred receipts root of the block at `height` on the
/// pivot chain based on local execution information.
#[inline]
fn correct_deferred_receipts_root_hash_of(
&self, height: u64,
) -> Result<H256, Error> {
let epoch = height.saturating_sub(DEFERRED_STATE_EPOCH_COUNT);
let pivot = self.pivot_hash_of(epoch)?;
let commitments = self
.consensus
.get_data_manager()
.get_epoch_execution_commitment_with_db(&pivot)
.ok_or_else(|| {
Error::from(Error::InternalError(format!(
"Execution commitments for {:?} not found",
pivot
)))
})?;
Ok(commitments.receipts_root)
}
/// Get the correct deferred logs bloom root of the block at `height` on the
/// pivot chain based on local execution information.
#[inline]
fn correct_deferred_logs_root_hash_of(
&self, height: u64,
) -> Result<H256, Error> {
let epoch = height.saturating_sub(DEFERRED_STATE_EPOCH_COUNT);
let pivot = self.pivot_hash_of(epoch)?;
let commitments = self
.consensus
.get_data_manager()
.get_epoch_execution_commitment_with_db(&pivot)
.ok_or_else(|| {
Error::from(Error::InternalError(format!(
"Execution commitments for {:?} not found",
pivot
)))
})?;
Ok(commitments.logs_bloom_hash)
}
/// Get the number of epochs per snapshot period.
#[inline]
pub fn snapshot_epoch_count(&self) -> u32 {
self.consensus.get_data_manager().get_snapshot_epoch_count()
}
/// Get the state trie corresponding to the execution of `epoch`.
#[inline]
fn state_of(&self, epoch: u64) -> Result<State, Error> {
let pivot = self.pivot_hash_of(epoch)?;
let maybe_state_index = self
.consensus
.get_data_manager()
.get_state_readonly_index(&pivot);
let state = maybe_state_index.map(|state_index| {
self.consensus
.get_data_manager()
.storage_manager
.get_state_no_commit_inner(
state_index,
/* try_open = */ true,
true,
)
});
match state {
Some(Ok(Some(state))) => Ok(state),
_ => {
bail!(Error::InternalError(format!(
"State of epoch {} not found",
epoch
)));
}
}
}
/// Get the state trie roots corresponding to the execution of `epoch`.
#[inline]
pub fn state_root_of(
&self, epoch: u64,
) -> Result<StateRootWithAuxInfo, Error> {
match self.state_of(epoch)?.get_state_root() {
Ok(root) => Ok(root),
Err(e) => {
bail!(Error::InternalError(format!(
"State root of epoch {} not found: {:?}",
epoch, e
)));
}
}
}
/// Get the state trie entry under `key` at `epoch`.
#[inline]
pub fn state_entry_at(
&self, epoch: u64, key: &Vec<u8>,
) -> Result<(Option<Vec<u8>>, StateProof), Error> {
let state = self.state_of(epoch)?;
let key = StorageKeyWithSpace::from_key_bytes::<CheckInput>(&key)?;
let (value, proof) = state.get_original_raw_with_proof(key)?;
let value = value.map(|x| x.to_vec());
Ok((value, proof))
}
/// Get the storage root of contract `address` at `epoch`.
#[inline]
pub fn storage_root_of(
&self, epoch: u64, address: &Address,
) -> Result<(StorageRoot, StorageRootProof), Error> {
let state = self.state_of(epoch)?;
Ok(state.get_original_storage_root_with_proof(
&address.with_native_space(),
)?)
}
/// Get the epoch receipts corresponding to the execution of `epoch`.
/// Returns a vector of receipts for each block in `epoch`.
#[inline]
pub fn receipts_of(&self, epoch: u64) -> Result<Vec<BlockReceipts>, Error> {
if epoch == 0 {
return Ok(vec![]);
}
let pivot = self.pivot_hash_of(epoch)?;
let hashes = self.block_hashes_in(epoch)?;
hashes
.into_iter()
.map(|h| {
self.consensus
.get_data_manager()
.block_execution_result_by_hash_with_epoch(
&h, &pivot, false, /* update_pivot_assumption */
false, /* update_cache */
)
.map(|res| (*res.block_receipts).clone())
.ok_or_else(|| {
Error::InternalError(format!(
"Receipts of epoch {} not found",
epoch
))
.into()
})
})
.collect()
}
/// Get the aggregated bloom corresponding to the execution of `epoch`.
#[inline]
pub fn bloom_of(&self, epoch: u64) -> Result<Bloom, Error> {
if epoch == 0 {
return Ok(Bloom::zero());
}
let pivot = self.pivot_hash_of(epoch)?;
let hashes = self.block_hashes_in(epoch)?;
let blooms = hashes
.into_iter()
.map(|h| {
self.consensus
.get_data_manager()
.block_execution_result_by_hash_with_epoch(
&h, &pivot, false, /* update_pivot_assumption */
false, /* update_cache */
)
.map(|res| res.bloom)
.ok_or_else(|| {
Error::InternalError(format!(
"Logs bloom of epoch {} not found",
epoch
))
.into()
})
})
.collect::<Result<Vec<Bloom>, Error>>()?;
Ok(BlockHeaderBuilder::compute_aggregated_bloom(blooms))
}
/// Get a list of all headers for which the block at height `witness` on the
/// pivot chain stores the correct roots based on the blame information.
/// NOTE: This list will contains `witness` in all cases.
#[inline]
pub fn headers_seen_by_witness(
&self, witness: u64,
) -> Result<Vec<u64>, Error> {
let blame = self.pivot_header_of(witness)?.blame() as u64;
// assumption: the witness header is correct
// i.e. it does not blame blocks at or before the genesis block
assert!(witness > blame);
// collect all header heights that were used to compute DSR of `witness`
Ok((0..(blame + 1)).map(|ii| witness - ii).collect())
}
/// Get all correct state roots, receipts roots, and bloom hashes seen by
/// the header at height `witness`.
#[inline]
pub fn witness_info(
&self, witness: u64,
) -> Result<WitnessInfoWithHeight, Error> {
let mut state_root_hashes = vec![];
let mut receipt_hashes = vec![];
let mut bloom_hashes = vec![];
for h in self.headers_seen_by_witness(witness)? {
state_root_hashes
.push(self.correct_deferred_state_root_hash_of(h)?);
receipt_hashes
.push(self.correct_deferred_receipts_root_hash_of(h)?);
bloom_hashes.push(self.correct_deferred_logs_root_hash_of(h)?);
}
Ok(WitnessInfoWithHeight {
height: witness,
state_root_hashes,
receipt_hashes,
bloom_hashes,
})
}
}