moonproof_runtime/
state.rs1use moonproof_ledger::coin_structure::contract::ContractAddress;
23use moonproof_ledger::onchain_runtime::state::{ChargedState, ContractState};
24use moonproof_ledger::serialize::{tagged_deserialize, tagged_serialize};
25use moonproof_ledger::storage::db::InMemoryDB;
26
27use crate::error::{ContractRuntimeError, Result};
28
29#[derive(Debug, Clone)]
31pub struct ContractRuntimeState {
32 address: ContractAddress,
33 current_state: ContractState<InMemoryDB>,
34 last_observed_tx_id: Option<i64>,
35 last_observed_block_height: Option<i64>,
36}
37
38impl ContractRuntimeState {
39 #[must_use]
42 pub fn new(address: ContractAddress, current_state: ContractState<InMemoryDB>) -> Self {
43 Self {
44 address,
45 current_state,
46 last_observed_tx_id: None,
47 last_observed_block_height: None,
48 }
49 }
50
51 #[must_use]
54 pub fn with_observed(
55 address: ContractAddress,
56 current_state: ContractState<InMemoryDB>,
57 last_observed_tx_id: Option<i64>,
58 last_observed_block_height: Option<i64>,
59 ) -> Self {
60 Self {
61 address,
62 current_state,
63 last_observed_tx_id,
64 last_observed_block_height,
65 }
66 }
67
68 pub fn apply_observed(
71 &mut self,
72 current_state: ContractState<InMemoryDB>,
73 tx_id: i64,
74 block_height: i64,
75 ) {
76 self.current_state = current_state;
77 self.last_observed_tx_id = Some(match self.last_observed_tx_id {
78 Some(prev) => prev.max(tx_id),
79 None => tx_id,
80 });
81 self.last_observed_block_height = Some(match self.last_observed_block_height {
82 Some(prev) => prev.max(block_height),
83 None => block_height,
84 });
85 }
86
87 #[inline]
89 #[must_use]
90 pub fn address(&self) -> &ContractAddress {
91 &self.address
92 }
93
94 #[must_use]
95 pub fn address_hex(&self) -> String {
96 contract_address_to_hex(&self.address)
97 }
98
99 #[inline]
100 #[must_use]
101 pub fn current_state(&self) -> &ContractState<InMemoryDB> {
102 &self.current_state
103 }
104
105 #[inline]
106 #[must_use]
107 pub fn charged_state(&self) -> &ChargedState<InMemoryDB> {
108 &self.current_state.data
109 }
110
111 #[inline]
112 #[must_use]
113 pub fn last_observed_tx_id(&self) -> Option<i64> {
114 self.last_observed_tx_id
115 }
116
117 #[inline]
118 #[must_use]
119 pub fn last_observed_block_height(&self) -> Option<i64> {
120 self.last_observed_block_height
121 }
122}
123
124#[must_use]
127pub fn contract_address_to_hex(address: &ContractAddress) -> String {
128 hex::encode(address.0 .0)
129}
130
131pub fn decode_contract_address(hex_str: &str) -> Result<ContractAddress> {
133 let bytes = hex::decode(hex_str)?;
134 if bytes.len() != 32 {
135 return Err(ContractRuntimeError::Deserialize {
136 context: "decode_contract_address: expected 32 bytes",
137 source: std::io::Error::new(
138 std::io::ErrorKind::InvalidData,
139 format!("got {} bytes", bytes.len()),
140 ),
141 });
142 }
143 let mut hash_bytes = [0u8; 32];
144 hash_bytes.copy_from_slice(&bytes);
145 Ok(ContractAddress(
146 moonproof_ledger::base_crypto::hash::HashOutput(hash_bytes),
147 ))
148}
149
150pub fn decode_contract_state(hex_str: &str) -> Result<ContractState<InMemoryDB>> {
153 let bytes = hex::decode(hex_str)?;
154 tagged_deserialize::<ContractState<InMemoryDB>>(&mut bytes.as_slice()).map_err(|e| {
155 ContractRuntimeError::Deserialize {
156 context: "tagged_deserialize(ContractState)",
157 source: e,
158 }
159 })
160}
161
162pub fn encode_contract_state(state: &ContractState<InMemoryDB>) -> Result<String> {
165 let mut buf = Vec::new();
166 tagged_serialize(state, &mut buf).map_err(|e| ContractRuntimeError::Serialize {
167 context: "tagged_serialize(ContractState)",
168 source: e,
169 })?;
170 Ok(hex::encode(buf))
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176 use moonproof_ledger::base_crypto::hash::{HashOutput, PERSISTENT_HASH_BYTES};
177 use moonproof_ledger::onchain_runtime::state::ContractState;
178
179 fn dummy_contract_state() -> ContractState<InMemoryDB> {
180 use moonproof_ledger::onchain_runtime::state::{
181 ContractMaintenanceAuthority, EntryPointBuf,
182 };
183 use moonproof_ledger::storage::storage::HashMap;
184 let op_key: EntryPointBuf = b"noop"[..].into();
185 ContractState::<InMemoryDB>::new(
186 moonproof_ledger::onchain_runtime::state::StateValue::Null,
187 HashMap::new().insert(op_key, moonproof_ledger::contract_operation(None)),
188 ContractMaintenanceAuthority::default(),
189 )
190 }
191
192 fn dummy_address(byte: u8) -> ContractAddress {
193 ContractAddress(HashOutput([byte; PERSISTENT_HASH_BYTES]))
194 }
195
196 #[test]
197 fn new_stores_address_and_state() {
198 let addr = dummy_address(0x01);
199 let state = ContractRuntimeState::new(addr, dummy_contract_state());
200 assert_eq!(state.address(), &addr);
201 assert_eq!(state.address_hex().len(), 64);
202 assert!(state.last_observed_tx_id().is_none());
203 assert!(state.last_observed_block_height().is_none());
204 assert_eq!(
205 state.address_hex(),
206 "0101010101010101010101010101010101010101010101010101010101010101",
207 );
208 }
209
210 #[test]
211 fn charged_state_is_current_state_data() {
212 let state = ContractRuntimeState::new(dummy_address(0x02), dummy_contract_state());
213 let charged = state.charged_state();
214 let from_full = &state.current_state().data;
215 assert!(std::ptr::eq(charged, from_full));
216 }
217
218 #[test]
219 fn contract_address_roundtrips_through_hex() {
220 let addr = dummy_address(0xab);
221 let hex = contract_address_to_hex(&addr);
222 let back = decode_contract_address(&hex).unwrap();
223 assert_eq!(addr, back);
224 }
225
226 #[test]
227 fn decode_contract_address_rejects_short_input() {
228 let err = decode_contract_address("deadbeef").unwrap_err();
229 matches!(err, ContractRuntimeError::Deserialize { .. });
230 }
231
232 #[test]
233 fn decode_contract_address_rejects_invalid_hex() {
234 let err = decode_contract_address("not-hex").unwrap_err();
235 matches!(err, ContractRuntimeError::HexDecode(_));
236 }
237
238 #[test]
239 fn contract_state_roundtrips_through_hex() {
240 let cs = dummy_contract_state();
241 let hex = encode_contract_state(&cs).unwrap();
242 let back = decode_contract_state(&hex).unwrap();
243 let reencoded = encode_contract_state(&back).unwrap();
244 assert_eq!(hex, reencoded);
245 }
246
247 #[test]
248 fn decode_contract_state_rejects_malformed_hex() {
249 let err = decode_contract_state("zzzz").unwrap_err();
250 matches!(err, ContractRuntimeError::HexDecode(_));
251 }
252
253 #[test]
254 fn decode_contract_state_rejects_truncated_payload() {
255 let err = decode_contract_state("aa").unwrap_err();
256 matches!(err, ContractRuntimeError::Deserialize { .. });
257 }
258
259 #[test]
260 fn apply_observed_advances_markers() {
261 let addr = dummy_address(0x03);
262 let mut state = ContractRuntimeState::new(addr, dummy_contract_state());
263 state.apply_observed(dummy_contract_state(), 7, 42);
264 assert_eq!(state.last_observed_tx_id(), Some(7));
265 assert_eq!(state.last_observed_block_height(), Some(42));
266
267 state.apply_observed(dummy_contract_state(), 3, 10);
269 assert_eq!(state.last_observed_tx_id(), Some(7));
270 assert_eq!(state.last_observed_block_height(), Some(42));
271 }
272}