use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::onchain_runtime::state::{ChargedState, ContractState};
use moonproof_ledger::serialize::{tagged_deserialize, tagged_serialize};
use moonproof_ledger::storage::db::InMemoryDB;
use crate::error::{ContractRuntimeError, Result};
#[derive(Debug, Clone)]
pub struct ContractRuntimeState {
address: ContractAddress,
current_state: ContractState<InMemoryDB>,
last_observed_tx_id: Option<i64>,
last_observed_block_height: Option<i64>,
}
impl ContractRuntimeState {
#[must_use]
pub fn new(address: ContractAddress, current_state: ContractState<InMemoryDB>) -> Self {
Self {
address,
current_state,
last_observed_tx_id: None,
last_observed_block_height: None,
}
}
#[must_use]
pub fn with_observed(
address: ContractAddress,
current_state: ContractState<InMemoryDB>,
last_observed_tx_id: Option<i64>,
last_observed_block_height: Option<i64>,
) -> Self {
Self {
address,
current_state,
last_observed_tx_id,
last_observed_block_height,
}
}
pub fn apply_observed(
&mut self,
current_state: ContractState<InMemoryDB>,
tx_id: i64,
block_height: i64,
) {
self.current_state = current_state;
self.last_observed_tx_id = Some(match self.last_observed_tx_id {
Some(prev) => prev.max(tx_id),
None => tx_id,
});
self.last_observed_block_height = Some(match self.last_observed_block_height {
Some(prev) => prev.max(block_height),
None => block_height,
});
}
#[inline]
#[must_use]
pub fn address(&self) -> &ContractAddress {
&self.address
}
#[must_use]
pub fn address_hex(&self) -> String {
contract_address_to_hex(&self.address)
}
#[inline]
#[must_use]
pub fn current_state(&self) -> &ContractState<InMemoryDB> {
&self.current_state
}
#[inline]
#[must_use]
pub fn charged_state(&self) -> &ChargedState<InMemoryDB> {
&self.current_state.data
}
#[inline]
#[must_use]
pub fn last_observed_tx_id(&self) -> Option<i64> {
self.last_observed_tx_id
}
#[inline]
#[must_use]
pub fn last_observed_block_height(&self) -> Option<i64> {
self.last_observed_block_height
}
}
#[must_use]
pub fn contract_address_to_hex(address: &ContractAddress) -> String {
hex::encode(address.0 .0)
}
pub fn decode_contract_address(hex_str: &str) -> Result<ContractAddress> {
let bytes = hex::decode(hex_str)?;
if bytes.len() != 32 {
return Err(ContractRuntimeError::Deserialize {
context: "decode_contract_address: expected 32 bytes",
source: std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("got {} bytes", bytes.len()),
),
});
}
let mut hash_bytes = [0u8; 32];
hash_bytes.copy_from_slice(&bytes);
Ok(ContractAddress(
moonproof_ledger::base_crypto::hash::HashOutput(hash_bytes),
))
}
pub fn decode_contract_state(hex_str: &str) -> Result<ContractState<InMemoryDB>> {
let bytes = hex::decode(hex_str)?;
tagged_deserialize::<ContractState<InMemoryDB>>(&mut bytes.as_slice()).map_err(|e| {
ContractRuntimeError::Deserialize {
context: "tagged_deserialize(ContractState)",
source: e,
}
})
}
pub fn encode_contract_state(state: &ContractState<InMemoryDB>) -> Result<String> {
let mut buf = Vec::new();
tagged_serialize(state, &mut buf).map_err(|e| ContractRuntimeError::Serialize {
context: "tagged_serialize(ContractState)",
source: e,
})?;
Ok(hex::encode(buf))
}
#[cfg(test)]
mod tests {
use super::*;
use moonproof_ledger::base_crypto::hash::{HashOutput, PERSISTENT_HASH_BYTES};
use moonproof_ledger::onchain_runtime::state::ContractState;
fn dummy_contract_state() -> ContractState<InMemoryDB> {
use moonproof_ledger::onchain_runtime::state::{
ContractMaintenanceAuthority, EntryPointBuf,
};
use moonproof_ledger::storage::storage::HashMap;
let op_key: EntryPointBuf = b"noop"[..].into();
ContractState::<InMemoryDB>::new(
moonproof_ledger::onchain_runtime::state::StateValue::Null,
HashMap::new().insert(op_key, moonproof_ledger::contract_operation(None)),
ContractMaintenanceAuthority::default(),
)
}
fn dummy_address(byte: u8) -> ContractAddress {
ContractAddress(HashOutput([byte; PERSISTENT_HASH_BYTES]))
}
#[test]
fn new_stores_address_and_state() {
let addr = dummy_address(0x01);
let state = ContractRuntimeState::new(addr, dummy_contract_state());
assert_eq!(state.address(), &addr);
assert_eq!(state.address_hex().len(), 64);
assert!(state.last_observed_tx_id().is_none());
assert!(state.last_observed_block_height().is_none());
assert_eq!(
state.address_hex(),
"0101010101010101010101010101010101010101010101010101010101010101",
);
}
#[test]
fn charged_state_is_current_state_data() {
let state = ContractRuntimeState::new(dummy_address(0x02), dummy_contract_state());
let charged = state.charged_state();
let from_full = &state.current_state().data;
assert!(std::ptr::eq(charged, from_full));
}
#[test]
fn contract_address_roundtrips_through_hex() {
let addr = dummy_address(0xab);
let hex = contract_address_to_hex(&addr);
let back = decode_contract_address(&hex).unwrap();
assert_eq!(addr, back);
}
#[test]
fn decode_contract_address_rejects_short_input() {
let err = decode_contract_address("deadbeef").unwrap_err();
matches!(err, ContractRuntimeError::Deserialize { .. });
}
#[test]
fn decode_contract_address_rejects_invalid_hex() {
let err = decode_contract_address("not-hex").unwrap_err();
matches!(err, ContractRuntimeError::HexDecode(_));
}
#[test]
fn contract_state_roundtrips_through_hex() {
let cs = dummy_contract_state();
let hex = encode_contract_state(&cs).unwrap();
let back = decode_contract_state(&hex).unwrap();
let reencoded = encode_contract_state(&back).unwrap();
assert_eq!(hex, reencoded);
}
#[test]
fn decode_contract_state_rejects_malformed_hex() {
let err = decode_contract_state("zzzz").unwrap_err();
matches!(err, ContractRuntimeError::HexDecode(_));
}
#[test]
fn decode_contract_state_rejects_truncated_payload() {
let err = decode_contract_state("aa").unwrap_err();
matches!(err, ContractRuntimeError::Deserialize { .. });
}
#[test]
fn apply_observed_advances_markers() {
let addr = dummy_address(0x03);
let mut state = ContractRuntimeState::new(addr, dummy_contract_state());
state.apply_observed(dummy_contract_state(), 7, 42);
assert_eq!(state.last_observed_tx_id(), Some(7));
assert_eq!(state.last_observed_block_height(), Some(42));
state.apply_observed(dummy_contract_state(), 3, 10);
assert_eq!(state.last_observed_tx_id(), Some(7));
assert_eq!(state.last_observed_block_height(), Some(42));
}
}