wacc 2.0.0

Web Assembly Cryptographic Constructs VM implementation
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
#![allow(
    clippy::string_lit_as_bytes,
    clippy::manual_string_new,
    clippy::needless_pass_by_value,
    clippy::uninlined_format_args,
    clippy::needless_collect,
    clippy::cast_sign_loss
)]
// SPDX-License-Identifier: Apache-2.0
use std::{collections::BTreeMap, fs::read, path::PathBuf, sync::Arc};
use test_log::test;
use tracing::{info, span, Level};
use wacc::types::{CheckCount, ContextPath};
use wacc::{
    storage::{Pairs, Stack},
    vm::{Builder, Context, Instance, Value},
};
use wasmtime::{AsContextMut, StoreLimitsBuilder};

const MEMORY_LIMIT: usize = 1 << 22; /* 4MB */

fn load_wasm(file_name: &str) -> Option<Vec<u8>> {
    let mut pb = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    pb.push("target");
    pb.push(file_name);
    info!("trying to load: {}", pb.as_os_str().display());
    read(&pb).ok()
}

fn load_wast(file_name: &str) -> Vec<u8> {
    let mut pb = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    pb.push("examples/wacc/wast");
    pb.push(file_name);
    info!("trying to load: {}", pb.as_os_str().display());
    read(&pb).unwrap_or_else(|_| panic!("WAST file {} must exist", file_name))
}

fn test_example(
    script: Vec<u8>,
    func: &str,
    expected: bool,
    current: Kvp,
    proposed: Kvp,
    pstack: Stk,
    rstack: Stk,
) -> Instance {
    // build the context
    let context = Context {
        current: Box::new(current),
        proposed: Box::new(proposed),
        pstack: Box::new(pstack),
        rstack: Box::new(rstack),
        check_count: CheckCount::zero(),
        write_idx: 0,
        context: ContextPath::new("/forks/child/"),
        log: Vec::default(),
        limiter: StoreLimitsBuilder::new()
            .memory_size(MEMORY_LIMIT)
            .instances(2)
            .memories(1)
            .build(),
    };

    // construct the instance
    let mut instance = match Builder::new()
        .with_context(context)
        .with_bytes(&script)
        .try_build()
    {
        Ok(i) => i,
        Err(e) => {
            println!("builder failed: {}", e);
            panic!()
        }
    };

    // execute the instance
    let result = instance.run(func).unwrap();

    assert_eq!(expected, result);
    instance
}

#[derive(Default, Clone)]
struct Kvp {
    pub pairs: BTreeMap<String, Value>,
}

impl Pairs for Kvp {
    /// get a value associated with the key
    fn get(&self, key: &str) -> Option<Value> {
        self.pairs.get(key).cloned()
    }

    /// add a key-value pair to the storage, return previous value if overwritten
    fn put(&mut self, key: &str, value: &Value) -> Option<Value> {
        self.pairs.insert(key.to_string(), value.clone())
    }
}

#[derive(Default, Clone)]
struct Stk {
    pub stack: Vec<Value>,
}

impl Stack for Stk {
    /// push a value onto the stack
    fn push(&mut self, value: Value) {
        self.stack.push(value);
    }

    /// remove the last top value from the stack
    fn pop(&mut self) -> Option<Value> {
        self.stack.pop()
    }

    /// get a reference to the top value on the stack
    fn top(&self) -> Option<Value> {
        self.stack.last().cloned()
    }

    /// peek at the item at the given index
    fn peek(&self, idx: usize) -> Option<Value> {
        if idx >= self.stack.len() {
            return None;
        }
        Some(self.stack[self.stack.len() - 1 - idx].clone())
    }

    /// return the number of values on the stack
    fn len(&self) -> usize {
        self.stack.len()
    }

    /// return if the stack is empty
    fn is_empty(&self) -> bool {
        self.stack.is_empty()
    }
}

#[test]
fn test_pubkey_lock_wast() {
    let _span_ = span!(Level::INFO, "test_pubkey_lock_wast").entered();
    // the key-value pair store with the message and signature data
    let mut kvp_unlock = Kvp::default();
    // the key-value pair store with the encoded Multikey
    let mut kvp_lock = Kvp::default();

    // Values to transfer from unlock to lock phase
    let mut pstack_values: Vec<Value>;

    {
        // unlock
        // create the stack to use for unlock
        let pstack = Stk::default();
        let rstack = Stk::default();

        // set up the key-value pair store with the message and signature data
        let _ = kvp_unlock.put(
            "/entry/",
            &"for great justice, move every zig!".as_bytes().into(),
        );
        let _ = kvp_unlock.put("/entry/proof", &hex::decode("b92483a6c0060001004076fee92ca796162b5e37a84b4150da685d636491b43c1e2a1fab392a7337553502588a609075b56c46b5c033b260d8d314b584e396fc2221c55f54843679ee08").unwrap().into());

        // load the unlock script
        let script = load_wast("unlock.wast");

        // run the unlock script to set up the stack
        let mut instance = test_example(
            script,
            "for_great_justice",
            true,
            kvp_unlock.clone(),
            kvp_unlock.clone(),
            pstack,
            rstack,
        );

        // check that the stack is what we expect and save values
        let mut ctx = instance.store.as_context_mut();
        let context = ctx.data_mut();
        assert_eq!(1, context.pstack.len());
        assert_eq!(context.pstack.top(), Some(Value::Bin { hint: "".to_string(), data: Arc::from(hex::decode("b92483a6c0060001004076fee92ca796162b5e37a84b4150da685d636491b43c1e2a1fab392a7337553502588a609075b56c46b5c033b260d8d314b584e396fc2221c55f54843679ee08").unwrap().into_boxed_slice()) }));
        // Save the pstack values for the lock phase by extracting them
        pstack_values = vec![];
        for i in 0..context.pstack.len() {
            if let Some(val) = context.pstack.peek(context.pstack.len() - 1 - i) {
                pstack_values.push(val);
            }
        }
    }

    {
        // lock
        // create the stack to use for lock and populate it with values from unlock phase
        let pstack = Stk {
            stack: pstack_values,
        };
        let rstack = Stk::default();

        // set up the key-value pair store with the encoded Multikey
        let _ = kvp_lock.put("/keys/primary", &hex::decode("ba24ed010874657374206b657901012084d515ef051e07d597f3c14ac09e5a9d5012c659c196d96db5c6b98ea552f603").unwrap().into());

        // load the lock script
        let script = load_wast("lock.wast");

        // run the lock script to check the proof
        let mut instance = test_example(
            script,
            "move_every_zig",
            true,
            kvp_lock,
            kvp_unlock,
            pstack,
            rstack,
        );

        // check that the stack is what we expect
        let mut ctx = instance.store.as_context_mut();
        let context = ctx.data_mut();
        assert_eq!(2, context.rstack.len());
        // NOTE: the check count is 1 because the check_signature("/tpubkey") failed before the
        // check_signature("/keys/primary") succeeded.
        assert_eq!(context.rstack.top(), Some(Value::Success(1)));
    }
}

#[test]
fn test_preimage_lock_wast() {
    // the key-value pair store with the message and signature data
    let mut kvp_unlock = Kvp::default();
    // the key-value pair store with the encoded Multikey
    let mut kvp_lock = Kvp::default();

    // Values to transfer from unlock to lock phase
    let mut pstack_values: Vec<Value>;

    {
        // unlock
        // create the stack to use for unlock
        let pstack = Stk::default();
        let rstack = Stk::default();

        // set up the key-value pair store with the message and a preimage
        let _ = kvp_unlock.put("/entry/", &"blah".as_bytes().into());
        let _ = kvp_unlock.put(
            "/entry/proof",
            &"for great justice, move every zig!".as_bytes().into(),
        );

        // load the unlock script
        let script = load_wast("unlock.wast");

        // run the unlock script to set up the stack
        let mut instance = test_example(
            script,
            "for_great_justice",
            true,
            kvp_unlock.clone(),
            kvp_unlock.clone(),
            pstack,
            rstack,
        );

        // check that the stack is what we expect and save values
        let mut ctx = instance.store.as_context_mut();
        let context = ctx.data_mut();
        assert_eq!(1, context.pstack.len());
        assert_eq!(
            context.pstack.top(),
            Some(Value::Bin {
                hint: "".to_string(),
                data: Arc::from(&b"for great justice, move every zig!"[..])
            })
        );
        // Save the pstack values for the lock phase by extracting them
        pstack_values = vec![];
        for i in 0..context.pstack.len() {
            if let Some(val) = context.pstack.peek(context.pstack.len() - 1 - i) {
                pstack_values.push(val);
            }
        }
    }

    {
        // lock
        // create the stack to use for lock and populate it with values from unlock phase
        let pstack = Stk {
            stack: pstack_values,
        };
        let rstack = Stk::default();

        // set up the key-value pair store with the encoded Multihash
        let _ = kvp_lock.put(
            "/hash",
            &hex::decode("16206b761d3b2e7675e088e337a82207b55711d3957efdb877a3d261b0ca2c38e201")
                .unwrap()
                .into(),
        );

        // load the lock script
        let script = load_wast("lock.wast");

        // run the lock script to check the proof
        let mut instance = test_example(
            script,
            "move_every_zig",
            true,
            kvp_lock,
            kvp_unlock,
            pstack,
            rstack,
        );

        // check that the stack is what we expect
        let mut ctx = instance.store.as_context_mut();
        let context = ctx.data_mut();
        // NOTE: the check_preimage("/hash") call only pops the top preimage off of the stack so
        // the message is still on there giving the len of 2
        assert_eq!(3, context.rstack.len());
        // NOTE: the check count is 2 because the check_signature("/tpubkey") and
        // check_signature("/keys/primary") failed before the check_preimage("/hash") succeeded
        assert_eq!(context.rstack.top(), Some(Value::Success(2)));
    }
}

#[test]
fn test_pubkey_lock_wasm() {
    // Skip test if WASM file not built (requires wat2wasm tool)
    let Some(unlock_script) = load_wasm("unlock.wasm") else {
        eprintln!("Skipping test_pubkey_lock_wasm: unlock.wasm not found (run 'make' in examples/wast to build)");
        return;
    };
    let Some(lock_script) = load_wasm("lock.wasm") else {
        eprintln!("Skipping test_pubkey_lock_wasm: lock.wasm not found (run 'make' in examples/wast to build)");
        return;
    };

    // the key-value pair store with the message and signature data
    let mut kvp_unlock = Kvp::default();
    // the key-value pair store with the encoded Multikey
    let mut kvp_lock = Kvp::default();

    // Values to transfer from unlock to lock phase
    let mut pstack_values: Vec<Value>;

    {
        // unlock
        // create the stack to use for unlock
        let pstack = Stk::default();
        let rstack = Stk::default();

        // set up the key-value pair store with the message and signature data
        let _ = kvp_unlock.put(
            "/entry/",
            &"for great justice, move every zig!".as_bytes().into(),
        );
        let _ = kvp_unlock.put("/entry/proof", &hex::decode("b92483a6c0060001004076fee92ca796162b5e37a84b4150da685d636491b43c1e2a1fab392a7337553502588a609075b56c46b5c033b260d8d314b584e396fc2221c55f54843679ee08").unwrap().into());

        // run the unlock script to set up the stack
        let mut instance = test_example(
            unlock_script,
            "for_great_justice",
            true,
            kvp_unlock.clone(),
            kvp_unlock.clone(),
            pstack,
            rstack,
        );

        // check that the stack is what we expect and save values
        let mut ctx = instance.store.as_context_mut();
        let context = ctx.data_mut();
        assert_eq!(1, context.pstack.len());
        assert_eq!(context.pstack.top(), Some(Value::Bin { hint: "".to_string(), data: Arc::from(hex::decode("b92483a6c0060001004076fee92ca796162b5e37a84b4150da685d636491b43c1e2a1fab392a7337553502588a609075b56c46b5c033b260d8d314b584e396fc2221c55f54843679ee08").unwrap().into_boxed_slice()) }));
        // Save the pstack values for the lock phase by extracting them
        pstack_values = vec![];
        for i in 0..context.pstack.len() {
            if let Some(val) = context.pstack.peek(context.pstack.len() - 1 - i) {
                pstack_values.push(val);
            }
        }
    }

    {
        // lock
        // create the stack to use for lock and populate it with values from unlock phase
        let pstack = Stk {
            stack: pstack_values,
        };
        let rstack = Stk::default();

        // set up the key-value pair store with the encoded Multikey
        let _ = kvp_lock.put("/keys/primary", &hex::decode("ba24ed010874657374206b657901012084d515ef051e07d597f3c14ac09e5a9d5012c659c196d96db5c6b98ea552f603").unwrap().into());

        // run the lock script to check the proof
        let mut instance = test_example(
            lock_script,
            "move_every_zig",
            true,
            kvp_lock,
            kvp_unlock,
            pstack,
            rstack,
        );

        // check that the stack is what we expect
        let mut ctx = instance.store.as_context_mut();
        let context = ctx.data_mut();
        assert_eq!(2, context.rstack.len());
        // NOTE: the check count is 1 because the check_signature("/tpubkey") failed before the
        // check_signature("/keys/primary") succeeded.
        assert_eq!(context.rstack.top(), Some(Value::Success(1)));
    }
}

#[test]
fn test_preimage_lock_wasm() {
    // Skip test if WASM file not built (requires wat2wasm tool)
    let Some(unlock_script) = load_wasm("unlock.wasm") else {
        eprintln!("Skipping test_preimage_lock_wasm: unlock.wasm not found (run 'make' in examples/wast to build)");
        return;
    };
    let Some(lock_script) = load_wasm("lock.wasm") else {
        eprintln!("Skipping test_preimage_lock_wasm: lock.wasm not found (run 'make' in examples/wast to build)");
        return;
    };

    // the key-value pair store with the message and signature data
    let mut kvp_unlock = Kvp::default();
    // the key-value pair store with the encoded Multikey
    let mut kvp_lock = Kvp::default();

    // Values to transfer from unlock to lock phase
    let mut pstack_values: Vec<Value>;

    {
        // unlock
        // create the stack to use for unlock
        let pstack = Stk::default();
        let rstack = Stk::default();

        // set up the key-value pair store with the message and a preimage
        let _ = kvp_unlock.put("/entry/", &"blah".as_bytes().into());
        let _ = kvp_unlock.put(
            "/entry/proof",
            &"for great justice, move every zig!".as_bytes().into(),
        );

        // run the unlock script to set up the stack
        let mut instance = test_example(
            unlock_script,
            "for_great_justice",
            true,
            kvp_unlock.clone(),
            kvp_unlock.clone(),
            pstack,
            rstack,
        );

        // check that the stack is what we expect and save values
        let mut ctx = instance.store.as_context_mut();
        let context = ctx.data_mut();
        assert_eq!(1, context.pstack.len());
        assert_eq!(
            context.pstack.top(),
            Some(Value::Bin {
                hint: "".to_string(),
                data: Arc::from(&b"for great justice, move every zig!"[..])
            })
        );
        // Save the pstack values for the lock phase by extracting them
        pstack_values = vec![];
        for i in 0..context.pstack.len() {
            if let Some(val) = context.pstack.peek(context.pstack.len() - 1 - i) {
                pstack_values.push(val);
            }
        }
    }

    {
        // lock
        // create the stack to use for lock and populate it with values from unlock phase
        let pstack = Stk {
            stack: pstack_values,
        };
        let rstack = Stk::default();

        // set up the key-value pair store with the encoded Multihash
        let _ = kvp_lock.put(
            "/hash",
            &hex::decode("16206b761d3b2e7675e088e337a82207b55711d3957efdb877a3d261b0ca2c38e201")
                .unwrap()
                .into(),
        );

        // run the lock script to check the proof
        let mut instance = test_example(
            lock_script,
            "move_every_zig",
            true,
            kvp_lock,
            kvp_unlock,
            pstack,
            rstack,
        );

        // check that the stack is what we expect
        let mut ctx = instance.store.as_context_mut();
        let context = ctx.data_mut();
        // NOTE: the check_preimage("/hash") call only pops the top preimage off of the stack so
        // the message is still on there giving the len of 2
        assert_eq!(3, context.rstack.len());
        // NOTE: the check count is 2 because the check_signature("/tpubkey") and
        // check_signature("/keys/primary") failed before the check_preimage("/hash") succeeded
        assert_eq!(context.rstack.top(), Some(Value::Success(2)));
    }
}