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
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

pub mod base;
pub mod experimental;
pub mod sandbox;

/// Default directory where saved Move resources live
pub const DEFAULT_STORAGE_DIR: &str = "storage";

/// Default directory where Move modules live
pub const DEFAULT_SOURCE_DIR: &str = "src";

/// Default directory where Move packages live under build_dir
pub const DEFAULT_PACKAGE_DIR: &str = "package";

/// Default dependency inclusion mode
pub const DEFAULT_DEP_MODE: &str = "stdlib";

/// Default directory for build output
pub use move_lang::command_line::DEFAULT_OUTPUT_DIR as DEFAULT_BUILD_DIR;

/// Extension for resource and event files, which are in BCS format
const BCS_EXTENSION: &str = "bcs";

use crate::sandbox::utils::on_disk_state_view::OnDiskStateView;
use anyhow::Result;
use move_core_types::{
    account_address::AccountAddress, errmap::ErrorMapping, identifier::Identifier,
    language_storage::TypeTag, parser, transaction_argument::TransactionArgument,
};
use move_lang::shared::{self, AddressBytes};
use move_vm_runtime::native_functions::NativeFunction;
use sandbox::utils::mode::{Mode, ModeType};
use std::{
    fs,
    path::{Path, PathBuf},
};
use structopt::{clap::arg_enum, StructOpt};

type NativeFunctionRecord = (AccountAddress, Identifier, Identifier, NativeFunction);

#[derive(StructOpt)]
#[structopt(
    name = "move",
    about = "CLI frontend for Move compiler and VM",
    rename_all = "kebab-case"
)]
pub struct Move {
    /// Named address mapping
    #[structopt(
        name = "NAMED_ADDRESSES",
        short = "a",
        long = "addresses",
        global = true,
        parse(try_from_str = shared::parse_named_address)
    )]
    named_addresses: Vec<(String, AddressBytes)>,

    /// Directory storing Move resources, events, and module bytecodes produced by module publishing
    /// and script execution.
    #[structopt(long, default_value = DEFAULT_STORAGE_DIR, parse(from_os_str), global = true)]
    storage_dir: PathBuf,
    /// Directory storing build artifacts produced by compilation
    #[structopt(long, default_value = DEFAULT_BUILD_DIR, parse(from_os_str), global = true)]
    build_dir: PathBuf,

    /// Dependency inclusion mode
    #[structopt(
        long,
        default_value = DEFAULT_DEP_MODE,
        global = true,
    )]
    mode: ModeType,

    /// Print additional diagnostics
    #[structopt(short = "v", global = true)]
    verbose: bool,
}

/// MoveCLI is the CLI that will be executed by the `move-cli` command
/// The `cmd` argument is added here rather than in `Move` to make it
/// easier for other crates to extend `move-cli`
#[derive(StructOpt)]
pub struct MoveCLI {
    #[structopt(flatten)]
    move_args: Move,

    #[structopt(subcommand)]
    cmd: Command,
}

#[derive(StructOpt)]
pub enum Command {
    /// Compile and emit Move bytecode for the specified scripts and/or modules
    #[structopt(name = "compile")]
    Compile {
        /// The source files to check
        #[structopt(
            name = "PATH_TO_SOURCE_FILE",
            default_value = DEFAULT_SOURCE_DIR,
        )]
        source_files: Vec<String>,
        /// Do not emit source map information along with the compiled bytecode
        #[structopt(long = "no-source-maps")]
        no_source_maps: bool,
        /// Type check and verify the specified scripts and/or modules. Does not emit bytecode.
        #[structopt(long = "check")]
        check: bool,
    },
    /// Execute a sandbox command
    #[structopt(name = "sandbox")]
    Sandbox {
        #[structopt(subcommand)]
        cmd: SandboxCommand,
    },
    /// (Experimental) Run static analyses on Move source or bytecode
    #[structopt(name = "experimental")]
    Experimental {
        #[structopt(subcommand)]
        cmd: ExperimentalCommand,
    },
}

#[derive(StructOpt)]
pub enum SandboxCommand {
    /// Compile the specified modules and publish the resulting bytecodes in global storage
    #[structopt(name = "publish")]
    Publish {
        /// The source files containing modules to publish
        #[structopt(
            name = "PATH_TO_SOURCE_FILE",
            default_value = DEFAULT_SOURCE_DIR,
        )]
        source_files: Vec<String>,
        /// If set, fail during compilation when attempting to publish a module that already
        /// exists in global storage
        #[structopt(long = "no-republish")]
        no_republish: bool,
        /// By default, code that might cause breaking changes for bytecode
        /// linking or data layout compatibility checks will not be published.
        /// Set this flag to ignore breaking changes checks and publish anyway
        #[structopt(long = "ignore-breaking-changes")]
        ignore_breaking_changes: bool,
        /// fix publishing order
        #[structopt(short = "m", long = "override-ordering")]
        override_ordering: Option<Vec<String>>,
    },
    /// Compile/run a Move script that reads/writes resources stored on disk in `storage`.
    /// This command compiles the script first before running it.
    #[structopt(name = "run")]
    Run {
        /// Path to .mv file containing either script or module bytecodes. If the file is a module, the
        /// `script_name` parameter must be set.
        #[structopt(name = "script")]
        script_file: String,
        /// Name of the script function inside `script_file` to call. Should only be set if `script_file`
        /// points to a module.
        #[structopt(name = "name")]
        script_name: Option<String>,
        /// Possibly-empty list of signers for the current transaction (e.g., `account` in
        /// `main(&account: signer)`). Must match the number of signers expected by `script_file`.
        #[structopt(long = "signers")]
        signers: Vec<String>,
        /// Possibly-empty list of arguments passed to the transaction (e.g., `i` in
        /// `main(i: u64)`). Must match the arguments types expected by `script_file`.
        /// Supported argument types are
        /// bool literals (true, false),
        /// u64 literals (e.g., 10, 58),
        /// address literals (e.g., 0x12, 0x0000000000000000000000000000000f),
        /// hexadecimal strings (e.g., x"0012" will parse as the vector<u8> value [00, 12]), and
        /// ASCII strings (e.g., 'b"hi" will parse as the vector<u8> value [68, 69])
        #[structopt(long = "args", parse(try_from_str = parser::parse_transaction_argument))]
        args: Vec<TransactionArgument>,
        /// Possibly-empty list of type arguments passed to the transaction (e.g., `T` in
        /// `main<T>()`). Must match the type arguments kinds expected by `script_file`.
        #[structopt(long = "type-args", parse(try_from_str = parser::parse_type_tag))]
        type_args: Vec<TypeTag>,
        /// Maximum number of gas units to be consumed by execution.
        /// When the budget is exhaused, execution will abort.
        /// By default, no `gas-budget` is specified and gas metering is disabled.
        #[structopt(long = "gas-budget", short = "g")]
        gas_budget: Option<u64>,
        /// If set, the effects of executing `script_file` (i.e., published, updated, and
        /// deleted resources) will NOT be committed to disk.
        #[structopt(long = "dry-run", short = "n")]
        dry_run: bool,
    },
    /// Run expected value tests using the given batch file
    #[structopt(name = "test")]
    Test {
        /// a directory path in which all the tests will be executed
        #[structopt(name = "path")]
        path: String,
        /// Use an ephemeral directory to serve as the testing workspace.
        /// By default, the directory containing the `args.txt` will be the workspace
        #[structopt(long = "use-temp-dir")]
        use_temp_dir: bool,
        /// Show coverage information after tests are done.
        /// By default, coverage will not be tracked nor shown.
        #[structopt(long = "track-cov")]
        track_cov: bool,
        /// Create a new test directory scaffold with the specified <path>
        #[structopt(long = "create")]
        create: bool,
    },
    /// View Move resources, events files, and modules stored on disk
    #[structopt(name = "view")]
    View {
        /// Path to a resource, events file, or module stored on disk.
        #[structopt(name = "file")]
        file: String,
    },
    /// Delete all resources, events, and modules stored on disk under `storage`.
    /// Does *not* delete anything in `src`.
    Clean {},
    /// Run well-formedness checks on the `storage` and `build` directories.
    #[structopt(name = "doctor")]
    Doctor {},
    /// Typecheck and verify the scripts and/or modules under `src`.
    #[structopt(name = "link")]
    Link {
        /// The source files containing modules to publish
        #[structopt(
            name = "PATH_TO_SOURCE_FILE",
            default_value = DEFAULT_SOURCE_DIR,
        )]
        source_files: Vec<String>,

        /// If set, fail when attempting to typecheck a module that already exists in global storage
        #[structopt(long = "no-republish")]
        no_republish: bool,
    },
    /// Generate struct layout bindings for the modules stored on disk under `storage`
    // TODO: expand this to generate script bindings, docs, errmaps, etc.?
    #[structopt(name = "generate")]
    Generate {
        #[structopt(subcommand)]
        cmd: GenerateCommand,
    },
}

#[derive(StructOpt)]
pub enum GenerateCommand {
    /// Generate struct layout bindings for the modules stored on disk under `storage`
    #[structopt(name = "struct-layouts")]
    StructLayouts {
        /// Path to a module stored on disk.
        #[structopt(long)]
        module: String,
        /// If set, generate bindings for the specified struct and type arguments. If unset,
        /// generate bindings for all closed struct definitions
        #[structopt(flatten)]
        options: StructLayoutOptions,
    },
}
#[derive(StructOpt)]
pub struct StructLayoutOptions {
    /// Generate layout bindings for this struct
    #[structopt(long = "struct")]
    struct_: Option<String>,
    /// Generate layout bindings for `struct` bound to these type arguments
    #[structopt(long = "type-args", parse(try_from_str = parser::parse_type_tag), requires="struct")]
    type_args: Option<Vec<TypeTag>>,
}

#[derive(StructOpt)]
pub enum ExperimentalCommand {
    /// Perform a read/write set analysis and print the results for
    /// `module_file`::`script_name`
    #[structopt(name = "read-write-set")]
    ReadWriteSet {
        /// Path to .mv file containing module bytecode.
        #[structopt(name = "module")]
        module_file: String,
        /// A function inside `module_file`.
        #[structopt(name = "function")]
        fun_name: String,
        #[structopt(long = "signers")]
        signers: Vec<String>,
        #[structopt(long = "args", parse(try_from_str = parser::parse_transaction_argument))]
        args: Vec<TransactionArgument>,
        #[structopt(long = "type-args", parse(try_from_str = parser::parse_type_tag))]
        type_args: Vec<TypeTag>,
        #[structopt(long = "concretize", possible_values = &ConcretizeMode::variants(), case_insensitive = true, default_value = "dont")]
        concretize: ConcretizeMode,
    },
}

// Specify if/how the analysis should concretize and filter the static analysis summary
arg_enum! {
    // Specify if/how the analysis should concretize and filter the static analysis summary
    #[derive(Debug, Clone, Copy)]
    pub enum ConcretizeMode {
        // Show the full concretized access paths read or written (e.g. 0xA/0x1::M::S/f/g)
        Paths,
        // Show only the concrete resource keys that are read (e.g. 0xA/0x1::M::S)
        Reads,
        // Show only the concrete resource keys that are written (e.g. 0xA/0x1::M::S)
        Writes,
        // Do not concretize; show the results from the static analysis
        Dont,
    }
}

fn handle_experimental_commands(
    move_args: &Move,
    mode: &Mode,
    experimental_command: &ExperimentalCommand,
) -> Result<()> {
    match experimental_command {
        ExperimentalCommand::ReadWriteSet {
            module_file,
            fun_name,
            signers,
            args,
            type_args,
            concretize,
        } => {
            let state = mode.prepare_state(&move_args.build_dir, &move_args.storage_dir)?;
            experimental::commands::analyze_read_write_set(
                &state,
                module_file,
                fun_name,
                signers,
                args,
                type_args,
                *concretize,
                move_args.verbose,
            )
        }
    }
}

fn handle_sandbox_commands(
    natives: Vec<NativeFunctionRecord>,
    error_descriptions: &ErrorMapping,
    move_args: &Move,
    mode: &Mode,
    sandbox_command: &SandboxCommand,
) -> Result<()> {
    let additional_named_addresses =
        shared::verify_and_create_named_address_mapping(move_args.named_addresses.clone())?;
    match sandbox_command {
        SandboxCommand::Link {
            source_files,
            no_republish,
        } => {
            let state = mode.prepare_state(&move_args.build_dir, &move_args.storage_dir)?;
            base::commands::check(
                &[state.interface_files_dir()?],
                !*no_republish,
                source_files,
                state.get_named_addresses(additional_named_addresses)?,
                move_args.verbose,
            )
        }
        SandboxCommand::Publish {
            source_files,
            no_republish,
            ignore_breaking_changes,
            override_ordering,
        } => {
            let state = mode.prepare_state(&move_args.build_dir, &move_args.storage_dir)?;
            sandbox::commands::publish(
                natives,
                &state,
                source_files,
                !*no_republish,
                *ignore_breaking_changes,
                override_ordering.as_ref().map(|o| o.as_slice()),
                state.get_named_addresses(additional_named_addresses)?,
                move_args.verbose,
            )
        }
        SandboxCommand::Run {
            script_file,
            script_name,
            signers,
            args,
            type_args,
            gas_budget,
            dry_run,
        } => {
            let state = mode.prepare_state(&move_args.build_dir, &move_args.storage_dir)?;
            sandbox::commands::run(
                natives,
                error_descriptions,
                &state,
                script_file,
                script_name,
                signers,
                args,
                type_args.to_vec(),
                state.get_named_addresses(additional_named_addresses)?,
                *gas_budget,
                *dry_run,
                move_args.verbose,
            )
        }
        SandboxCommand::Test {
            path,
            use_temp_dir: _,
            track_cov: _,
            create: true,
        } => sandbox::commands::create_test_scaffold(path),
        SandboxCommand::Test {
            path,
            use_temp_dir,
            track_cov,
            create: false,
        } => sandbox::commands::run_all(
            path,
            &std::env::current_exe()?.to_string_lossy(),
            *use_temp_dir,
            *track_cov,
        ),
        SandboxCommand::View { file } => {
            let state = mode.prepare_state(&move_args.build_dir, &move_args.storage_dir)?;
            sandbox::commands::view(&state, file)
        }
        SandboxCommand::Clean {} => {
            // delete storage
            let storage_dir = Path::new(&move_args.storage_dir);
            if storage_dir.exists() {
                fs::remove_dir_all(&storage_dir)?;
            }

            // delete build
            let build_dir = Path::new(&move_args.build_dir);
            if build_dir.exists() {
                fs::remove_dir_all(&build_dir)?;
            }
            Ok(())
        }
        SandboxCommand::Doctor {} => {
            let state = mode.prepare_state(&move_args.build_dir, &move_args.storage_dir)?;
            sandbox::commands::doctor(&state)
        }
        SandboxCommand::Generate { cmd } => {
            let state = mode.prepare_state(&move_args.build_dir, &move_args.storage_dir)?;
            handle_generate_commands(cmd, &state)
        }
    }
}

fn handle_generate_commands(cmd: &GenerateCommand, state: &OnDiskStateView) -> Result<()> {
    match cmd {
        GenerateCommand::StructLayouts { module, options } => {
            sandbox::commands::generate::generate_struct_layouts(
                module,
                &options.struct_,
                &options.type_args,
                state,
            )
        }
    }
}

pub fn run_cli(
    natives: Vec<NativeFunctionRecord>,
    error_descriptions: &ErrorMapping,
    move_args: &Move,
    cmd: &Command,
) -> Result<()> {
    let mode = Mode::new(move_args.mode);
    let additional_named_addresses =
        shared::verify_and_create_named_address_mapping(move_args.named_addresses.clone())?;

    match cmd {
        Command::Compile {
            source_files,
            no_source_maps,
            check,
        } => {
            let state = mode.prepare_state(&move_args.build_dir, &move_args.storage_dir)?;
            if *check {
                base::commands::check(
                    &[state.interface_files_dir()?],
                    false,
                    source_files,
                    state.get_named_addresses(additional_named_addresses)?,
                    move_args.verbose,
                )
            } else {
                base::commands::compile(
                    &[state.interface_files_dir()?],
                    state.build_dir().to_str().unwrap(),
                    false,
                    source_files,
                    state.get_named_addresses(additional_named_addresses)?,
                    !*no_source_maps,
                    move_args.verbose,
                )
            }
        }
        Command::Sandbox { cmd } => {
            handle_sandbox_commands(natives, error_descriptions, move_args, &mode, cmd)
        }
        Command::Experimental { cmd } => handle_experimental_commands(move_args, &mode, cmd),
    }
}

pub fn move_cli(
    natives: Vec<NativeFunctionRecord>,
    error_descriptions: &ErrorMapping,
) -> Result<()> {
    let args = MoveCLI::from_args();
    run_cli(natives, error_descriptions, &args.move_args, &args.cmd)
}