essential-check 0.11.0

Core logic related to validating Essential state transitions.
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
use essential_check::{solution, vm::asm};
use essential_hash::content_addr;
use essential_types::{
    contract::Contract,
    predicate::{Edge, Node, Predicate, Program, Reads},
    solution::{Mutation, Solution, SolutionSet},
    ContentAddress, PredicateAddress, Word,
};
use std::{collections::HashMap, sync::Arc};
use util::{empty_solution_set, State};

pub mod util;

fn test_predicate_addr() -> PredicateAddress {
    PredicateAddress {
        contract: ContentAddress([0; 32]),
        predicate: ContentAddress([0; 32]),
    }
}

fn test_solution() -> Solution {
    Solution {
        predicate_to_solve: test_predicate_addr(),
        predicate_data: vec![],
        state_mutations: vec![],
    }
}

fn test_mutation(salt: usize) -> Mutation {
    Mutation {
        key: vec![salt as Word; 4],
        value: vec![42],
    }
}

#[test]
fn solution_data_mut_not_be_empty() {
    let set = empty_solution_set();
    assert!(matches!(
        solution::check_set(&set).unwrap_err(),
        solution::InvalidSolutionSet::Solution(solution::InvalidSolution::Empty),
    ));
}

#[test]
fn too_many_solution_data() {
    let set = SolutionSet {
        solutions: (0..solution::MAX_SOLUTIONS + 1)
            .map(|_| test_solution())
            .collect(),
    };
    assert!(matches!(
        solution::check_set(&set).unwrap_err(),
        solution::InvalidSolutionSet::Solution(solution::InvalidSolution::TooMany(n))
            if n == solution::MAX_SOLUTIONS + 1
    ));
}

#[test]
fn too_many_predicate_data() {
    let set = SolutionSet {
        solutions: vec![Solution {
            predicate_to_solve: test_predicate_addr(),
            predicate_data: vec![vec![0]; (solution::MAX_PREDICATE_DATA + 1) as usize],
            state_mutations: vec![],
        }],
    };
    assert!(matches!(
        solution::check_set(&set).unwrap_err(),
        solution::InvalidSolutionSet::Solution(solution::InvalidSolution::PredicateDataLenExceeded(0, n))
            if n == solution::MAX_PREDICATE_DATA as usize + 1
    ));
}

#[test]
fn too_many_state_mutations() {
    let set = SolutionSet {
        solutions: vec![Solution {
            predicate_to_solve: test_predicate_addr(),
            predicate_data: vec![],
            state_mutations: (0..(solution::MAX_STATE_MUTATIONS + 1))
                .map(test_mutation)
                .collect(),
        }],
    };
    assert!(matches!(
        solution::check_set(&set).unwrap_err(),
        solution::InvalidSolutionSet::StateMutations(solution::InvalidSetStateMutations::TooMany(n))
            if n == solution::MAX_STATE_MUTATIONS + 1
    ));
}

#[test]
fn multiple_mutations_for_slot() {
    let set = SolutionSet {
        solutions: vec![Solution {
            predicate_to_solve: test_predicate_addr(),
            predicate_data: vec![],
            state_mutations: vec![
                Mutation {
                    key: vec![0; 4],
                    value: vec![42],
                };
                2
            ],
        }],
    };
    assert!(matches!(
        solution::check_set(&set).unwrap_err(),
        solution::InvalidSolutionSet::StateMutations(solution::InvalidSetStateMutations::MultipleMutationsForSlot(addr, key))
            if addr == test_predicate_addr() && key == [0; 4]
    ));
}

// A simple test to check that resulting stacks are passed from parents to children.
//
// ```ignore
// a     b
//  \   /
//   \ /
//    v
//    c
// ```
#[tokio::test]
async fn predicate_graph_stack_passing() {
    use essential_vm::asm::short::*;
    let _ = tracing_subscriber::fmt::try_init();
    let a = Program(asm::to_bytes([PUSH(1), PUSH(2), PUSH(3), HLT]).collect());
    let b = Program(asm::to_bytes([PUSH(4), PUSH(5), PUSH(6), HLT]).collect());
    let c = Program(
        asm::to_bytes([
            // Stack should already have `[1, 2, 3, 4, 5, 6]`.
            PUSH(1),
            PUSH(2),
            PUSH(3),
            PUSH(4),
            PUSH(5),
            PUSH(6),
            // a `len` for `EqRange`.
            PUSH(6), // EqRange len
            EQRA,
            HLT,
        ])
        .collect(),
    );

    let a_ca = content_addr(&a);
    let b_ca = content_addr(&b);
    let c_ca = content_addr(&c);

    let node = |program_address, edge_start| Node {
        program_address,
        edge_start,
        reads: Reads::Pre, // unused for this test.
    };
    let nodes = vec![
        node(a_ca.clone(), 0),
        node(b_ca.clone(), 1),
        node(c_ca.clone(), Edge::MAX),
    ];
    let edges = vec![2, 2];
    let predicate = Predicate { nodes, edges };
    let contract = Contract::without_salt(vec![predicate]);
    let pred_addr = PredicateAddress {
        contract: content_addr(&contract),
        predicate: content_addr(&contract.predicates[0]),
    };

    // Create a solution that "solves" our predicate.
    let set = SolutionSet {
        solutions: vec![Solution {
            predicate_to_solve: pred_addr.clone(),
            predicate_data: Default::default(),
            state_mutations: vec![],
        }],
    };

    // First, validate both predicates and solution.
    essential_check::predicate::check(&contract.predicates[0]).unwrap();
    essential_check::solution::check_set(&set).unwrap();

    // There's only one predicate to solve.
    let predicate = Arc::new(contract.predicates[0].clone());
    let get_predicate = |addr: &PredicateAddress| {
        assert_eq!(&pred_addr, addr);
        predicate.clone()
    };
    let programs: HashMap<ContentAddress, Arc<Program>> = vec![
        (a_ca, Arc::new(a)),
        (b_ca, Arc::new(b)),
        (c_ca, Arc::new(c)),
    ]
    .into_iter()
    .collect();
    let get_program: Arc<HashMap<_, _>> = Arc::new(programs);

    // Run the check, and ensure ok and gas aren't 0.
    let gas = solution::check_set_predicates(
        &State::EMPTY,
        &State::EMPTY,
        Arc::new(set),
        get_predicate,
        get_program,
        Arc::new(solution::CheckPredicateConfig::default()),
    )
    .await
    .unwrap();

    assert!(gas > 0);
}

// A simple test to check that resulting memories are passed from parents to children.
//
// ```ignore
// a     b
//  \   /
//   \ /
//    v
//    c
// ```
#[tokio::test]
async fn predicate_graph_memory_passing() {
    use essential_vm::asm::short::*;
    let _ = tracing_subscriber::fmt::try_init();
    // Store `[1, 2, 3]` at the start of memory.
    let a = Program(
        asm::to_bytes([
            PUSH(3),
            ALOC,
            PUSH(1),
            STO,
            PUSH(1),
            PUSH(2),
            STO,
            PUSH(2),
            PUSH(3),
            STO,
            HLT,
        ])
        .collect(),
    );
    // Store `[4, 5, 6]` at the start of memory.
    let b = Program(
        asm::to_bytes([
            PUSH(3),
            ALOC,
            PUSH(4),
            STO,
            PUSH(1),
            PUSH(5),
            STO,
            PUSH(2),
            PUSH(6),
            STO,
            HLT,
        ])
        .collect(),
    );
    let c = Program(
        asm::to_bytes([
            // Memory should already have `[1, 2, 3, 4, 5, 6]` at the start.
            PUSH(0),
            LOD,
            PUSH(1),
            LOD,
            PUSH(2),
            LOD,
            PUSH(3),
            LOD,
            PUSH(4),
            LOD,
            PUSH(5),
            LOD,
            // Check that they're equal.
            PUSH(1),
            PUSH(2),
            PUSH(3),
            PUSH(4),
            PUSH(5),
            PUSH(6),
            // a `len` for `EqRange`.
            PUSH(6), // EqRange len
            EQRA,
            HLT,
        ])
        .collect(),
    );

    let a_ca = content_addr(&a);
    let b_ca = content_addr(&b);
    let c_ca = content_addr(&c);

    let node = |program_address, edge_start| Node {
        program_address,
        edge_start,
        reads: Reads::Pre, // unused for this test.
    };
    let nodes = vec![
        node(a_ca.clone(), 0),
        node(b_ca.clone(), 1),
        node(c_ca.clone(), Edge::MAX),
    ];
    let edges = vec![2, 2];
    let predicate = Predicate { nodes, edges };
    let contract = Contract::without_salt(vec![predicate]);
    let pred_addr = PredicateAddress {
        contract: content_addr(&contract),
        predicate: content_addr(&contract.predicates[0]),
    };

    // Create a solution that "solves" our predicate.
    let set = SolutionSet {
        solutions: vec![Solution {
            predicate_to_solve: pred_addr.clone(),
            predicate_data: Default::default(),
            state_mutations: vec![],
        }],
    };

    // First, validate both predicates and solution.
    essential_check::predicate::check(&contract.predicates[0]).unwrap();
    essential_check::solution::check_set(&set).unwrap();

    // There's only one predicate to solve.
    let predicate = Arc::new(contract.predicates[0].clone());
    let get_predicate = |addr: &PredicateAddress| {
        assert_eq!(&pred_addr, addr);
        predicate.clone()
    };
    let programs: HashMap<ContentAddress, Arc<Program>> = vec![
        (a_ca, Arc::new(a)),
        (b_ca, Arc::new(b)),
        (c_ca, Arc::new(c)),
    ]
    .into_iter()
    .collect();
    let get_program: Arc<HashMap<_, _>> = Arc::new(programs);

    // Run the check, and ensure ok and gas aren't 0.
    let gas = solution::check_set_predicates(
        &State::EMPTY,
        &State::EMPTY,
        Arc::new(set),
        get_predicate,
        get_program,
        Arc::new(solution::CheckPredicateConfig::default()),
    )
    .await
    .unwrap();

    assert!(gas > 0);
}

// A simple test to check that transient nodes can read state and provide the results to its
// children.
//
// In this program:
//
// 1. *a* pushes a key to the stack.
// 2. *b* uses the key to read from pre *and* post-state (under different nodes).
// 3. *c* multiples the values together and checks they equal 42.
//
//
// ```ignore
//         a
//       /   \
//      /     \
//     /       \
//    /         \
//   v           v
// b (pre)     b (post)
//    \         /
//     \       /
//      \     /
//       \   /
//        \ /
//         v
//         c
// ```
#[tokio::test]
async fn predicate_graph_state_read() {
    use essential_vm::asm::short::*;
    let _ = tracing_subscriber::fmt::try_init();

    let key = vec![9, 9, 9, 9];

    // Push the key and prepare the stack for the key read.
    let a = Program(
        asm::to_bytes(key.iter().map(|&w| PUSH(w)).chain([
            // Push the length and num keys to read for the `KeyRange` op.
            PUSH(4),
            PUSH(1),
            HLT,
        ]))
        .collect(),
    );
    // Perform the read op to read the value from state onto the stack.
    // FIXME: This will change with state slot removal.
    let b = Program(
        asm::to_bytes([
            // Allocate space for reading in [index, len, value].
            // ALOC returns `0` on the stack, i.e. the `mem_addr` to read into.
            PUSH(3),
            ALOC,
            // Read the key range into memory.
            KRNG,
            // Read the value from memory (i.e from `[index, len, value]`) onto the stack.
            PUSH(2),
            LOD,
            // Clear our memory - future programs don't need it.
            PUSH(0),
            FREE,
            // Remove the index, we're only reading one key.
            // POP,
            HLT,
        ])
        .collect(),
    );
    // Stack should now have `[6, 7]` at the start.
    // The `6` from pre-state, the `7` from post-state.
    let c = Program(asm::to_bytes([MUL, PUSH(42), EQ]).collect());

    let a_ca = content_addr(&a);
    let b_ca = content_addr(&b);
    let c_ca = content_addr(&c);

    let node = |program_address, edge_start, reads| Node {
        program_address,
        edge_start,
        reads,
    };
    let nodes = vec![
        node(a_ca.clone(), 0, Reads::Pre),
        node(b_ca.clone(), 2, Reads::Pre),
        node(b_ca.clone(), 3, Reads::Post),
        node(c_ca.clone(), Edge::MAX, Reads::Pre),
    ];
    let edges = vec![1, 2, 3, 3];
    let predicate = Predicate { nodes, edges };
    let contract = Contract::without_salt(vec![predicate]);
    let pred_addr = PredicateAddress {
        contract: content_addr(&contract),
        predicate: content_addr(&contract.predicates[0]),
    };

    // Create the state. The initial state should be 6.
    let mut pre_state = State::EMPTY;
    pre_state.deploy_namespace(pred_addr.contract.clone());
    pre_state.set(pred_addr.contract.clone(), &key, vec![6]);

    // Create a solution that "solves" our predicate.
    let set = SolutionSet {
        solutions: vec![Solution {
            predicate_to_solve: pred_addr.clone(),
            predicate_data: Default::default(),
            state_mutations: vec![
                // Set the post state to 7.
                Mutation {
                    key,
                    value: vec![7],
                },
            ],
        }],
    };

    // Apply the solution's mutations for the post state.
    let mut post_state = pre_state.clone();
    post_state.apply_mutations(&set);

    // First, validate both predicates and solution.
    essential_check::predicate::check(&contract.predicates[0]).unwrap();
    essential_check::solution::check_set(&set).unwrap();

    // There's only one predicate to solve.
    let predicate = Arc::new(contract.predicates[0].clone());
    let get_predicate = |addr: &PredicateAddress| {
        assert_eq!(&pred_addr, addr);
        predicate.clone()
    };
    let programs: HashMap<ContentAddress, Arc<Program>> = vec![
        (a_ca, Arc::new(a)),
        (b_ca, Arc::new(b)),
        (c_ca, Arc::new(c)),
    ]
    .into_iter()
    .collect();
    let get_program: Arc<HashMap<_, _>> = Arc::new(programs);

    // Run the check, and ensure ok and gas aren't 0.
    let gas = solution::check_set_predicates(
        &pre_state,
        &post_state,
        Arc::new(set),
        get_predicate,
        get_program,
        Arc::new(solution::CheckPredicateConfig::default()),
    )
    .await
    .unwrap();

    assert!(gas > 0);
}