Skip to content

Commit

Permalink
block info support and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
EdHastingsCasperAssociation committed Oct 3, 2024
1 parent 4188618 commit e3cb1bc
Show file tree
Hide file tree
Showing 20 changed files with 414 additions and 36 deletions.
8 changes: 8 additions & 0 deletions Cargo.lock

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

3 changes: 1 addition & 2 deletions execution_engine/src/engine_state/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,6 @@ impl ExecutionEngineV1 {
Err(ese) => return WasmV1Result::precondition_failure(gas_limit, ese),
};
let access_rights = entity.extract_access_rights(entity_hash, &named_keys);
let block_time = block_info.block_time;
Executor::new(self.config().clone()).exec(
execution_kind,
args,
Expand All @@ -134,7 +133,7 @@ impl ExecutionEngineV1 {
access_rights,
authorization_keys,
account_hash,
block_time,
block_info,
transaction_hash,
gas_limit,
protocol_version,
Expand Down
15 changes: 15 additions & 0 deletions execution_engine/src/engine_state/wasm_v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,25 @@ impl BlockInfo {
self.state_hash = state_hash;
}

/// State hash.
pub fn state_hash(&self) -> Digest {
self.state_hash
}

/// Block time.
pub fn block_time(&self) -> BlockTime {
self.block_time
}

/// Parent block hash.
pub fn parent_block_hash(&self) -> BlockHash {
self.parent_block_hash
}

/// Block height.
pub fn block_height(&self) -> u64 {
self.block_height
}
}

/// A request to execute the given Wasm on the V1 runtime.
Expand Down
6 changes: 3 additions & 3 deletions execution_engine/src/execution/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,9 @@ pub enum Error {
/// The EntryPoints contains an invalid entry.
#[error("The EntryPoints contains an invalid entry")]
InvalidEntryPointType,
/// Invalid message topic operation.
#[error("The requested operation is invalid for a message topic")]
InvalidMessageTopicOperation,
/// Invalid operation.
#[error("The imputed operation is invalid")]
InvalidImputedOperation,
/// Invalid string encoding.
#[error("Invalid UTF-8 string encoding: {0}")]
InvalidUtf8Encoding(Utf8Error),
Expand Down
12 changes: 6 additions & 6 deletions execution_engine/src/execution/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ use casper_storage::{
};
use casper_types::{
account::AccountHash, addressable_entity::NamedKeys, contract_messages::Messages,
execution::Effects, AddressableEntity, AddressableEntityHash, BlockTime, ContextAccessRights,
execution::Effects, AddressableEntity, AddressableEntityHash, ContextAccessRights,
EntryPointType, Gas, Key, Phase, ProtocolVersion, RuntimeArgs, StoredValue, Tagged,
TransactionHash, U512,
};

use crate::{
engine_state::{execution_kind::ExecutionKind, EngineConfig, WasmV1Result},
engine_state::{execution_kind::ExecutionKind, BlockInfo, EngineConfig, WasmV1Result},
execution::ExecError,
runtime::{Runtime, RuntimeStack},
runtime_context::{CallingAddContractVersion, RuntimeContext},
Expand Down Expand Up @@ -53,7 +53,7 @@ impl Executor {
access_rights: ContextAccessRights,
authorization_keys: BTreeSet<AccountHash>,
account_hash: AccountHash,
blocktime: BlockTime,
block_info: BlockInfo,
txn_hash: TransactionHash,
gas_limit: Gas,
protocol_version: ProtocolVersion,
Expand Down Expand Up @@ -101,7 +101,7 @@ impl Executor {
account_hash,
address_generator,
tracking_copy,
blocktime,
block_info,
protocol_version,
txn_hash,
phase,
Expand Down Expand Up @@ -163,7 +163,7 @@ impl Executor {
account_hash: AccountHash,
address_generator: Rc<RefCell<AddressGenerator>>,
tracking_copy: Rc<RefCell<TrackingCopy<R>>>,
blocktime: BlockTime,
block_info: BlockInfo,
protocol_version: ProtocolVersion,
txn_hash: TransactionHash,
phase: Phase,
Expand All @@ -189,7 +189,7 @@ impl Executor {
address_generator,
tracking_copy,
self.config.clone(),
blocktime,
block_info,
protocol_version,
txn_hash,
phase,
Expand Down
1 change: 1 addition & 0 deletions execution_engine/src/resolvers/v1_function_index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ pub(crate) enum FunctionIndex {
ManageMessageTopic,
EmitMessage,
LoadCallerInformation,
GetBlockInfoIndex,
}

impl From<FunctionIndex> for usize {
Expand Down
4 changes: 4 additions & 0 deletions execution_engine/src/resolvers/v1_resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,10 @@ impl ModuleImportResolver for RuntimeModuleImportResolver {
Signature::new(&[ValueType::I32; 4][..], Some(ValueType::I32)),
FunctionIndex::EmitMessage.into(),
),
"casper_get_block_info" => FuncInstance::alloc_host(
Signature::new(&[ValueType::I32; 2][..], None),
FunctionIndex::GetBlockInfoIndex.into(),
),
_ => {
return Err(InterpreterError::Function(format!(
"host module doesn't export function with name {}",
Expand Down
19 changes: 17 additions & 2 deletions execution_engine/src/runtime/externals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,7 @@ where
)?;
Ok(Some(RuntimeValue::I32(api_error::i32_from(ret))))
}

FunctionIndex::AddContractVersion => {
// args(0) = pointer to package key in wasm memory
// args(1) = size of package key in wasm memory
Expand Down Expand Up @@ -660,6 +661,7 @@ where
)?;
Ok(Some(RuntimeValue::I32(api_error::i32_from(ret))))
}

FunctionIndex::AddPackageVersion => {
// args(0) = pointer to package hash in wasm memory
// args(1) = size of package hash in wasm memory
Expand Down Expand Up @@ -1152,6 +1154,7 @@ where

Ok(Some(RuntimeValue::I32(0)))
}

FunctionIndex::EnableContractVersion => {
// args(0) = pointer to package hash in wasm memory
// args(1) = size of package hash in wasm memory
Expand All @@ -1175,6 +1178,7 @@ where

Ok(Some(RuntimeValue::I32(api_error::i32_from(result))))
}

FunctionIndex::ManageMessageTopic => {
// args(0) = pointer to the serialized topic name string in wasm memory
// args(1) = size of the serialized topic name string in wasm memory
Expand Down Expand Up @@ -1206,11 +1210,11 @@ where
.map_err(|e| Trap::from(ExecError::InvalidUtf8Encoding(e)))?;

if operation_size as usize > MessageTopicOperation::max_serialized_len() {
return Err(Trap::from(ExecError::InvalidMessageTopicOperation));
return Err(Trap::from(ExecError::InvalidImputedOperation));
}
let topic_operation = self
.t_from_mem(operation_ptr, operation_size)
.map_err(|_e| Trap::from(ExecError::InvalidMessageTopicOperation))?;
.map_err(|_e| Trap::from(ExecError::InvalidImputedOperation))?;

// only allow managing messages from stored contracts
if !self.context.get_entity_key().is_smart_contract_key() {
Expand All @@ -1225,6 +1229,7 @@ where

Ok(Some(RuntimeValue::I32(api_error::i32_from(result))))
}

FunctionIndex::EmitMessage => {
// args(0) = pointer to the serialized topic name string in wasm memory
// args(1) = size of the serialized name string in wasm memory
Expand Down Expand Up @@ -1276,6 +1281,16 @@ where
}
Ok(Some(RuntimeValue::I32(api_error::i32_from(result))))
}

FunctionIndex::GetBlockInfoIndex => {
// args(0) = field selector
// args(1) = pointer to output pointer where host will write argument bytes
let (field_idx, dest_ptr): (u8, u32) = Args::parse(args)?;

self.charge_host_function_call(&host_function_costs.get_block_info, [0u32, 0u32])?;
self.get_block_info(field_idx, dest_ptr)?;
Ok(None)
}
}
}
}
51 changes: 43 additions & 8 deletions execution_engine/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,11 +434,48 @@ where
.map_err(|e| ExecError::Interpreter(e.into()).into())
}

/// Writes requested field from runtime context's block info to dest_ptr in the Wasm memory.
fn get_block_info(&self, field_idx: u8, dest_ptr: u32) -> Result<(), Trap> {
if field_idx == 0 {
// original functionality
return self.get_blocktime(dest_ptr);
}
let block_info = self.context.get_block_info();

let mut data: Vec<u8> = vec![];
if field_idx == 1 {
data = block_info
.block_height()
.into_bytes()
.map_err(ExecError::BytesRepr)?;
}
if field_idx == 2 {
data = block_info
.parent_block_hash()
.into_bytes()
.map_err(ExecError::BytesRepr)?;
}
if field_idx == 3 {
data = block_info
.state_hash()
.into_bytes()
.map_err(ExecError::BytesRepr)?;
}
if data.is_empty() {
Err(ExecError::InvalidImputedOperation.into())
} else {
Ok(self
.try_get_memory()?
.set(dest_ptr, &data)
.map_err(|e| ExecError::Interpreter(e.into()))?)
}
}

/// Writes current blocktime to dest_ptr in Wasm memory.
fn get_blocktime(&self, dest_ptr: u32) -> Result<(), Trap> {
let blocktime = self
.context
.get_blocktime()
let block_info = self.context.get_block_info();
let blocktime = block_info
.block_time()
.into_bytes()
.map_err(ExecError::BytesRepr)?;
self.try_get_memory()?
Expand Down Expand Up @@ -2017,10 +2054,8 @@ where

for (_, topic_hash) in previous_message_topics.iter() {
let topic_key = Key::message_topic(entity_addr, *topic_hash);
let summary = StoredValue::MessageTopic(MessageTopicSummary::new(
0,
self.context.get_blocktime(),
));
let block_time = self.context.get_block_info().block_time();
let summary = StoredValue::MessageTopic(MessageTopicSummary::new(0, block_time));
self.context.metered_write_gs_unsafe(topic_key, summary)?;
}

Expand Down Expand Up @@ -3557,7 +3592,7 @@ where
return Ok(Err(ApiError::MessageTopicNotRegistered));
};

let current_blocktime = self.context.get_blocktime();
let current_blocktime = self.context.get_block_info().block_time();
let topic_message_index = if prev_topic_summary.blocktime() != current_blocktime {
for index in 1..prev_topic_summary.message_count() {
self.context
Expand Down
24 changes: 14 additions & 10 deletions execution_engine/src/runtime_context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ use casper_types::{
DICTIONARY_ITEM_KEY_MAX_LENGTH, KEY_HASH_LENGTH, U512,
};

use crate::{engine_state::EngineConfig, execution::ExecError};
use crate::{
engine_state::{BlockInfo, EngineConfig},
execution::ExecError,
};

/// Number of bytes returned from the `random_bytes` function.
pub const RANDOM_BYTES_COUNT: usize = 32;
Expand All @@ -64,7 +67,7 @@ pub struct RuntimeContext<'a, R> {
access_rights: ContextAccessRights,
args: RuntimeArgs,
authorization_keys: BTreeSet<AccountHash>,
blocktime: BlockTime,
block_info: BlockInfo,
transaction_hash: TransactionHash,
gas_limit: Gas,
gas_counter: Gas,
Expand Down Expand Up @@ -104,7 +107,7 @@ where
address_generator: Rc<RefCell<AddressGenerator>>,
tracking_copy: Rc<RefCell<TrackingCopy<R>>>,
engine_config: EngineConfig,
blocktime: BlockTime,
block_info: BlockInfo,
protocol_version: ProtocolVersion,
transaction_hash: TransactionHash,
phase: Phase,
Expand Down Expand Up @@ -132,7 +135,7 @@ where
entity_key,
authorization_keys,
account_hash,
blocktime,
block_info,
transaction_hash,
gas_limit,
gas_counter,
Expand Down Expand Up @@ -165,7 +168,7 @@ where
let tracking_copy = self.state();
let engine_config = self.engine_config.clone();

let blocktime = self.blocktime;
let block_info = self.block_info;
let protocol_version = self.protocol_version;
let transaction_hash = self.transaction_hash;
let phase = self.phase;
Expand All @@ -186,7 +189,7 @@ where
entity_key,
authorization_keys,
account_hash,
blocktime,
block_info,
transaction_hash,
gas_limit,
gas_counter,
Expand Down Expand Up @@ -265,9 +268,9 @@ where
self.remove_key_from_entity(name)
}

/// Returns the block time.
pub fn get_blocktime(&self) -> BlockTime {
self.blocktime
/// Returns block info.
pub fn get_block_info(&self) -> BlockInfo {
self.block_info
}

/// Returns the transaction hash.
Expand Down Expand Up @@ -1425,7 +1428,8 @@ where
};

let topic_key = Key::Message(MessageAddr::new_topic_addr(entity_addr, topic_name_hash));
let summary = StoredValue::MessageTopic(MessageTopicSummary::new(0, self.get_blocktime()));
let block_time = self.block_info.block_time();
let summary = StoredValue::MessageTopic(MessageTopicSummary::new(0, block_time));

let entity_value = self.addressable_entity_to_validated_value(entity)?;

Expand Down
Loading

0 comments on commit e3cb1bc

Please sign in to comment.