blockchain_runtime/
types.rs

1//! Core types for blockchain runtime
2
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5
6use crate::constants::*;
7
8/// Network mode for runtime
9#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
10pub enum NetworkMode {
11    Local,
12    Testnet,
13    MainnetFork,
14}
15
16/// Runtime type for environment
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
18pub enum RuntimeType {
19    Docker,
20    LocalProcess,
21    CloudInstance,
22    InMemory,
23}
24
25/// Environment state
26#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
27pub enum EnvironmentState {
28    Creating,
29    Ready,
30    Running,
31    Stopped,
32    Error,
33}
34
35/// Metric type for runtime monitoring
36#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
37pub enum MetricType {
38    Gas,
39    ComputeUnits,
40    StorageBytes,
41    Time,
42    Custom(String),
43}
44
45/// State change type
46#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
47pub enum StateChangeType {
48    Created,
49    Updated,
50    Deleted,
51}
52
53/// Security violation type
54#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
55pub enum SecurityViolationType {
56    ReentrancyAttack,
57    IntegerOverflow,
58    AccessControlViolation,
59    ResourceLimitExceeded,
60    SandboxViolation,
61    CallDepthExceeded,
62    ExternalCallLimitExceeded,
63    GasLimitExceeded,
64    MemoryLimitExceeded,
65}
66
67/// Security severity level
68#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
69pub enum SecuritySeverity {
70    Low,
71    Medium,
72    High,
73    Critical,
74}
75
76/// Runtime metric definition
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct RuntimeMetricDefinition {
79    pub name: String,
80    pub description: String,
81    pub unit: String,
82    pub metric_type: MetricType,
83}
84
85/// Runtime capabilities
86#[derive(Debug, Clone, Serialize, Deserialize)]
87pub struct RuntimeCapabilities {
88    pub supports_contract_deployment: bool,
89    pub supports_function_calls: bool,
90    pub supports_state_inspection: bool,
91    pub supports_event_monitoring: bool,
92    pub supports_gas_estimation: bool,
93    pub supports_time_travel: bool,
94    pub max_execution_time_seconds: u64,
95}
96
97impl Default for RuntimeCapabilities {
98    fn default() -> Self {
99        Self {
100            supports_contract_deployment: true,
101            supports_function_calls: true,
102            supports_state_inspection: true,
103            supports_event_monitoring: true,
104            supports_gas_estimation: false,
105            supports_time_travel: false,
106            max_execution_time_seconds: DEFAULT_MAX_EXECUTION_TIME_SECONDS,
107        }
108    }
109}
110
111/// Runtime environment instance
112#[derive(Debug, Clone, Serialize, Deserialize)]
113pub struct RuntimeEnvironment {
114    pub environment_id: String,
115    pub blockchain_id: String,
116    pub runtime_type: RuntimeType,
117    pub endpoint_url: String,
118    pub state: EnvironmentState,
119    pub metadata: HashMap<String, serde_json::Value>,
120}
121
122/// Execution inputs
123#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct ExecutionInputs {
125    pub target_function: String,
126    pub parameters: HashMap<String, serde_json::Value>,
127    pub context: ExecutionContext,
128}
129
130/// Execution context
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct ExecutionContext {
133    pub sender: Option<String>,
134    pub block_number: Option<u64>,
135    pub timestamp: Option<u64>,
136    pub extra: HashMap<String, serde_json::Value>,
137}
138
139/// State change during execution
140#[derive(Debug, Clone, Serialize, Deserialize)]
141pub struct StateChange {
142    pub key: String,
143    pub old_value: Option<serde_json::Value>,
144    pub new_value: serde_json::Value,
145    pub change_type: StateChangeType,
146}
147
148/// Runtime event
149#[derive(Debug, Clone, Serialize, Deserialize)]
150pub struct RuntimeEvent {
151    pub event_id: String,
152    pub event_type: String,
153    pub timestamp: u64,
154    pub data: HashMap<String, serde_json::Value>,
155}
156
157/// Access control check result
158#[derive(Debug, Clone, Serialize, Deserialize)]
159pub struct AccessControlCheck {
160    pub function_name: String,
161    pub caller: String,
162    pub required_role: Option<String>,
163    pub has_permission: bool,
164    pub check_timestamp: u64,
165}
166
167/// Security violation detected during execution
168#[derive(Debug, Clone, Serialize, Deserialize)]
169pub struct SecurityViolation {
170    pub violation_type: SecurityViolationType,
171    pub description: String,
172    pub severity: SecuritySeverity,
173    pub timestamp: u64,
174    pub context: HashMap<String, serde_json::Value>,
175}
176
177/// Execution context with security tracking
178#[derive(Debug, Clone, Serialize, Deserialize)]
179pub struct SecureExecutionContext {
180    pub call_depth: u32,
181    pub external_call_count: u32,
182    pub gas_used: u64,
183    pub memory_used: u64,
184    pub call_stack: Vec<String>,
185    pub access_control_checks: Vec<AccessControlCheck>,
186    pub security_violations: Vec<SecurityViolation>,
187}
188
189impl Default for SecureExecutionContext {
190    fn default() -> Self {
191        Self {
192            call_depth: 0,
193            external_call_count: 0,
194            gas_used: 0,
195            memory_used: 0,
196            call_stack: Vec::new(),
197            access_control_checks: Vec::new(),
198            security_violations: Vec::new(),
199        }
200    }
201}
202
203/// Execution result with security information
204#[derive(Debug, Clone, Serialize, Deserialize)]
205pub struct ExecutionResult {
206    pub execution_id: String,
207    pub success: bool,
208    pub return_value: Option<serde_json::Value>,
209    pub error: Option<String>,
210    pub metrics: HashMap<String, serde_json::Value>,
211    pub state_changes: Vec<StateChange>,
212    pub events: Vec<RuntimeEvent>,
213    pub execution_time_ms: u64,
214    /// Security context
215    pub security_context: SecureExecutionContext,
216    /// Security violations detected
217    pub security_violations: Vec<SecurityViolation>,
218}
219
220impl ExecutionResult {
221    /// Create a new execution result
222    pub fn new(execution_id: String, success: bool) -> Self {
223        Self {
224            execution_id,
225            success,
226            return_value: None,
227            error: None,
228            metrics: HashMap::new(),
229            state_changes: Vec::new(),
230            events: Vec::new(),
231            execution_time_ms: 0,
232            security_context: SecureExecutionContext::default(),
233            security_violations: Vec::new(),
234        }
235    }
236
237    /// Add a security violation to the result
238    pub fn add_security_violation(&mut self, violation: SecurityViolation) {
239        self.security_violations.push(violation);
240    }
241
242    /// Check if execution has security violations
243    pub fn has_security_violations(&self) -> bool {
244        !self.security_violations.is_empty()
245    }
246
247    /// Get the highest severity level of violations
248    pub fn get_highest_severity(&self) -> Option<SecuritySeverity> {
249        self.security_violations
250            .iter()
251            .map(|v| &v.severity)
252            .max_by(|a, b| {
253                let severity_order = [SecuritySeverity::Low, SecuritySeverity::Medium, SecuritySeverity::High, SecuritySeverity::Critical];
254                let a_order = severity_order.iter().position(|x| x == *a).unwrap_or(0);
255                let b_order = severity_order.iter().position(|x| x == *b).unwrap_or(0);
256                a_order.cmp(&b_order)
257            })
258            .cloned()
259    }
260}