blockchain-runtime 0.1.0

Blockchain-agnostic runtime abstraction for dynamic analysis, testing, and simulation
Documentation
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
# Architecture

## System Overview

Blockchain Runtime implements a **blockchain-agnostic abstraction layer** that provides a unified interface for executing, testing, and analyzing smart contracts across different blockchain platforms.

```
┌─────────────────────────────────────────────────────────────┐
│                  Application Layer                           │
│         (Security Tools, Testing Frameworks)                 │
└───────────────────┬──────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│              BlockchainRuntime Trait                         │
│           (Blockchain-Agnostic Interface)                    │
├─────────────────────────────────────────────────────────────┤
│  - create_environment()                                      │
│  - execute()                                                 │
│  - deploy_contract()                                         │
│  - call_function()                                           │
│  - monitor()                                                 │
│  - capabilities()                                            │
└───────────────────┬──────────────────────────────────────────┘
       ┌────────────┴────────────┬────────────┬────────────┐
       │                         │            │            │
       ▼                         ▼            ▼            ▼
┌──────────────┐        ┌──────────────┐  ┌───────┐  ┌───────┐
│   Ethereum   │        │   Solana     │  │ Near  │  │Custom │
│   Runtime    │        │   Runtime    │  │Runtime│  │Runtime│
└──────┬───────┘        └──────┬───────┘  └───┬───┘  └───┬───┘
       │                       │              │          │
       ▼                       ▼              ▼          ▼
┌──────────────┐        ┌──────────────┐  ┌──────────────┐
│ Docker       │        │ LocalProcess │  │CloudInstance │
│ Container    │        │ (ganache)    │  │ (Alchemy)    │
└──────────────┘        └──────────────┘  └──────────────┘
```

## Core Components

### 1. BlockchainRuntime Trait

Main interface for all blockchain operations.

**Responsibilities:**
- Environment lifecycle management
- Code execution
- Contract deployment
- Function calls
- Event monitoring
- Metrics collection

**Definition:**
```rust
#[async_trait]
pub trait BlockchainRuntime: Send + Sync {
    fn blockchain_id(&self) -> &str;
    async fn create_environment(&self, config: RuntimeConfig) -> Result<RuntimeEnvironment>;
    async fn execute(&self, env: &RuntimeEnvironment, code: &Path, inputs: &ExecutionInputs) -> Result<ExecutionResult>;
    async fn deploy_contract(&self, env: &RuntimeEnvironment, bytecode: &[u8], args: &[u8]) -> Result<String>;
    async fn call_function(&self, env: &RuntimeEnvironment, address: &str, function: &str, args: &[u8]) -> Result<Vec<u8>>;
    fn metrics_definition(&self) -> Vec<RuntimeMetricDefinition>;
    async fn monitor(&self, env: &RuntimeEnvironment, execution_id: &str) -> Result<Vec<RuntimeEvent>>;
    async fn destroy(&self, env: RuntimeEnvironment) -> Result<()>;
    async fn is_available(&self) -> bool;
    fn capabilities(&self) -> RuntimeCapabilities;
}
```

**Location:** `src/lib.rs`

### 2. Runtime Environment

Represents an isolated blockchain execution environment.

**Structure:**
```rust
pub struct RuntimeEnvironment {
    pub environment_id: String,          // Unique identifier
    pub blockchain_id: String,           // ethereum, solana, etc.
    pub runtime_type: RuntimeType,       // Docker, LocalProcess, etc.
    pub endpoint_url: String,            // RPC endpoint
    pub state: EnvironmentState,         // Creating, Ready, Running, etc.
    pub metadata: HashMap<String, serde_json::Value>,
}
```

**States:**
```
Creating → Ready → Running → Stopped
            Error
```

### 3. Runtime Configuration

Configuration for creating runtime environments.

**Structure:**
```rust
pub struct RuntimeConfig {
    pub timeout_seconds: u64,            // Max execution time
    pub memory_limit_mb: u64,            // Memory limit
    pub network_mode: NetworkMode,       // Local, Testnet, MainnetFork
    pub enable_monitoring: bool,         // Enable event monitoring
    pub blockchain_config: HashMap<String, serde_json::Value>,
}
```

**Default Values:**
- timeout_seconds: 300 (5 minutes)
- memory_limit_mb: 1024 (1GB)
- network_mode: Local
- enable_monitoring: true

### 4. Execution Flow

#### Contract Deployment

```
User Request: deploy_contract(bytecode, args)
  │
  ├─ 1. Validate environment is Ready
  ├─ 2. Prepare deployment transaction
  ├─ 3. Submit to blockchain
  ├─ 4. Wait for confirmation
  ├─ 5. Extract contract address
  └─ 6. Return address

Result: Contract address string
```

#### Function Call

```
User Request: call_function(address, function, args)
  │
  ├─ 1. Validate contract exists
  ├─ 2. Encode function call
  ├─ 3. Create transaction
  ├─ 4. Execute transaction
  ├─ 5. Decode return value
  └─ 6. Return result

Result: Raw bytes (caller decodes)
```

#### Code Execution

```
User Request: execute(code_path, inputs)
  │
  ├─ 1. Read code file
  ├─ 2. Compile if needed
  ├─ 3. Deploy to environment
  ├─ 4. Call target function
  ├─ 5. Collect metrics
  ├─ 6. Capture events
  ├─ 7. Track state changes
  └─ 8. Return ExecutionResult

Result: ExecutionResult with metrics, events, state changes
```

## Runtime Types

### Docker Runtime

```
┌─────────────────────────────────────────┐
│  Docker Container                       │
├─────────────────────────────────────────┤
│  ┌───────────────────────────────────┐  │
│  │  Blockchain Node (geth, anvil)   │  │
│  │  - Local network                  │  │
│  │  - Isolated filesystem            │  │
│  │  - Port forwarding                │  │
│  └───────────────────────────────────┘  │
└────────────┬────────────────────────────┘
             │ RPC calls
      Application Code
```

**Advantages:**
- Complete isolation
- Reproducible environments
- Easy cleanup
- No host pollution

**Use Cases:**
- CI/CD pipelines
- Parallel test execution
- Security analysis

### LocalProcess Runtime

```
┌─────────────────────────────────────────┐
│  Host Process                           │
├─────────────────────────────────────────┤
│  ganache-cli                            │
│  hardhat node                           │
│  anvil                                  │
└────────────┬────────────────────────────┘
             │ RPC calls (localhost)
      Application Code
```

**Advantages:**
- Fast startup
- Lower resource usage
- Easy debugging
- Direct access

**Use Cases:**
- Local development
- Quick testing
- Debugging

### CloudInstance Runtime

```
┌─────────────────────────────────────────┐
│  Cloud Provider (Alchemy, Infura)      │
├─────────────────────────────────────────┤
│  Test Network or Mainnet Fork          │
└────────────┬────────────────────────────┘
             │ HTTPS RPC calls
      Application Code
```

**Advantages:**
- No local setup
- Realistic environment
- Persistent state
- Shared access

**Use Cases:**
- Integration testing
- Mainnet forking
- Team development

### InMemory Runtime

```
┌─────────────────────────────────────────┐
│  Application Process                    │
├─────────────────────────────────────────┤
│  ┌───────────────────────────────────┐  │
│  │  Simulated Blockchain             │  │
│  │  - In-memory state                │  │
│  │  - Mock contracts                 │  │
│  │  - Fast execution                 │  │
│  └───────────────────────────────────┘  │
└─────────────────────────────────────────┘
```

**Advantages:**
- Extremely fast
- No external dependencies
- Deterministic
- Lightweight

**Use Cases:**
- Unit testing
- Fuzzing
- Property testing

## Network Modes

### Local Mode

```
Local Network (Chain ID: 1337)
  │
  ├─ Pre-funded accounts
  ├─ No gas costs (free)
  ├─ Fast block times
  ├─ No real funds
  └─ Full control
```

**Use Case:** Development and testing

### Testnet Mode

```
Public Testnet (Goerli, Sepolia, Devnet)
  │
  ├─ Real network behavior
  ├─ Free test tokens (faucets)
  ├─ Public visibility
  ├─ Network delays
  └─ Shared state
```

**Use Case:** Integration testing, staging

### MainnetFork Mode

```
Mainnet Fork (at specific block)
  │
  ├─ Real mainnet state
  ├─ Real contracts available
  ├─ Local execution
  ├─ No real funds spent
  └─ Realistic testing
```

**Use Case:** Testing against real contracts

## Execution Result Structure

```rust
pub struct ExecutionResult {
    pub execution_id: String,                    // Unique execution ID
    pub success: bool,                           // Success/failure
    pub return_value: Option<serde_json::Value>, // Decoded return value
    pub error: Option<String>,                   // Error message
    pub metrics: HashMap<String, serde_json::Value>, // Metrics collected
    pub state_changes: Vec<StateChange>,         // State modifications
    pub events: Vec<RuntimeEvent>,               // Emitted events
    pub execution_time_ms: u64,                  // Time taken
}
```

### State Changes

```rust
pub struct StateChange {
    pub key: String,                             // Storage key
    pub old_value: Option<serde_json::Value>,   // Previous value
    pub new_value: serde_json::Value,           // New value
    pub change_type: StateChangeType,           // Created/Updated/Deleted
}
```

### Runtime Events

```rust
pub struct RuntimeEvent {
    pub event_id: String,                        // Unique event ID
    pub event_type: String,                      // Event name
    pub timestamp: u64,                          // When emitted
    pub data: HashMap<String, serde_json::Value>, // Event data
}
```

## Metrics System

### Metric Definitions

```rust
pub struct RuntimeMetricDefinition {
    pub name: String,                            // Metric name
    pub description: String,                     // What it measures
    pub unit: String,                            // Unit (gas, ms, bytes)
    pub metric_type: MetricType,                 // Type classification
}
```

### Common Metrics

| Blockchain | Metric | Unit | Description |
|------------|--------|------|-------------|
| Ethereum | gas_used | units | Gas consumed |
| Ethereum | gas_price | gwei | Gas price |
| Ethereum | storage_delta | bytes | Storage change |
| Solana | compute_units | units | Compute consumed |
| Solana | heap_memory | bytes | Heap usage |
| All | execution_time | ms | Time taken |
| All | state_changes | count | State modifications |

## Capabilities System

```rust
pub struct RuntimeCapabilities {
    pub supports_contract_deployment: bool,      // Can deploy contracts
    pub supports_function_calls: bool,           // Can call functions
    pub supports_state_inspection: bool,         // Can inspect state
    pub supports_event_monitoring: bool,         // Can monitor events
    pub supports_gas_estimation: bool,           // Can estimate gas
    pub supports_time_travel: bool,              // Can manipulate time
    pub max_execution_time_seconds: u64,         // Max execution time
}
```

**Usage:**
```rust
let caps = runtime.capabilities();

if caps.supports_time_travel {
    // Can use evm_increaseTime, evm_mine, etc.
}
```

## Error Handling

All operations return `anyhow::Result<T>` for flexibility.

### Common Errors

- `EnvironmentNotReady` - Environment not in Ready state
- `DeploymentFailed` - Contract deployment failed
- `ExecutionTimeout` - Execution exceeded timeout
- `ContractNotFound` - Contract address not found
- `InsufficientFunds` - Not enough balance
- `InvalidInput` - Malformed input data

### Error Propagation

```rust
async fn execute_safely(runtime: &dyn BlockchainRuntime) -> Result<()> {
    let env = runtime.create_environment(config).await
        .context("Failed to create environment")?;
    
    let address = runtime.deploy_contract(&env, bytecode, &args).await
        .context("Failed to deploy contract")?;
    
    Ok(())
}
```

## Thread Safety

All types implement `Send + Sync`:
- `BlockchainRuntime`: Thread-safe trait object
- `RuntimeEnvironment`: Can be shared across threads
- `ExecutionResult`: Immutable, thread-safe

## Performance Characteristics

### Environment Creation

| Runtime Type | Time | Resource Usage |
|-------------|------|----------------|
| Docker | 2-5s | High (container overhead) |
| LocalProcess | 1-2s | Medium |
| CloudInstance | <1s | Low (remote) |
| InMemory | <100ms | Very low |

### Execution

| Operation | Typical Time |
|-----------|-------------|
| Deploy contract | 500ms - 2s |
| Call function | 100ms - 500ms |
| State inspection | 50ms - 200ms |
| Event monitoring | 100ms - 1s |

## Security Considerations

### Isolation

- Docker provides strong isolation
- LocalProcess shares host resources
- CloudInstance requires API keys
- InMemory has no external access

### Resource Limits

- Timeout prevents infinite execution
- Memory limits prevent OOM
- Cleanup on destroy prevents leaks

## Future Enhancements

### v0.2
- Snapshot/restore functionality
- Time travel capabilities
- Enhanced monitoring

### v0.3
- Multi-environment orchestration
- Performance profiling
- Advanced debugging

### v0.4
- Smart contract fuzzing
- Formal verification integration
- Cross-chain testing