Skip to content

Commit

Permalink
updating Miden VM version in the playground
Browse files Browse the repository at this point in the history
  • Loading branch information
Dominik1999 committed Apr 30, 2024
1 parent 523acc1 commit 71f70a1
Show file tree
Hide file tree
Showing 10 changed files with 60 additions and 43 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/gh-pages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: Deploy Miden Assembly Playground
on:
push:
branches:
- main
- dominik_update_to_miden_vm_0.9

jobs:
build:
Expand Down
8 changes: 4 additions & 4 deletions playground/miden-wasm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ edition = "2021"
crate-type = ["cdylib", "rlib"]

[dependencies]
assembly = { package = "miden-assembly", version = "0.7.0", default-features = false }
assembly = { package = "miden-assembly", version = "0.9", default-features = false }
hex = { version = "0.4", default-features = false }
miden-air = { package = "miden-air", version = "0.7.0", default-features = false }
miden-vm = { package = "miden-vm", version = "0.7.0", default-features = false }
miden-stdlib = { package = "miden-stdlib", version = "0.6.0", default-features = false }
miden-air = { package = "miden-air", version = "0.9", default-features = false }
miden-vm = { package = "miden-vm", version = "0.9", default-features = false }
miden-stdlib = { package = "miden-stdlib", version = "0.9", default-features = false }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde-wasm-bindgen = "0.4"
Expand Down
22 changes: 15 additions & 7 deletions playground/miden-wasm/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
extern crate alloc;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

mod utils_debug;
mod utils_input;
mod utils_program;
use miden_vm::{ExecutionProof, ProvingOptions, DefaultHost, MemAdviceProvider};
use miden_air::ExecutionOptions;
use miden_vm::{ExecutionProof, MemAdviceProvider, DefaultHost, ProvingOptions};
use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::*;

Expand Down Expand Up @@ -32,8 +36,7 @@ pub fn run_program(code_frontend: &str, inputs_frontend: &str) -> Result<Outputs

let host = DefaultHost::new(MemAdviceProvider::from(inputs.advice_provider));

let execution_options = ExecutionOptions::new(None, 64 as u32)
.map_err(|err| format!("{err}"))?;
let execution_options = ExecutionOptions::default();

let trace = miden_vm::execute(
&program.program.unwrap(),
Expand All @@ -43,9 +46,11 @@ pub fn run_program(code_frontend: &str, inputs_frontend: &str) -> Result<Outputs
)
.map_err(|err| format!("Failed to generate execution trace - {:?}", err))?;

let stack_output = trace.stack_outputs().stack().iter().map(|felt| felt.as_int()).collect();

let result = Outputs {
program_hash: program.program_info.unwrap().program_hash().to_string(),
stack_output: trace.stack_outputs().stack().to_vec(),
stack_output: stack_output,
cycles: Some(trace.trace_len_summary().trace_len()),
trace_len: Some(trace.get_trace_len()),
overflow_addrs: None,
Expand Down Expand Up @@ -82,12 +87,15 @@ pub fn prove_program(code_frontend: &str, inputs_frontend: &str) -> Result<Outpu
)
.map_err(|err| format!("Failed to prove execution - {:?}", err))?;

let stack_output = output.stack().iter().map(|felt| felt.as_int()).collect();
let overflow_addrs = output.overflow_addrs().iter().map(|felt| felt.as_int()).collect::<Vec<_>>();

let result = Outputs {
program_hash: program.program_info.clone().unwrap().program_hash().to_string(),
stack_output: output.stack().to_vec(),
stack_output: stack_output,
cycles: None,
trace_len: Some(proof.stark_proof().trace_length()),
overflow_addrs: Some(output.overflow_addrs().to_vec()),
overflow_addrs: Some(overflow_addrs),
proof: Some(proof.to_bytes()),
};

Expand Down Expand Up @@ -253,7 +261,7 @@ fn test_debug_program() {
// we test playing one more cycle
let output = debug_executor_2.execute(utils_debug::DebugCommand::Play, Some(1));
assert_eq!(output.clk, 4);
assert_eq!(output.op, Some("Push(BaseElement(8589934590))".to_string()));
assert_eq!(output.op, Some("Push(2)".to_string()));
assert_eq!(output.instruction, Some("\"push.2\"".to_string()));
assert_eq!(output.num_of_operations, Some(1));
assert_eq!(output.operation_index, Some(1));
Expand Down
4 changes: 3 additions & 1 deletion playground/miden-wasm/src/utils_debug.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use crate::utils_input::Inputs;
use crate::utils_program::{MidenProgram, DEBUG_ON};
use miden_vm::{math::StarkField, VmState, VmStateIterator, Word, DefaultHost, MemAdviceProvider};
use miden_vm::{VmState, VmStateIterator, Word, DefaultHost, MemAdviceProvider};
use wasm_bindgen::prelude::*;
use alloc::string::String;
use alloc::vec::Vec;

// This is the main struct that will be exported to JS
// It will be used to execute debug commands against the VM
Expand Down
45 changes: 25 additions & 20 deletions playground/miden-wasm/src/utils_input.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
use miden_vm::{
crypto::{MerkleStore, MerkleTree, SimpleSmt},
math::{Felt, FieldElement},
utils::collections::BTreeMap,
AdviceInputs, MemAdviceProvider, StackInputs, StackOutputs, Word,
crypto::{MerkleStore, MerkleTree, SimpleSmt, RpoDigest},
math::Felt,
AdviceInputs, MemAdviceProvider, StackInputs, StackOutputs, Word, ZERO,
};

use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

// CONSTANTS
// ================================================================================================
const SIMPLE_SMT_DEPTH: u8 = u64::BITS as u8;

/// The Outputs struct is used to serialize the output of the program.
/// Via Rust WASM we cannot return arbitrary structs, so we need to serialize it to JSON.
/// Here we need the Outputs because they can be inputs for the verifier.
Expand Down Expand Up @@ -103,7 +110,7 @@ impl InputFile {
}

/// Parse advice map data from the input file.
fn parse_advice_map(&self) -> Result<Option<BTreeMap<[u8; 32], Vec<Felt>>>, String> {
fn parse_advice_map(&self) -> Result<Option<BTreeMap<RpoDigest, Vec<Felt>>>, String> {
let advice_map = match &self.advice_map {
Some(advice_map) => advice_map,
None => return Ok(None),
Expand All @@ -112,23 +119,22 @@ impl InputFile {
let map = advice_map
.iter()
.map(|(k, v)| {
// decode hex key
let mut key = [0u8; 32];
hex::decode_to_slice(k, &mut key)
.map_err(|e| format!("failed to decode advice map key `{k}` - {e}"))?;
// Convert key to RpoDigest
let key = RpoDigest::try_from(k)
.map_err(|e| format!("failed to decode advice map key '{k}': {e}"))?;

// convert values to Felt
let values = v
.iter()
.map(|v| {
Felt::try_from(*v).map_err(|e| {
format!("failed to convert advice map value `{v}` to Felt - {e}")
format!("failed to convert advice map value '{v}' to Felt: {e}")
})
})
.collect::<Result<Vec<_>, _>>()?;
Ok((key, values))
})
.collect::<Result<BTreeMap<[u8; 32], Vec<Felt>>, String>>()?;
.collect::<Result<BTreeMap<RpoDigest, Vec<Felt>>, String>>()?;

Ok(Some(map))
}
Expand All @@ -152,10 +158,9 @@ impl InputFile {
MerkleData::SparseMerkleTree(data) => {
let entries = Self::parse_sparse_merkle_tree(data)?;
// TODO: Support variable depth
let smt =
SimpleSmt::with_leaves(SimpleSmt::MAX_DEPTH, entries).map_err(|e| {
format!("failed to add sparse merkle tree to merkle store - {e}")
})?;
let smt = SimpleSmt::<SIMPLE_SMT_DEPTH>::with_leaves(entries)
.map_err(|e| format!("failed to parse a Sparse Merkle Tree: {e}"))?;

merkle_store.extend(smt.inner_nodes());
}
}
Expand Down Expand Up @@ -210,7 +215,7 @@ impl InputFile {
.map(|v| v.parse::<u64>().map_err(|e| e.to_string()))
.collect::<Result<Vec<_>, _>>()?;

StackInputs::try_from_values(stack_inputs).map_err(|e| e.to_string())
StackInputs::try_from_ints(stack_inputs).map_err(|e| e.to_string())
}
}

Expand All @@ -225,7 +230,7 @@ pub struct Inputs {
impl Inputs {
pub fn new() -> Self {
Self {
stack_inputs: StackInputs::new(vec![Felt::ZERO]),
stack_inputs: StackInputs::new(vec![ZERO]).unwrap(),
advice_provider: MemAdviceProvider::default(),
stack_outputs: StackOutputs::new(vec![], vec![]).unwrap(),
}
Expand All @@ -246,7 +251,7 @@ impl Inputs {
let outputs_as_json: Outputs =
serde_json::from_str(outputs_as_str).map_err(|e| e.to_string())?;

let outputs = StackOutputs::new(
let outputs = StackOutputs::try_from_ints(
outputs_as_json.stack_output,
outputs_as_json.overflow_addrs.unwrap_or(vec![]),
).unwrap();
Expand All @@ -273,7 +278,7 @@ fn test_parse_output() {

assert_eq!(
output.stack(),
vec![3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
vec![Felt::new(3), ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO]
);
assert_eq!(output.overflow_addrs(), vec![0, 1]);
assert_eq!(output.overflow_addrs(), vec![ZERO, Felt::new(1)]);
}
1 change: 1 addition & 0 deletions playground/miden-wasm/src/utils_program.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use miden_stdlib::StdLibrary;
use miden_vm::{Assembler, Kernel, Program, ProgramInfo};
use alloc::string::{String, ToString};

pub struct MidenProgram {
pub assembler: Assembler,
Expand Down
Binary file removed playground/public/miden_tx_demo_prepare.mp4
Binary file not shown.
Binary file removed playground/public/miden_tx_demo_prove.mp4
Binary file not shown.
12 changes: 6 additions & 6 deletions playground/src/components/DropDown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import { ChevronDownIcon } from '@heroicons/react/24/solid';
const examples = [
'addition',
'catalan',
'collatz',
'comparison',
//'collatz',
//'comparison',
'conditional',
'fibonacci',
'game_of_life_4x4',
'matrix_multiplication',
'nprime',
//'matrix_multiplication',
//'nprime',
'shamir_secret_share',
'standard_library',
'advice_provider',
//'standard_library',
//'advice_provider',
];

function classExamples(...classes: string[]) {
Expand Down
9 changes: 5 additions & 4 deletions playground/src/pages/CodingEnvironment.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,9 @@ export default function CodingEnvironment(): JSX.Element {
setProof(null);
setDisableForm(false);

// reset the output
setOutput(emptyOutput);

const value = exampleChange;

// set the current example to the selected one
Expand All @@ -199,9 +202,6 @@ export default function CodingEnvironment(): JSX.Element {
if (isCodeEditorVisible) {
setCodeUploadContent(await example_code[0]);
}

// reset the output
setOutput(emptyOutput);
};

const hideAllRightSideLayout = () => {
Expand Down Expand Up @@ -427,6 +427,7 @@ export default function CodingEnvironment(): JSX.Element {
proof
}: Outputs = prove_program(code, inputs);
const overflow = overflow_addrs ? overflow_addrs.toString() : '[]';
setStackOutputValue(stack_output.toString());
setProgramInfo(
`Program Hash: ${program_hash}
Cycles: ${cycles}
Expand Down Expand Up @@ -804,4 +805,4 @@ export default function CodingEnvironment(): JSX.Element {
)}
</div>
);
}
}

0 comments on commit 71f70a1

Please sign in to comment.