clvm_tools_rs 0.4.0

tools for working with chialisp language; compiler, repl, python and wasm bindings
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::rc::Rc;

use clvmr::allocator::Allocator;

use crate::classic::clvm_tools::cmds::{cldb_hierarchy, CldbHierarchyArgs, YamlElement};
use crate::classic::clvm_tools::stages::stage_0::DefaultProgramRunner;
use crate::compiler::cldb::{hex_to_modern_sexp, CldbNoOverride, CldbRun, CldbRunEnv, FAVOR_HEX};
use crate::compiler::clvm::{start_step, RunStep};
use crate::compiler::compiler::{compile_file, DefaultCompilerOpts};
use crate::compiler::comptypes::CompilerOpts;
use crate::compiler::prims;
use crate::compiler::sexp::{parse_sexp, SExp};
use crate::compiler::srcloc::Srcloc;

fn json_to_yamlelement(json: &serde_json::Value) -> YamlElement {
    match json {
        serde_json::Value::Object(map) => {
            let mut yaml_map = BTreeMap::new();
            for (k, v) in map.iter() {
                let yamelled_wing = json_to_yamlelement(v);
                yaml_map.insert(k.to_string(), yamelled_wing);
            }
            YamlElement::Subtree(yaml_map)
        }
        serde_json::Value::String(s) => YamlElement::String(s.clone()),
        serde_json::Value::Array(v) => {
            YamlElement::Array(v.iter().map(|v| json_to_yamlelement(v)).collect())
        }
        _ => todo!(),
    }
}

fn yaml_to_yamlelement(yaml: &BTreeMap<String, YamlElement>) -> YamlElement {
    YamlElement::Subtree(yaml.clone())
}

trait StepOfCldbViewer {
    fn show(&mut self, _step: &RunStep, _output: Option<BTreeMap<String, String>>) -> bool {
        true
    }
}

fn run_clvm_in_cldb<V>(
    program_name: &str,
    program_lines: Rc<Vec<String>>,
    program: Rc<SExp>,
    symbols: HashMap<String, String>,
    args: Rc<SExp>,
    viewer: &mut V,
    flags: u32,
) -> Option<String>
where
    V: StepOfCldbViewer,
{
    let mut allocator = Allocator::new();
    let runner = Rc::new(DefaultProgramRunner::new());

    let mut prim_map = HashMap::new();
    for p in prims::prims().iter() {
        prim_map.insert(p.0.clone(), Rc::new(p.1.clone()));
    }
    let step = start_step(program, args);
    let cldbenv = CldbRunEnv::new(
        Some(program_name.to_string()),
        program_lines,
        Box::new(CldbNoOverride::new_symbols(symbols)),
    );
    let mut cldbrun = CldbRun::new(runner, Rc::new(prim_map), Box::new(cldbenv), step);
    cldbrun.set_flags(flags);

    let mut output: BTreeMap<String, String> = BTreeMap::new();

    loop {
        if cldbrun.is_ended() {
            return output.get("Final").cloned();
        }

        if let Some(result) = cldbrun.step(&mut allocator) {
            output = result;
            if !viewer.show(&cldbrun.current_step(), Some(output.clone())) {
                return None;
            }
        }
    }
}

struct DoesntWatchCldb {}

impl StepOfCldbViewer for DoesntWatchCldb {}

#[test]
fn test_run_clvm_in_cldb() {
    let program_name = "fact.clsp";
    let program_code = "(mod (X) (include *standard-cl-21*) (defun fact (X) (if (> X 1) (* X (fact (- X 1))) 1)) (fact X))";
    let mut allocator = Allocator::new();
    let runner = Rc::new(DefaultProgramRunner::new());
    let opts = Rc::new(DefaultCompilerOpts::new(program_name));
    let mut symbols = HashMap::new();
    let args = parse_sexp(Srcloc::start("*args*"), "(5)".bytes()).expect("should parse")[0].clone();

    let program = compile_file(
        &mut allocator,
        runner.clone(),
        opts,
        &program_code,
        &mut symbols,
    )
    .expect("should compile");

    let program_lines: Vec<String> = program_code.lines().map(|x| x.to_string()).collect();

    assert_eq!(
        run_clvm_in_cldb(
            program_name,
            Rc::new(program_lines),
            Rc::new(program),
            symbols,
            args,
            &mut DoesntWatchCldb {},
            0,
        ),
        Some("120".to_string())
    );
}

#[test]
fn test_cldb_hex_to_modern_sexp_smoke_0() {
    let mut allocator = Allocator::new();
    let symbol_table = HashMap::new();
    let input_program = "ff01ff03ff0580";
    let result_succeed = hex_to_modern_sexp(
        &mut allocator,
        &symbol_table,
        Srcloc::start("*test*"),
        input_program,
    )
    .unwrap();
    assert_eq!(result_succeed.to_string(), "(1 3 5)");
}

#[test]
fn test_cldb_hex_to_modern_sexp_fail_half_cons() {
    let mut allocator = Allocator::new();
    let symbol_table = HashMap::new();
    let input_program = "ff01ff03ff05";
    let result = hex_to_modern_sexp(
        &mut allocator,
        &symbol_table,
        Srcloc::start("*test*"),
        input_program,
    );
    assert!(result.is_err());
}

#[test]
fn test_cldb_hex_to_modern_sexp_fail_odd_hex() {
    let mut allocator = Allocator::new();
    let symbol_table = HashMap::new();
    let input_program = "ff01ff03ff058";
    let result = hex_to_modern_sexp(
        &mut allocator,
        &symbol_table,
        Srcloc::start("*test*"),
        input_program,
    );
    assert!(result.is_err());
}

fn compile_and_run_program_with_tree(
    input_file: &str,
    input_program_text: &str,
    args_text: &str,
    search_paths: &[String],
    flags: u32,
) -> Vec<BTreeMap<String, YamlElement>> {
    let mut allocator = Allocator::new();
    let runner = Rc::new(DefaultProgramRunner::new());
    let opts = Rc::new(DefaultCompilerOpts::new(&input_file))
        .set_optimize(false)
        .set_search_paths(search_paths);

    let mut use_symbol_table = HashMap::new();

    let program = compile_file(
        &mut allocator,
        runner.clone(),
        opts.clone(),
        &input_program_text,
        &mut use_symbol_table,
    )
    .expect("should compile");
    let args = parse_sexp(program.loc(), args_text.as_bytes().iter().copied())
        .expect("should parse args")[0]
        .clone();

    let mut prim_map = HashMap::new();
    for p in prims::prims().iter() {
        prim_map.insert(p.0.clone(), Rc::new(p.1.clone()));
    }
    let program_lines: Rc<Vec<String>> =
        Rc::new(input_program_text.lines().map(|x| x.to_string()).collect());

    cldb_hierarchy(CldbHierarchyArgs {
        runner,
        prim_map: Rc::new(prim_map),
        input_file_name: Some(input_file.to_owned()),
        lines: program_lines,
        symbol_table: Rc::new(use_symbol_table),
        prog: Rc::new(program),
        args,
        flags,
    })
}

fn run_program_as_tree_from_hex(
    file_name: &str,
    input_program: &str,
    input_args: &str,
    symbol_table: HashMap<String, String>,
) -> Vec<BTreeMap<String, YamlElement>> {
    let mut allocator = Allocator::new();
    let prog_srcloc = Srcloc::start("*program*");
    let args_srcloc = Srcloc::start("*args*");

    let program = hex_to_modern_sexp(
        &mut allocator,
        &symbol_table,
        prog_srcloc.clone(),
        &input_program,
    )
    .expect("should decode from hex");

    let args = hex_to_modern_sexp(
        &mut allocator,
        &symbol_table,
        args_srcloc.clone(),
        &input_args,
    )
    .expect("should decode from hex");

    let mut prim_map = HashMap::new();
    for p in prims::prims().iter() {
        prim_map.insert(p.0.clone(), Rc::new(p.1.clone()));
    }
    let program_lines = Rc::new(vec![]);
    let runner = Rc::new(DefaultProgramRunner::new());
    cldb_hierarchy(CldbHierarchyArgs {
        runner,
        prim_map: Rc::new(prim_map),
        input_file_name: Some(file_name.to_owned()),
        lines: program_lines,
        symbol_table: Rc::new(symbol_table),
        prog: program,
        args,
        flags: 0,
    })
}

fn compare_run_output(
    result: Vec<BTreeMap<String, YamlElement>>,
    run_entries: Vec<serde_json::Value>,
) {
    assert_eq!(result.len(), run_entries.len());
    for i in 0..result.len() {
        let result_entry = result[i].clone();
        let want_entry = &run_entries[i];
        let want_yaml = json_to_yamlelement(want_entry);
        let have_yaml = yaml_to_yamlelement(&result_entry);
        assert_eq!(want_yaml, have_yaml);
    }
}

#[test]
fn test_cldb_hierarchy_mode() {
    let json_text = fs::read_to_string("resources/tests/cldb_tree/test.json")
        .expect("test resources should exist: test.json");
    let run_entries: Vec<serde_json::Value> =
        serde_json::from_str(&json_text).expect("should contain json");
    let input_program = fs::read_to_string("resources/tests/cldb_tree/test_rec_1.cl")
        .expect("test resources should exist: test_rec_1.cl");
    let input_file = "./test_rec_1.cl";

    let result =
        compile_and_run_program_with_tree(&input_file, &input_program, "(3 2)", &vec![], 0);

    compare_run_output(result, run_entries);
}

#[test]
fn test_execute_program_and_capture_arguments() {
    let compiled_symbols_text =
        fs::read_to_string("resources/tests/cldb_tree/pool_member_innerpuz_extra.sym")
            .expect("should exist");
    let compiled_symbols: HashMap<String, String> =
        serde_json::from_str(&compiled_symbols_text).expect("should decode");
    let result = run_program_as_tree_from_hex(
        "./pool_member_innerpuz.hex",
        &fs::read_to_string("resources/tests/cldb_tree/pool_member_innerpuz.hex")
            .expect("should exist"),
        &fs::read_to_string("resources/tests/cldb_tree/pool_member_innerpuz_args.hex")
            .expect("should exist"),
        compiled_symbols,
    );

    let json_text = fs::read_to_string("resources/tests/cldb_tree/pool_member_innerpuz_run.json")
        .expect("test resources should exist");
    let run_entries: Vec<serde_json::Value> =
        serde_json::from_str(&json_text).expect("should contain json");

    compare_run_output(result, run_entries);
}

struct ExpectFailure {
    throw: bool,
    found_desired: bool,
    want_result: Option<String>,
}

impl ExpectFailure {
    fn new(throw: bool, want_result: Option<String>) -> Self {
        ExpectFailure {
            throw,
            want_result,
            found_desired: false,
        }
    }

    fn correct_result(&self) -> bool {
        self.found_desired
    }
}

impl StepOfCldbViewer for ExpectFailure {
    fn show(&mut self, _step: &RunStep, output: Option<BTreeMap<String, String>>) -> bool {
        if let Some(o) = output {
            if let Some(_) = o.get("Failure") {
                let did_throw = o.get("Operator") == Some(&"8".to_string());
                if let Some(desired_outcome) = &self.want_result {
                    self.found_desired =
                        did_throw == self.throw && o.get("Arguments") == Some(desired_outcome);
                } else {
                    self.found_desired = did_throw == self.throw;
                }
                return false;
            }
        }

        return true;
    }
}

#[test]
fn test_cldb_explicit_throw() {
    let program_name = "*test*";
    let loc = Srcloc::start(program_name);
    let program =
        parse_sexp(loc.clone(), b"(x (q . 2))".iter().copied()).expect("should parse")[0].clone();
    let args = Rc::new(SExp::Nil(loc));
    let program_lines = Rc::new(Vec::new());

    let mut watcher = ExpectFailure::new(true, Some("(2)".to_string()));

    assert_eq!(
        run_clvm_in_cldb(
            program_name,
            program_lines,
            program,
            HashMap::new(),
            args,
            &mut watcher,
            0
        ),
        None
    );

    assert!(watcher.correct_result());
}

#[test]
fn test_clvm_operator_with_weird_tail() {
    let filename = "test-weird-tail.clvm";
    let loc = Srcloc::start(filename);
    let program = "(+ (q . 3) (q . 5) . \"\")";
    let parsed = parse_sexp(loc.clone(), program.as_bytes().iter().copied()).expect("should parse");
    let args = Rc::new(SExp::Nil(loc));
    let program_lines = Rc::new(vec![program.to_string()]);

    assert_eq!(
        run_clvm_in_cldb(
            filename,
            program_lines,
            parsed[0].clone(),
            HashMap::new(),
            args,
            &mut DoesntWatchCldb {},
            0,
        ),
        Some("8".to_string())
    );
}

#[test]
fn test_cldb_with_favor_hex() {
    let filename = "favor_hex.clvm";
    let loc = Srcloc::start(filename);
    let program = "(concat (1 . 1) (1 . 1122334455))";
    let parsed = parse_sexp(loc.clone(), program.as_bytes().iter().copied()).expect("should parse");
    let args = Rc::new(SExp::Nil(loc));
    let program_lines = Rc::new(vec![program.to_string()]);

    assert_eq!(
        run_clvm_in_cldb(
            filename,
            program_lines,
            parsed[0].clone(),
            HashMap::new(),
            args,
            &mut DoesntWatchCldb {},
            FAVOR_HEX,
        ),
        Some("0x0142e576f7".to_string())
    );
}

#[test]
fn test_cldb_hierarchy_hex() {
    let json_text = fs::read_to_string("resources/tests/cldb_tree/hex.json")
        .expect("test resources should exist: test.json");
    let run_entries: Vec<serde_json::Value> =
        serde_json::from_str(&json_text).expect("should contain json");
    let input_program = "(mod () (concat 1 1122334455))".to_string();

    let input_file = "test_with_hex.clsp";

    let result =
        compile_and_run_program_with_tree(&input_file, &input_program, "()", &vec![], FAVOR_HEX);

    compare_run_output(result, run_entries);
}

#[test]
fn test_cldb_hierarchy_before_hex() {
    let json_text = fs::read_to_string("resources/tests/cldb_tree/pre_hex.json")
        .expect("test resources should exist: test.json");
    let run_entries: Vec<serde_json::Value> =
        serde_json::from_str(&json_text).expect("should contain json");
    let input_program = "(mod () (concat 1 1122334455))".to_string();

    let input_file = "test_with_hex.clsp";

    let result = compile_and_run_program_with_tree(&input_file, &input_program, "()", &vec![], 0);

    compare_run_output(result, run_entries);
}

#[test]
fn test_cldb_operators_outside_guard() {
    let filename = "coinid.clvm";
    let loc = Srcloc::start(filename);
    let inputs_outputs = [
        (
            "(coinid (sha256 (q . 3)) (sha256 (q . 3)) (q . 4))",
            "()",
            "0x9f7f12b86a583805a4442879b7b5b531469e45c7e753e5fd431058e90bf3fbec"
        ),
        (
            "(modpow (q . 2) (q . 8) (q . 10))",
            "()",
            "6"
        ),
        (
            "(% (q . 13) (q . 5))",
            "()",
            "3"
        ),
        (
            // resources/tests/bls/modern-bls-verify-signature.clsp
            "(2 (1 59 (1 . 0xb00ab9a8af54804b43067531d96c176710c05980fccf8eee1ae12a4fd543df929cce860273af931fe4fdbc407d495f73114ab7d17ef08922e56625daada0497582340ecde841a9e997f2f557653c21c070119662dd2efa47e2d6c5e2de00eefa) (1 . 0x86243290bbcbfd9ae75bdece7981965350208eb5e99b04d5cd24e955ada961f8c0a162dee740be7bdc6c3c0613ba2eb1) 5) (4 (1) 1))",
            "(0x0102030405)",
            "()"
        )
    ];

    for (program, arg_str, expected) in inputs_outputs {
        let parsed = parse_sexp(loc.clone(), program.bytes()).expect("should parse");
        let args_parsed = parse_sexp(loc.clone(), arg_str.bytes()).expect("should parse");
        let program_lines = Rc::new(vec![program.to_string()]);

        assert_eq!(
            run_clvm_in_cldb(
                filename,
                program_lines,
                parsed[0].clone(),
                HashMap::new(),
                args_parsed[0].clone(),
                &mut DoesntWatchCldb {},
                FAVOR_HEX,
            ),
            Some(expected.to_string())
        );
    }
}