svmscope 0.2.0

Transaction autopsy for Solana — decode any mainnet transaction, replay it locally in an embedded SVM, and mutate state to see what happens.
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
//! The JSON suite-file format — the on-disk spec for `svmscope test`, and the
//! wire types the web server and browser share.
//!
//! Mutations and scenarios arrive as JSON (from the browser, or a `.json` test
//! file); these `Deserialize` types convert them into the strongly-typed
//! [`crate::Scenario`] / [`crate::replay::Mutation`] the engine runs.

use serde::Deserialize;
use solana_address::Address;
use std::str::FromStr;

use crate::error::{Error, Result};

use crate::check::{Check, CheckKind, Scenario};
use crate::replay::{
    AccountAssert, CmpOp, Expect, FeatureToggle, Mutation, StateCheck, TimeTravel,
};

/// A runtime feature-gate toggle for a replay: `{"id":"<feature pubkey>","active":true}`.
/// `active` true = activate the gate (e.g. test a not-yet-live feature early),
/// false = deactivate an active one.
#[derive(Deserialize, Clone)]
pub struct FeatureInput {
    /// The feature gate's address, as base58.
    pub id: String,
    /// True to activate the gate, false to deactivate it.
    #[serde(default)]
    pub active: bool,
}

impl FeatureInput {
    /// Convert into the engine's [`FeatureToggle`], validating the id.
    pub fn into_toggle(self) -> Result<FeatureToggle> {
        let id = Address::from_str(self.id.trim()).map_err(|_| {
            Error::InvalidSpec(format!("bad feature id (not a pubkey): {}", self.id))
        })?;
        Ok(FeatureToggle {
            id,
            active: self.active,
        })
    }
}

/// Convert a list of feature inputs into engine toggles, failing on the first bad id.
pub fn feature_toggles(features: Vec<FeatureInput>) -> Result<Vec<FeatureToggle>> {
    features
        .into_iter()
        .map(FeatureInput::into_toggle)
        .collect()
}

/// One what-if mutation. `kind` selects the variant:
/// `{"kind":"lamports","address":..,"lamports":..}` or
/// `{"kind":"data","address":..,"offset":..,"bytes_hex":".."}` (patch at offset).
#[derive(Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum MutationInput {
    /// Set an account's lamport balance.
    Lamports {
        /// The account to mutate.
        address: String,
        /// The new lamport balance.
        lamports: u64,
    },
    /// Patch an account's data at an offset.
    Data {
        /// The account to mutate.
        address: String,
        /// Byte offset where the patch begins.
        offset: usize,
        /// The bytes to write, as hex (`0x`, spaces, underscores tolerated).
        bytes_hex: String,
    },
}

/// Decode a hex string, tolerating `0x`, spaces, and underscores.
fn hex_decode(s: &str) -> Result<Vec<u8>> {
    let s = s.trim().trim_start_matches("0x").replace([' ', '_'], "");
    // Guard ASCII before byte-slicing below: a multi-byte char would otherwise
    // pass the even-length check and panic on a non-char-boundary slice.
    if s.is_empty() || !s.len().is_multiple_of(2) || !s.is_ascii() {
        return Err(Error::InvalidSpec(
            "hex bytes must be a non-empty, even-length hex string".into(),
        ));
    }
    let bytes = s.as_bytes();
    (0..bytes.len())
        .step_by(2)
        .map(|i| {
            let pair = std::str::from_utf8(&bytes[i..i + 2]).expect("ascii checked above");
            u8::from_str_radix(pair, 16)
                .map_err(|_| Error::InvalidSpec(format!("invalid hex: {s}")))
        })
        .collect()
}

impl MutationInput {
    /// Convert into the engine's [`Mutation`], decoding hex bytes.
    pub fn into_mutation(self) -> Result<Mutation> {
        Ok(match self {
            MutationInput::Lamports { address, lamports } => Mutation::Lamports {
                address,
                value: lamports,
            },
            MutationInput::Data {
                address,
                offset,
                bytes_hex,
            } => Mutation::DataPatch {
                address,
                offset,
                bytes: hex_decode(&bytes_hex)?,
            },
        })
    }
}

/// A post-replay state assertion. `kind` is one of:
/// - `"u64"` — little-endian u64 at `offset`.
/// - `"lamports"` — the account's lamports.
/// - `"token_amount"` — SPL token amount (u64 @ 64); shorthand for `u64` at offset 64.
/// - `"lamports_delta"` — change in lamports (post − pre); `value` may be negative.
/// - `"token_delta"` — change in SPL token amount (post − pre); `value` may be negative.
/// - `"field"` — the named `field` of the account's decoded layout (SPL layouts,
///   or the owner program's IDL), e.g. `"field":"pool.reserveA"`. Matched by
///   exact name or final dot-segment; integer/bool fields only, signed included.
/// - `"field_delta"` — change in the named `field` (post − pre); may be negative.
///
/// `op` is one of `== != < <= > >=` (default `==`).
#[derive(Deserialize)]
pub struct AssertInput {
    /// The account the assertion reads.
    pub address: String,
    /// The assertion kind (see the type docs); defaults to `"u64"`.
    #[serde(default = "default_kind")]
    pub kind: String,
    /// Byte offset for the `u64` kind.
    #[serde(default)]
    pub offset: usize,
    /// Field name for the `field` / `field_delta` kinds.
    #[serde(default)]
    pub field: Option<String>,
    /// Comparison operator: `==` `!=` `<` `<=` `>` `>=` (default `==`).
    #[serde(default = "default_op")]
    pub op: String,
    /// Signed so deltas can be negative; non-delta kinds require it to be ≥ 0.
    pub value: i64,
}

fn default_kind() -> String {
    "u64".into()
}
fn default_op() -> String {
    "==".into()
}

impl AssertInput {
    fn into_assert(self) -> Result<AccountAssert> {
        let op = match self.op.as_str() {
            "==" | "eq" => CmpOp::Eq,
            "!=" | "ne" => CmpOp::Ne,
            "<" | "lt" => CmpOp::Lt,
            "<=" | "le" => CmpOp::Le,
            ">" | "gt" => CmpOp::Gt,
            ">=" | "ge" => CmpOp::Ge,
            other => return Err(Error::InvalidSpec(format!("unknown assert op: {other}"))),
        };
        // Non-delta kinds compare against an unsigned value.
        let unsigned = || -> Result<u64> {
            u64::try_from(self.value)
                .map_err(|_| Error::InvalidSpec(format!("{} value must be ≥ 0", self.kind)))
        };
        // Field kinds compare signed (an i64 timestamp is a legitimate target).
        let field = || -> Result<String> {
            match &self.field {
                Some(f) if !f.trim().is_empty() => Ok(f.trim().to_string()),
                _ => Err(Error::InvalidSpec(format!(
                    "assert kind \"{}\" needs a \"field\" name",
                    self.kind
                ))),
            }
        };
        let check = match self.kind.as_str() {
            "lamports" => StateCheck::Lamports {
                op,
                value: unsigned()? as i128,
            },
            "u64" => StateCheck::U64At {
                offset: self.offset,
                op,
                value: unsigned()? as i128,
            },
            "token_amount" => StateCheck::U64At {
                offset: 64,
                op,
                value: unsigned()? as i128,
            },
            "lamports_delta" => StateCheck::LamportsDelta {
                op,
                value: self.value as i128,
            },
            "token_delta" => StateCheck::TokenDelta {
                op,
                value: self.value as i128,
            },
            "field" => StateCheck::Field {
                name: field()?,
                op,
                value: self.value as i128,
            },
            "field_delta" => StateCheck::FieldDelta {
                name: field()?,
                op,
                value: self.value as i128,
            },
            other => return Err(Error::InvalidSpec(format!("unknown assert kind: {other}"))),
        };
        Ok(AccountAssert {
            address: self.address,
            check,
        })
    }
}

/// One test scenario: a name, the mutations to apply, the transaction-level
/// outcome to assert, and optional post-replay state assertions.
///
/// `expect` is `"success"`, `"revert"` (or `"fail"`), or `"any"`. When reverting,
/// an optional `contains` requires the error/logs to include that text.
#[derive(Deserialize)]
pub struct ScenarioInput {
    /// The scenario's name, shown in outcomes.
    pub name: String,
    /// The transaction-level expectation: `"success"`, `"revert"`/`"fail"`,
    /// or `"any"` (the default).
    #[serde(default = "default_expect")]
    pub expect: String,
    /// For a revert expectation: text the error/logs must include.
    #[serde(default)]
    pub contains: Option<String>,
    /// Mutations applied to the world before replaying.
    #[serde(default)]
    pub mutations: Vec<MutationInput>,
    /// Post-replay state assertions.
    #[serde(default)]
    pub asserts: Vec<AssertInput>,
}

fn default_expect() -> String {
    "any".into()
}

impl ScenarioInput {
    /// Convert the JSON shape into an engine [`Scenario`].
    pub fn into_scenario(self) -> Result<Scenario> {
        let expect = match self.expect.trim() {
            "success" | "pass" => Expect::Success,
            "revert" | "fail" => match self.contains {
                Some(s) if !s.is_empty() => Expect::RevertContains(s),
                _ => Expect::Revert,
            },
            "any" => Expect::Any,
            // A typo like "sucess" must not silently become Any and let the
            // scenario pass vacuously — that is exactly the silent-pass footgun
            // the crate promises to eliminate.
            other => {
                return Err(Error::InvalidSpec(format!(
                    "unknown expect \"{other}\" (use success, revert, or any)"
                )))
            }
        };
        let mutations = self
            .mutations
            .into_iter()
            .map(MutationInput::into_mutation)
            .collect::<Result<_>>()?;
        let mut checks = vec![Check(CheckKind::Outcome(expect))];
        for a in self.asserts {
            checks.push(Check(CheckKind::Account(vec![a.into_assert()?])));
        }
        Ok(Scenario {
            name: self.name,
            mutations,
            checks,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn hex_decode_tolerates_prefix_spaces_underscores() {
        assert_eq!(
            hex_decode("0xDEAD_beef").unwrap(),
            vec![0xde, 0xad, 0xbe, 0xef]
        );
        assert_eq!(hex_decode("00 ff").unwrap(), vec![0x00, 0xff]);
    }

    #[test]
    fn hex_decode_rejects_bad_input() {
        assert!(hex_decode("").is_err());
        assert!(hex_decode("abc").is_err()); // odd length
        assert!(hex_decode("zz").is_err());
    }

    #[test]
    fn hex_decode_rejects_multibyte_without_panicking() {
        // A multi-byte char has an even byte length but no ASCII char boundary at
        // the slice points — this must be a typed error, never a slice panic.
        assert!(hex_decode("aΩb").is_err());
        assert!(hex_decode("0x€€").is_err());
    }

    #[test]
    fn unknown_expect_string_is_an_error_not_a_vacuous_pass() {
        let s: ScenarioInput =
            serde_json::from_str(r#"{"name":"typo","expect":"sucess"}"#).unwrap();
        assert!(matches!(s.into_scenario(), Err(Error::InvalidSpec(_))));
    }

    #[test]
    fn data_mutation_becomes_patch() {
        let m: MutationInput = serde_json::from_str(
            r#"{"kind":"data","address":"X","offset":64,"bytes_hex":"0000000000000000"}"#,
        )
        .unwrap();
        match m.into_mutation().unwrap() {
            Mutation::DataPatch {
                address,
                offset,
                bytes,
            } => {
                assert_eq!(address, "X");
                assert_eq!(offset, 64);
                assert_eq!(bytes, vec![0u8; 8]);
            }
            _ => panic!("expected DataPatch"),
        }
    }

    #[test]
    fn assert_kinds_and_ops_resolve() {
        let a: AssertInput =
            serde_json::from_str(r#"{"address":"X","kind":"token_amount","op":">=","value":5}"#)
                .unwrap();
        // token_amount is shorthand for u64 at the SPL amount offset.
        match a.into_assert().unwrap().check {
            StateCheck::U64At {
                offset: 64,
                op: CmpOp::Ge,
                value: 5,
            } => {}
            _ => panic!("expected U64At @64 >= 5"),
        }

        let d: AssertInput =
            serde_json::from_str(r#"{"address":"X","kind":"token_delta","op":"<","value":-3}"#)
                .unwrap();
        match d.into_assert().unwrap().check {
            StateCheck::TokenDelta {
                op: CmpOp::Lt,
                value: -3,
            } => {}
            _ => panic!("expected TokenDelta < -3"),
        }
    }

    #[test]
    fn field_asserts_resolve_and_allow_negatives() {
        let a: AssertInput = serde_json::from_str(
            r#"{"address":"X","kind":"field","field":"pool.reserveA","op":">=","value":1000}"#,
        )
        .unwrap();
        match a.into_assert().unwrap().check {
            StateCheck::Field {
                name,
                op: CmpOp::Ge,
                value: 1000,
            } => assert_eq!(name, "pool.reserveA"),
            _ => panic!("expected Field >= 1000"),
        }

        // Deltas — and signed fields like i64 timestamps — may go negative.
        let d: AssertInput = serde_json::from_str(
            r#"{"address":"X","kind":"field_delta","field":"reserveA","value":-500}"#,
        )
        .unwrap();
        match d.into_assert().unwrap().check {
            StateCheck::FieldDelta {
                name,
                op: CmpOp::Eq,
                value: -500,
            } => assert_eq!(name, "reserveA"),
            _ => panic!("expected FieldDelta == -500"),
        }
    }

    #[test]
    fn field_assert_requires_a_field_name() {
        let a: AssertInput =
            serde_json::from_str(r#"{"address":"X","kind":"field","value":1}"#).unwrap();
        assert!(a.into_assert().unwrap_err().to_string().contains("field"));
    }

    #[test]
    fn non_delta_assert_rejects_negative_value() {
        let a: AssertInput =
            serde_json::from_str(r#"{"address":"X","kind":"lamports","value":-1}"#).unwrap();
        assert!(a.into_assert().is_err());
    }

    #[test]
    fn unknown_op_and_kind_error() {
        let a: AssertInput =
            serde_json::from_str(r#"{"address":"X","op":"~=","value":1}"#).unwrap();
        assert!(a.into_assert().is_err());
        let k: AssertInput =
            serde_json::from_str(r#"{"address":"X","kind":"balancez","value":1}"#).unwrap();
        assert!(k.into_assert().is_err());
    }

    #[test]
    fn scenario_expect_revert_with_contains() {
        let s: ScenarioInput = serde_json::from_str(
            r#"{"name":"drain","expect":"revert","contains":"Slippage","mutations":[],"asserts":[]}"#,
        )
        .unwrap();
        let scenario = s.into_scenario().unwrap();
        match &scenario.checks[0].0 {
            CheckKind::Outcome(Expect::RevertContains(t)) => assert_eq!(t, "Slippage"),
            other => panic!("expected RevertContains, got {other:?}"),
        }
    }
}

/// POST body for `/simulate_suite`, and the on-disk format for `svmscope test`.
///
/// Provide `fixture` (a path to a frozen fixture file) for a deterministic,
/// offline run — the CI-safe path — or `signature` to fetch live state via RPC.
#[derive(Deserialize)]
pub struct SuiteRequest {
    /// Transaction signature for the live-RPC path.
    #[serde(default)]
    pub signature: Option<String>,
    /// Path to a frozen fixture file for the offline path.
    #[serde(default)]
    pub fixture: Option<String>,
    /// Cluster name (mainnet/devnet/testnet/localnet) for the live-signature path.
    #[serde(default)]
    pub cluster: Option<String>,
    /// Explicit RPC URL override for the live-signature path.
    #[serde(default)]
    pub rpc: Option<String>,
    /// Optional clock warp applied to every scenario in the suite.
    #[serde(default)]
    pub time_travel: TimeTravel,
    /// Optional runtime feature-gate toggles applied to every scenario.
    #[serde(default)]
    pub features: Vec<FeatureInput>,
    /// The scenarios to run.
    pub scenarios: Vec<ScenarioInput>,
}