forked from Timi16/soroban-debugger
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommands.rs
More file actions
3477 lines (3115 loc) · 121 KB
/
Copy pathcommands.rs
File metadata and controls
3477 lines (3115 loc) · 121 KB
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::analyzer::symbolic::SymbolicConfig;
use crate::analyzer::upgrade::{CompatibilityReport, ExecutionDiff, UpgradeAnalyzer};
use crate::analyzer::{
security::SecurityAnalyzer,
symbolic::{build_replay_bundle, SymbolicAnalyzer},
};
use crate::cli::args::{
AnalyzeArgs, CompareArgs, HistoryPruneArgs, InspectArgs, InteractiveArgs, OptimizeArgs,
OutputFormat, ProfileArgs, RemoteAction, RemoteArgs, ReplArgs, ReplayArgs, RunArgs,
ScenarioArgs, ServerArgs, SymbolicArgs, SymbolicProfile, TuiArgs, UpgradeCheckArgs, Verbosity,
};
use crate::cli::output::write_json_pretty_file;
use crate::debugger::engine::DebuggerEngine;
use crate::debugger::instruction_pointer::StepMode;
use crate::debugger::timeline::{
TimelineDeltas, TimelineExport, TimelinePausePoint, TimelineRunInfo, TimelineStorageDelta,
TimelineWarning, TIMELINE_EXPORT_SCHEMA_VERSION,
};
use crate::history::{HistoryManager, RunHistory};
use crate::inspector::events::{ContractEvent, EventInspector};
use crate::logging;
use crate::output::OutputWriter;
use crate::repeat::RepeatRunner;
use crate::repl::ReplConfig;
use crate::runtime::executor::ContractExecutor;
use crate::simulator::SnapshotLoader;
use crate::ui::formatter::Formatter;
use crate::ui::{run_dashboard, DebuggerUI};
use crate::{DebuggerError, Result};
use miette::WrapErr;
use std::fs;
use std::path::PathBuf;
fn print_info(message: impl AsRef<str>) {
if !Formatter::is_quiet() {
println!("{}", Formatter::info(message));
}
}
fn print_success(message: impl AsRef<str>) {
if !Formatter::is_quiet() {
println!("{}", Formatter::success(message));
}
}
fn print_warning(message: impl AsRef<str>) {
if !Formatter::is_quiet() {
println!("{}", Formatter::warning(message));
}
}
/// Print the final contract return value — always shown regardless of verbosity.
fn print_result(message: impl AsRef<str>) {
if !Formatter::is_quiet() {
println!("{}", Formatter::success(message));
}
}
/// Print verbose-only detail — only shown when --verbose is active.
fn print_verbose(message: impl AsRef<str>) {
if Formatter::is_verbose() {
println!("{}", Formatter::info(message));
}
}
fn budget_trend_stats_or_err(records: &[RunHistory]) -> Result<crate::history::BudgetTrendStats> {
crate::history::budget_trend_stats(records).ok_or_else(|| {
DebuggerError::ExecutionError(
"Failed to compute budget trend statistics for the selected dataset".to_string(),
)
.into()
})
}
#[derive(serde::Serialize)]
struct DynamicAnalysisMetadata {
function: String,
args: Option<String>,
result: Option<String>,
trace_entries: usize,
}
#[derive(serde::Serialize)]
struct AnalyzeCommandOutput {
findings: Vec<crate::analyzer::security::SecurityFinding>,
/// Rule metadata keyed by rule id (#1272). Lets downstream tools resolve a
/// finding's `rule_id` to stable id/name/severity/category/remediation
/// fields for filtering. A BTreeMap keeps the JSON ordering deterministic.
rules: std::collections::BTreeMap<String, crate::analyzer::security::RuleMetadata>,
dynamic_analysis: Option<DynamicAnalysisMetadata>,
warnings: Vec<String>,
suppressed_count: usize,
}
#[derive(serde::Serialize)]
struct SourceMapDiagnosticsCommandOutput {
contract: String,
source_map: crate::debugger::source_map::SourceMapInspectionReport,
}
fn render_symbolic_report(report: &crate::analyzer::symbolic::SymbolicReport) -> String {
let mut lines = vec![
format!("Function: {}", report.function),
format!("Paths explored: {}", report.paths_explored),
format!("Panics found: {}", report.panics_found),
format!(
"Replay token: {}",
report
.metadata
.seed
.map(|seed| seed.to_string())
.unwrap_or_else(|| "none".to_string())
),
format!(
"Budget: path_cap={}, input_combination_cap={}, timeout={}s",
report.metadata.config.max_paths,
report.metadata.config.max_input_combinations,
report.metadata.config.timeout_secs
),
format!(
"Input combinations: generated={}, attempted={}, distinct_paths={}",
report.metadata.generated_input_combinations,
report.metadata.attempted_input_combinations,
report.metadata.distinct_paths_recorded
),
format!(
"Coverage: {:.1}% (explored branch/function coverage)",
report.metadata.coverage_fraction * 100.0
),
];
if !report.metadata.uncovered_regions.is_empty() {
lines.push(format!(
"Uncovered regions: {}",
report.metadata.uncovered_regions.join(", ")
));
}
if report.metadata.truncation_reasons.is_empty() {
lines.push("Truncation: none".to_string());
} else {
lines.push(format!(
"Truncation: {}",
report.metadata.truncation_reasons.join("; ")
));
}
if report.paths.is_empty() {
lines.push("No distinct execution paths were discovered.".to_string());
return lines.join("\n");
}
lines.push(String::new());
lines.push("Distinct paths:".to_string());
for (idx, path) in report.paths.iter().enumerate() {
let outcome = match (&path.return_value, &path.panic) {
(Some(value), _) => format!("return {}", value),
(_, Some(panic)) => format!("panic {}", panic),
_ => "unknown".to_string(),
};
lines.push(format!(
" {}. inputs={} -> {}",
idx + 1,
path.inputs,
outcome
));
}
lines.join("\n")
}
fn symbolic_profile_config(profile: SymbolicProfile) -> SymbolicConfig {
match profile {
SymbolicProfile::Fast => SymbolicConfig::fast(),
SymbolicProfile::Balanced => SymbolicConfig::balanced(),
SymbolicProfile::Deep => SymbolicConfig::deep(),
}
}
fn symbolic_config_from_args(args: &SymbolicArgs) -> Result<SymbolicConfig> {
let mut config = symbolic_profile_config(args.profile);
if let Some(path_cap) = args.path_cap {
config.max_paths = path_cap;
}
if let Some(input_cap) = args.input_combination_cap {
config.max_input_combinations = input_cap;
}
if let Some(max_breadth) = args.max_breadth {
config.max_breadth = max_breadth;
}
if let Some(timeout) = args.timeout {
config.timeout_secs = timeout;
}
config.seed = args.seed.or(args.replay);
if let Some(storage_seed_path) = &args.storage_seed {
config.storage_seed = Some(fs::read_to_string(storage_seed_path).map_err(|e| {
DebuggerError::FileError(format!(
"Failed to read storage seed file {:?}: {}",
storage_seed_path, e
))
})?);
}
Ok(config)
}
/// Convert MinSeverity enum to analyzer Severity enum.
fn convert_min_severity(value: crate::cli::args::MinSeverity) -> crate::analyzer::security::Severity {
match value {
crate::cli::args::MinSeverity::Low => crate::analyzer::security::Severity::Low,
crate::cli::args::MinSeverity::Medium => crate::analyzer::security::Severity::Medium,
crate::cli::args::MinSeverity::High => crate::analyzer::security::Severity::High,
}
}
/// Find the closest matching rule IDs using Levenshtein distance.
fn suggest_rule_ids(unknown: &str, known_rules: &[String], max_distance: usize) -> Vec<String> {
use std::cmp;
// Calculate Levenshtein distance between two strings
let levenshtein = |a: &str, b: &str| {
let a_len = a.len();
let b_len = b.len();
let mut matrix = vec![vec![0; b_len + 1]; a_len + 1];
for i in 0..=a_len {
matrix[i][0] = i;
}
for j in 0..=b_len {
matrix[0][j] = j;
}
for (i, a_char) in a.chars().enumerate() {
for (j, b_char) in b.chars().enumerate() {
let cost = if a_char == b_char { 0 } else { 1 };
matrix[i + 1][j + 1] = cmp::min(
cmp::min(
matrix[i][j + 1] + 1, // deletion
matrix[i + 1][j] + 1, // insertion
),
matrix[i][j] + cost, // substitution
);
}
}
matrix[a_len][b_len]
};
let mut suggestions: Vec<_> = known_rules
.iter()
.map(|rule| {
let distance = levenshtein(&unknown.to_lowercase(), &rule.to_lowercase());
(distance, rule.clone())
})
.filter(|(distance, _)| *distance <= max_distance)
.collect();
suggestions.sort_by_key(|(distance, _)| *distance);
suggestions.into_iter().map(|(_, rule)| rule).collect()
}
/// Validate rule IDs in enable_rules and disable_rules lists.
fn validate_rule_ids(
enable_rules: &[String],
disable_rules: &[String],
registered_rules: &[String],
) -> Result<()> {
let mut invalid_rules = Vec::new();
// Check enable_rules
for rule in enable_rules {
if !registered_rules.contains(rule) {
invalid_rules.push(("enable", rule.clone()));
}
}
// Check disable_rules
for rule in disable_rules {
if !registered_rules.contains(rule) {
invalid_rules.push(("disable", rule.clone()));
}
}
if !invalid_rules.is_empty() {
let mut message = String::from("Invalid rule IDs provided:\n");
for (filter_type, rule) in &invalid_rules {
message.push_str(&format!(" --{}-rule '{}': not found\n", filter_type, rule));
let suggestions = suggest_rule_ids(rule, registered_rules, 2);
if !suggestions.is_empty() {
message.push_str(&format!(" Did you mean: {}?\n", suggestions.join(", ")));
}
}
message.push_str(&format!("\nAvailable rules: {}\n", registered_rules.join(", ")));
return Err(DebuggerError::InvalidArguments(message).into());
}
Ok(())
}
fn render_security_report(output: &AnalyzeCommandOutput) -> String {
let mut lines = Vec::new();
if let Some(dynamic) = &output.dynamic_analysis {
lines.push(format!("Dynamic analysis function: {}", dynamic.function));
if let Some(args) = &dynamic.args {
lines.push(format!("Dynamic analysis args: {}", args));
}
if let Some(result) = &dynamic.result {
lines.push(format!("Dynamic execution result: {}", result));
}
lines.push(format!(
"Dynamic trace entries captured: {}",
dynamic.trace_entries
));
lines.push(String::new());
}
if !output.warnings.is_empty() {
lines.push("Warnings:".to_string());
for warning in &output.warnings {
lines.push(format!(" - {}", warning));
}
lines.push(String::new());
}
if output.findings.is_empty() {
lines.push("No security findings detected.".to_string());
if output.suppressed_count > 0 {
lines.push(format!(
"({} findings were suppressed)",
output.suppressed_count
));
}
return lines.join("\n");
}
lines.push(format!(
"Findings: {} ({} suppressed)",
output.findings.len(),
output.suppressed_count
));
for (idx, finding) in output.findings.iter().enumerate() {
lines.push(format!(
" {}. [{:?}] {} at {}",
idx + 1,
finding.severity,
finding.rule_id,
finding.location
));
lines.push(format!(" {}", finding.description));
if let Some(confidence) = finding.confidence {
lines.push(format!(" Confidence: {:.0}%", confidence * 100.0));
}
if let Some(rationale) = &finding.rationale {
lines.push(format!(" Rationale: {}", rationale));
}
lines.push(format!(" Remediation: {}", finding.remediation));
}
lines.join("\n")
}
/// Run instruction-level stepping mode.
fn run_instruction_stepping(
engine: &mut DebuggerEngine,
function: &str,
args: Option<&str>,
) -> Result<()> {
logging::log_display(
"\n=== Instruction Stepping Mode ===",
logging::LogLevel::Info,
);
logging::log_display(
"Type 'help' for available commands\n",
logging::LogLevel::Info,
);
display_instruction_context(engine, 3);
loop {
print!("(step) > ");
std::io::Write::flush(&mut std::io::stdout())
.map_err(|e| DebuggerError::IoError(format!("Failed to flush stdout: {}", e)))?;
let mut input = String::new();
let bytes_read = std::io::stdin()
.read_line(&mut input)
.map_err(|e| DebuggerError::IoError(format!("Failed to read line: {}", e)))?;
if bytes_read == 0 {
logging::log_display("Input stream closed.", logging::LogLevel::Info);
break;
}
let input = input.trim().to_lowercase();
let cmd = input.as_str();
let result = match cmd {
"n" | "next" | "s" | "step" | "into" | "" => engine.step_into(),
"o" | "over" => engine.step_over(),
"u" | "out" => engine.step_out(),
"b" | "block" => engine.step_block(),
"p" | "prev" | "back" => engine.step_back(),
"c" | "continue" => {
logging::log_display("Continuing execution...", logging::LogLevel::Info);
engine.continue_execution()?;
let res = engine.execute_without_breakpoints(function, args)?;
logging::log_display(
format!("Execution completed. Result: {:?}", res),
logging::LogLevel::Info,
);
break;
}
"i" | "info" => {
display_instruction_info(engine);
continue;
}
"ctx" | "context" => {
display_instruction_context(engine, 5);
continue;
}
"h" | "help" => {
logging::log_display(Formatter::format_stepping_help(), logging::LogLevel::Info);
continue;
}
"q" | "quit" | "exit" => {
logging::log_display(
"Exiting instruction stepping mode...",
logging::LogLevel::Info,
);
break;
}
_ => {
logging::log_display(
format!("Unknown command: {cmd}. Type 'help' for available commands."),
logging::LogLevel::Info,
);
continue;
}
};
match result {
Ok(true) => display_instruction_context(engine, 3),
Ok(false) => {
let msg = if matches!(cmd, "p" | "prev" | "back") {
"Cannot step back: no previous instruction"
} else {
"Cannot step: execution finished or error occurred"
};
logging::log_display(msg, logging::LogLevel::Info);
}
Err(e) => {
logging::log_display(format!("Error stepping: {}", e), logging::LogLevel::Info)
}
}
}
Ok(())
}
fn display_instruction_context(engine: &DebuggerEngine, context_size: usize) {
let context = engine.get_instruction_context(context_size);
let formatted = Formatter::format_instruction_context(&context, context_size);
logging::log_display(formatted, logging::LogLevel::Info);
}
fn display_instruction_info(engine: &DebuggerEngine) {
if let Ok(state) = engine.state().lock() {
let ip = state.instruction_pointer();
let step_mode = if ip.is_stepping() {
Some(ip.step_mode())
} else {
None
};
logging::log_display(
Formatter::format_instruction_pointer_state(
ip.current_index(),
ip.call_stack_depth(),
step_mode,
ip.is_stepping(),
),
logging::LogLevel::Info,
);
logging::log_display(
Formatter::format_instruction_stats(
state.instructions().len(),
ip.current_index(),
state.step_count(),
),
logging::LogLevel::Info,
);
if let Some(inst) = state.current_instruction() {
logging::log_display(
format!(
"Current Instruction: {} (Offset: 0x{:08x}, Local index: {}, Control flow: {})",
inst.name(),
inst.offset,
inst.local_index,
inst.is_control_flow()
),
logging::LogLevel::Info,
);
}
} else {
logging::log_display("Cannot access debug state", logging::LogLevel::Info);
}
}
/// Parse a step mode from its textual form. The single source of truth for
/// step-mode parsing across the run and interactive flows (#1263). Unsupported
/// modes return a clear error instead of silently defaulting, so a typo can't
/// quietly change stepping behaviour.
fn parse_step_mode(mode: &str) -> Result<StepMode> {
match mode.trim().to_lowercase().as_str() {
"into" | "i" => Ok(StepMode::StepInto),
"over" | "o" => Ok(StepMode::StepOver),
"out" | "u" => Ok(StepMode::StepOut),
"block" | "b" => Ok(StepMode::StepBlock),
other => Err(crate::DebuggerError::InvalidArguments(format!(
"unsupported step mode '{other}'. Supported modes: into, over, out, block."
))
.into()),
}
}
/// Recommended/required minimum length for a remote debug auth token (#1262).
const MIN_REMOTE_TOKEN_LEN: usize = 16;
/// Outcome of the remote-debug token-strength policy (#1262).
#[derive(Debug, PartialEq, Eq)]
enum TokenPolicy {
Ok,
Warn(String),
Reject(String),
}
/// Evaluate the token-strength policy for the remote debug server (#1262).
/// A token shorter than [`MIN_REMOTE_TOKEN_LEN`] warns by default, or is
/// rejected when `require_strong` is set. No token is allowed (auth disabled).
fn evaluate_token_policy(token: Option<&str>, require_strong: bool) -> TokenPolicy {
match token {
None => TokenPolicy::Ok,
Some(t) if t.trim().len() >= MIN_REMOTE_TOKEN_LEN => TokenPolicy::Ok,
Some(_) => {
let msg = format!(
"Remote debug token is shorter than {MIN_REMOTE_TOKEN_LEN} characters. \
Prefer at least {MIN_REMOTE_TOKEN_LEN} characters, ideally a random 32-byte token."
);
if require_strong {
TokenPolicy::Reject(format!(
"{msg} Refusing to start because --require-strong-token is set."
))
} else {
TokenPolicy::Warn(msg)
}
}
}
}
#[cfg(test)]
mod step_and_token_tests {
use super::*;
use crate::debugger::instruction_pointer::StepMode;
#[test]
fn parse_step_mode_accepts_supported_modes_and_aliases() {
assert_eq!(parse_step_mode("into").unwrap(), StepMode::StepInto);
assert_eq!(parse_step_mode("OVER").unwrap(), StepMode::StepOver);
assert_eq!(parse_step_mode(" out ").unwrap(), StepMode::StepOut);
assert_eq!(parse_step_mode("b").unwrap(), StepMode::StepBlock);
}
#[test]
fn parse_step_mode_rejects_unsupported_mode() {
let err = parse_step_mode("sideways").unwrap_err().to_string();
assert!(err.contains("unsupported step mode"), "got: {err}");
assert!(err.contains("sideways"), "got: {err}");
}
#[test]
fn token_policy_ok_when_absent_or_long_enough() {
assert_eq!(evaluate_token_policy(None, true), TokenPolicy::Ok);
assert_eq!(
evaluate_token_policy(Some("0123456789abcdef"), true),
TokenPolicy::Ok
);
}
#[test]
fn token_policy_warns_by_default_for_short_token() {
assert!(matches!(
evaluate_token_policy(Some("short"), false),
TokenPolicy::Warn(_)
));
}
#[test]
fn token_policy_rejects_short_token_when_enforcement_enabled() {
assert!(matches!(
evaluate_token_policy(Some("short"), true),
TokenPolicy::Reject(_)
));
}
}
/// Display mock call log
fn display_mock_call_log(calls: &[crate::runtime::executor::MockCallEntry]) {
if calls.is_empty() {
return;
}
print_info("\n--- Mock Contract Calls ---");
for (i, entry) in calls.iter().enumerate() {
let status = if entry.mocked { "MOCKED" } else { "REAL" };
print_info(format!(
"{}. {} {} (args: {}) -> {}",
i + 1,
status,
entry.function,
entry.args_count,
if entry.returned.is_some() {
"returned"
} else {
"pending"
}
));
}
}
/// Execute batch mode with parallel execution
fn run_batch(args: &RunArgs, batch_file: &std::path::Path) -> Result<()> {
let contract = args
.contract
.as_ref()
.expect("contract is required for batch mode");
let function = args
.function
.as_ref()
.expect("function is required for batch mode");
print_info(format!("Loading contract: {:?}", contract));
logging::log_loading_contract(&contract.to_string_lossy());
let wasm_bytes = fs::read(contract).map_err(|e| {
DebuggerError::WasmLoadError(format!("Failed to read WASM file at {:?}: {}", contract, e))
})?;
print_success(format!(
"Contract loaded successfully ({} bytes)",
wasm_bytes.len()
));
logging::log_contract_loaded(wasm_bytes.len());
print_info(format!("Loading batch file: {:?}", batch_file));
let batch_items = crate::batch::BatchExecutor::load_batch_file(batch_file)?;
print_success(format!("Loaded {} test cases", batch_items.len()));
if let Some(snapshot_path) = &args.network_snapshot {
print_info(format!("\nLoading network snapshot: {:?}", snapshot_path));
logging::log_loading_snapshot(&snapshot_path.to_string_lossy());
let loader = SnapshotLoader::from_file(snapshot_path)?;
let loaded_snapshot = loader.apply_to_environment()?;
logging::log_display(loaded_snapshot.format_summary(), logging::LogLevel::Info);
}
print_info(format!(
"\nExecuting {} test cases in parallel for function: {}",
batch_items.len(),
function
));
logging::log_execution_start(function, None);
let executor = crate::batch::BatchExecutor::new(wasm_bytes, function.clone())?;
let results = executor.execute_batch(batch_items)?;
let summary = crate::batch::BatchExecutor::summarize(&results);
crate::batch::BatchExecutor::display_results(&results, &summary);
if args.is_json_output() {
let output = serde_json::json!({
"results": results,
"summary": summary,
});
logging::log_display(
crate::output::to_json_string(&output).map_err(|e| {
DebuggerError::FileError(format!("Failed to serialize output: {}", e))
})?,
logging::LogLevel::Info,
);
}
logging::log_execution_complete(&format!("{}/{} passed", summary.passed, summary.total));
if summary.failed > 0 || summary.errors > 0 {
return Err(DebuggerError::ExecutionError(format!(
"Batch execution completed with failures: {} failed, {} errors",
summary.failed, summary.errors
))
.into());
}
Ok(())
}
/// Execute the run command.
#[tracing::instrument(skip_all, fields(contract = ?args.contract, function = args.function))]
pub fn run(args: RunArgs, verbosity: Verbosity) -> Result<()> {
// Start debug server if requested
if args.server {
return server(ServerArgs {
host: args.host,
port: args.port,
token: args.token,
require_strong_token: false,
tls_cert: args.tls_cert,
tls_key: args.tls_key,
repeat: args.repeat,
storage_filter: args.storage_filter,
show_events: args.show_events,
event_filter: args.event_filter,
mock: args.mock,
});
}
// Remote execution/ping path.
if let Some(remote_addr) = &args.remote {
return remote(
RemoteArgs {
remote: remote_addr.clone(),
token: args.token.clone(),
contract: args.contract.clone(),
function: args.function.clone(),
tls_cert: args.tls_cert.clone(),
tls_key: args.tls_key.clone(),
tls_ca: None,
session_label: None,
args: args.args.clone(),
connect_timeout_ms: 10000,
timeout_ms: 30000,
inspect_timeout_ms: None,
storage_timeout_ms: None,
retry_attempts: 3,
retry_base_delay_ms: 200,
retry_max_delay_ms: 2000,
format: if args.is_json_output() { crate::cli::args::OutputFormat::Json } else { crate::cli::args::OutputFormat::Pretty },
action: None,
},
verbosity,
);
}
// Initialize output writer
let mut output_writer = OutputWriter::new(args.save_output.as_deref(), args.append)?;
// Handle batch execution mode
if let Some(batch_file) = &args.batch_args {
return run_batch(&args, batch_file);
}
if args.dry_run {
return run_dry_run(&args);
}
let contract = args
.contract
.as_ref()
.expect("contract is required for run");
let function = args
.function
.as_ref()
.expect("function is required for run");
print_info(format!("Loading contract: {:?}", contract));
output_writer.write(&format!("Loading contract: {:?}", contract))?;
logging::log_loading_contract(&contract.to_string_lossy());
let wasm_file = crate::utils::wasm::load_wasm(contract)
.with_context(|| format!("Failed to read WASM file: {:?}", contract))?;
let wasm_bytes = wasm_file.bytes;
let wasm_hash = wasm_file.sha256_hash;
if let Some(expected) = &args.expected_hash {
if expected.to_lowercase() != wasm_hash {
return Err((crate::DebuggerError::ChecksumMismatch(
expected.clone(),
wasm_hash.clone(),
))
.into());
}
}
print_success(format!(
"Contract loaded successfully ({} bytes)",
wasm_bytes.len()
));
output_writer.write(&format!(
"Contract loaded successfully ({} bytes)",
wasm_bytes.len()
))?;
if args.verbose || verbosity == Verbosity::Verbose {
print_verbose(format!("SHA-256: {}", wasm_hash));
output_writer.write(&format!("SHA-256: {}", wasm_hash))?;
if args.expected_hash.is_some() {
print_verbose("Checksum verified ✓");
output_writer.write("Checksum verified ✓")?;
}
}
logging::log_contract_loaded(wasm_bytes.len());
if let Some(snapshot_path) = &args.network_snapshot {
print_info(format!("\nLoading network snapshot: {:?}", snapshot_path));
output_writer.write(&format!("Loading network snapshot: {:?}", snapshot_path))?;
logging::log_loading_snapshot(&snapshot_path.to_string_lossy());
let loader = SnapshotLoader::from_file(snapshot_path)?;
let loaded_snapshot = loader.apply_to_environment()?;
output_writer.write(&loaded_snapshot.format_summary())?;
logging::log_display(loaded_snapshot.format_summary(), logging::LogLevel::Info);
}
let parsed_args = if let Some(args_json) = &args.args {
Some(parse_args(args_json)?)
} else {
None
};
let mut initial_storage = if let Some(storage_json) = &args.storage {
Some(parse_storage(storage_json)?)
} else {
None
};
// Import storage if specified
if let Some(import_path) = &args.import_storage {
print_info(format!("Importing storage from: {:?}", import_path));
let imported = crate::inspector::storage::StorageState::import_from_file(import_path)?;
print_success(format!("Imported {} storage entries", imported.len()));
initial_storage = Some(serde_json::to_string(&imported).map_err(|e| {
DebuggerError::StorageError(format!("Failed to serialize imported storage: {}", e))
})?);
}
if let Some(n) = args.repeat {
logging::log_repeat_execution(function, n as usize);
let runner = RepeatRunner::new(wasm_bytes, args.breakpoint, initial_storage);
let stats = runner.run(function, parsed_args.as_deref(), n)?;
stats.display();
return Ok(());
}
print_info("\nStarting debugger...");
output_writer.write("Starting debugger...")?;
print_info(format!("Function: {}", function));
output_writer.write(&format!("Function: {}", function))?;
if let Some(ref parsed) = parsed_args {
print_info(format!("Arguments: {}", parsed));
output_writer.write(&format!("Arguments: {}", parsed))?;
}
logging::log_execution_start(function, parsed_args.as_deref());
let mut executor = ContractExecutor::new(wasm_bytes.clone())?;
executor.set_timeout(args.timeout);
if let Some(storage) = initial_storage {
executor.set_initial_storage(storage)?;
}
if !args.mock.is_empty() {
executor.set_mock_specs(&args.mock)?;
}
let mut engine = DebuggerEngine::new(executor, args.breakpoint.clone());
if args.instruction_debug {
print_info("Enabling instruction-level debugging...");
engine.enable_instruction_debug(&wasm_bytes)?;
if args.step_instructions {
let step_mode = parse_step_mode(&args.step_mode)?;
print_info(format!(
"Starting instruction stepping in '{}' mode",
args.step_mode
));
engine.start_instruction_stepping(step_mode)?;
run_instruction_stepping(&mut engine, function, parsed_args.as_deref())?;
return Ok(());
}
}
print_info("\n--- Execution Start ---\n");
output_writer.write("\n--- Execution Start ---\n")?;
let storage_before = engine.executor().get_storage_snapshot()?;
let result = engine.execute(function, parsed_args.as_deref())?;
let storage_after = engine.executor().get_storage_snapshot()?;
print_success("\n--- Execution Complete ---\n");
output_writer.write("\n--- Execution Complete ---\n")?;
print_result(format!("Result: {:?}", result));
output_writer.write(&format!("Result: {:?}", result))?;
logging::log_execution_complete(&result);
// Generate test if requested
if let Some(test_path) = &args.generate_test {
if let Some(record) = engine.executor().last_execution() {
print_info(format!("\nGenerating unit test: {:?}", test_path));
let test_code = crate::codegen::TestGenerator::generate(record, contract)?;
crate::codegen::TestGenerator::write_to_file(test_path, &test_code, args.overwrite)?;
print_success(format!(
"Unit test generated successfully at {:?}",
test_path
));
} else {
print_warning("No execution record found to generate test.");
}
}
let storage_diff = crate::inspector::storage::StorageInspector::compute_diff(
&storage_before,
&storage_after,
&args.alert_on_change,
);
if !storage_diff.is_empty() || !args.alert_on_change.is_empty() {
print_info("\n--- Storage Changes ---");
crate::inspector::storage::StorageInspector::display_diff(&storage_diff);
}
let mock_calls = engine.executor().get_mock_call_log();
if !args.mock.is_empty() {
display_mock_call_log(&mock_calls);
}
// Save budget info to history
let host = engine.executor().host();
let budget = crate::inspector::budget::BudgetInspector::get_cpu_usage(host);
if let Ok(manager) = HistoryManager::new() {
let record = RunHistory {
date: chrono::Utc::now().to_rfc3339(),
contract_hash: contract.to_string_lossy().to_string(),
function: function.clone(),
cpu_used: budget.cpu_instructions,
memory_used: budget.memory_bytes,
};
let _ = manager.append_record(record);
}
let _json_memory_summary = engine.executor().last_memory_summary().cloned();
// Export storage if specified
if let Some(export_path) = &args.export_storage {
print_info(format!("Exporting storage to: {:?}", export_path));
let storage_snapshot = engine.executor().get_storage_snapshot()?;
crate::inspector::storage::StorageState::export_to_file(&storage_snapshot, export_path)?;
print_success(format!(
"Exported {} storage entries",
storage_snapshot.len()
));
}
let mut json_events = None;
if args.show_events || !args.event_filter.is_empty() || args.filter_topic.is_some() {
print_info("\n--- Events ---");
// Attempt to read raw events from executor
let raw_events = engine.executor().get_events()?;
// Convert runtime event objects into our inspector::events::ContractEvent via serde translation.
// This is a generic, safe conversion as long as runtime events are serializable with sensible fields.
let converted_events: Vec<ContractEvent> =
match serde_json::to_value(&raw_events).and_then(serde_json::from_value) {
Ok(evts) => evts,
Err(e) => {
// If conversion fails, fall back to attempting to stringify each raw event for display.
print_warning(format!(
"Failed to convert runtime events for structured display: {}",
e
));
// Fallback: attempt a best-effort stringification
let fallback: Vec<ContractEvent> = raw_events
.into_iter()
.map(|r| ContractEvent {
contract_id: None,
topics: vec![],
data: format!("{:?}", r),
})
.collect();
fallback
}
};
// Determine filter: prefer repeatable --event-filter, fallback to legacy --filter-topic
let filter_opt = if !args.event_filter.is_empty() {
Some(args.event_filter.join(","))
} else {
args.filter_topic.clone()
};
let filtered_events = if let Some(ref filt) = filter_opt {
EventInspector::filter_events(&converted_events, filt)
} else {
converted_events.clone()
};