Merge branch 'main' of github.com:mir-protocol/plonky2 into bls-fp2

This commit is contained in:
Dmitry Vagner 2023-04-10 16:05:57 -07:00
commit d79d2c4915
38 changed files with 5819 additions and 163 deletions

View File

@ -7,6 +7,24 @@ This repository was originally for Plonky2, a SNARK implementation based on tech
For more details about the Plonky2 argument system, see this [writeup](plonky2/plonky2.pdf).
Polymer Labs has written up a helpful tutorial [here](https://polymerlabs.medium.com/a-tutorial-on-writing-zk-proofs-with-plonky2-part-i-be5812f6b798)!
## Examples
A good starting point for how to use Plonky2 for simple applications is the included examples:
* [`factorial`](plonky2/examples/factorial.rs): Proving knowledge of 100!
* [`fibonacci`](plonky2/examples/fibonacci.rs): Proving knowledge of the hundredth Fibonacci number
* [`range_check`](plonky2/examples/range_check.rs): Proving that a field element is in a given range
* [`square_root`](plonky2/examples/square_root.rs): Proving knowledge of the square root of a given field element
To run an example, use
```sh
cargo run --example <example_name>
```
## Building

View File

@ -34,6 +34,7 @@ rlp = "0.5.1"
rlp-derive = "0.1.0"
serde = { version = "1.0.144", features = ["derive"] }
static_assertions = "1.1.0"
hashbrown = { version = "0.12.3" }
tiny-keccak = "2.0.2"
[target.'cfg(not(target_env = "msvc"))'.dependencies]

View File

@ -91,7 +91,6 @@ impl Table {
pub(crate) fn all_cross_table_lookups<F: Field>() -> Vec<CrossTableLookup<F>> {
let mut ctls = vec![ctl_keccak_sponge(), ctl_keccak(), ctl_logic(), ctl_memory()];
// TODO: Some CTLs temporarily disabled while we get them working.
disable_ctl(&mut ctls[0]);
disable_ctl(&mut ctls[3]);
ctls
}

View File

@ -146,7 +146,7 @@ impl<F: RichField + Extendable<D>, const D: usize> Stark<F, D> for CpuStark<F, D
bootstrap_kernel::eval_bootstrap_kernel(vars, yield_constr);
contextops::eval_packed(local_values, next_values, yield_constr);
control_flow::eval_packed_generic(local_values, next_values, yield_constr);
decode::eval_packed_generic(local_values, &mut dummy_yield_constr);
decode::eval_packed_generic(local_values, yield_constr);
dup_swap::eval_packed(local_values, yield_constr);
gas::eval_packed(local_values, next_values, yield_constr);
jumps::eval_packed(local_values, next_values, yield_constr);
@ -176,7 +176,7 @@ impl<F: RichField + Extendable<D>, const D: usize> Stark<F, D> for CpuStark<F, D
bootstrap_kernel::eval_bootstrap_kernel_circuit(builder, vars, yield_constr);
contextops::eval_ext_circuit(builder, local_values, next_values, yield_constr);
control_flow::eval_ext_circuit(builder, local_values, next_values, yield_constr);
decode::eval_ext_circuit(builder, local_values, &mut dummy_yield_constr);
decode::eval_ext_circuit(builder, local_values, yield_constr);
dup_swap::eval_ext_circuit(builder, local_values, yield_constr);
gas::eval_ext_circuit(builder, local_values, next_values, yield_constr);
jumps::eval_ext_circuit(builder, local_values, next_values, yield_constr);

View File

@ -191,7 +191,7 @@ pub fn eval_packed_generic<P: PackedField>(
.into_iter()
.zip(bits_from_opcode(oc))
.rev()
.take(block_length + 1)
.take(8 - block_length)
.map(|(row_bit, flag_bit)| match flag_bit {
// 1 if the bit does not match, and 0 otherwise
false => row_bit,
@ -264,7 +264,7 @@ pub fn eval_ext_circuit<F: RichField + Extendable<D>, const D: usize>(
.into_iter()
.zip(bits_from_opcode(oc))
.rev()
.take(block_length + 1)
.take(8 - block_length)
.fold(builder.zero_extension(), |cumul, (row_bit, flag_bit)| {
let to_add = match flag_bit {
false => row_bit,

View File

@ -17,6 +17,8 @@ pub(crate) fn combined_kernel() -> Kernel {
include_str!("asm/bignum/addmul.asm"),
include_str!("asm/bignum/cmp.asm"),
include_str!("asm/bignum/iszero.asm"),
include_str!("asm/bignum/modexp.asm"),
include_str!("asm/bignum/modmul.asm"),
include_str!("asm/bignum/mul.asm"),
include_str!("asm/bignum/shr.asm"),
include_str!("asm/bignum/util.asm"),
@ -109,6 +111,7 @@ pub(crate) fn combined_kernel() -> Kernel {
include_str!("asm/mpt/util.asm"),
include_str!("asm/rlp/decode.asm"),
include_str!("asm/rlp/encode.asm"),
include_str!("asm/rlp/encode_rlp_scalar.asm"),
include_str!("asm/rlp/encode_rlp_string.asm"),
include_str!("asm/rlp/num_bytes.asm"),
include_str!("asm/rlp/read_to_memory.asm"),

View File

@ -131,6 +131,10 @@ global extcodecopy:
%jump(load_code)
extcodecopy_contd:
// stack: code_size, size, offset, dest_offset, retdest
DUP1 DUP4
// stack: offset, code_size, code_size, size, offset, dest_offset, retdest
GT %jumpi(extcodecopy_large_offset)
// stack: code_size, size, offset, dest_offset, retdest
SWAP1
// stack: size, code_size, offset, dest_offset, retdest
@ -178,6 +182,12 @@ extcodecopy_end:
%stack (i, size, code_size, offset, dest_offset, retdest) -> (retdest)
JUMP
extcodecopy_large_offset:
// offset is larger than the code size. So we just have to write zeros.
// stack: code_size, size, offset, dest_offset, retdest
GET_CONTEXT
%stack (context, code_size, size, offset, dest_offset, retdest) -> (context, @SEGMENT_MAIN_MEMORY, dest_offset, 0, size, retdest)
%jump(memset)
// Loads the code at `address` into memory, at the given context and segment, starting at offset 0.
// Checks that the hash of the loaded code corresponds to the `codehash` in the state trie.

View File

@ -6,7 +6,6 @@
global add_bignum:
// stack: len, a_start_loc, b_start_loc, retdest
DUP1
// stack: len, len, a_start_loc, b_start_loc, retdest
ISZERO
%jumpi(len_zero)
// stack: len, a_start_loc, b_start_loc, retdest
@ -57,6 +56,7 @@ add_end:
SWAP1
// stack: retdest, carry_new
JUMP
len_zero:
// stack: len, a_start_loc, b_start_loc, retdest
%pop3

View File

@ -101,6 +101,7 @@ addmul_end:
SWAP1
// stack: retdest, carry_limb_new
JUMP
len_zero:
// stack: len, a_start_loc, b_start_loc, val, retdest
%pop4

View File

@ -0,0 +1,135 @@
// Arithmetic on integers represented with 128-bit limbs.
// These integers are represented in LITTLE-ENDIAN form.
// All integers must be under a given length bound, and are padded with leading zeroes.
// Stores b ^ e % m in output_loc, leaving b, e, and m unchanged.
// b, e, and m must have the same length.
// output_loc must have size length and be initialized with zeroes; scratch_1 must have size length.
// All of scratch_2..scratch_5 must have size 2 * length and be initialized with zeroes.
// Also, scratch_2..scratch_5 must be CONSECUTIVE in memory.
global modexp_bignum:
// stack: len, b_loc, e_loc, m_loc, out_loc, s1 (=scratch_1), s2, s3, s4, s5, retdest
DUP1
ISZERO
%jumpi(len_zero)
// We store the repeated-squares accumulator x_i in scratch_1, starting with x_0 := b.
DUP1
DUP3
DUP8
// stack: s1, b_loc, len, len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
%memcpy_kernel_general
// stack: len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
// We store the accumulated output value x_i in output_loc, starting with x_0=1.
PUSH 1
DUP6
// stack: out_loc, 1, len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
%mstore_kernel_general
modexp_loop:
// stack: len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
// y := e % 2
DUP3
// stack: e_loc, len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
%mload_kernel_general
// stack: e_first, len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
%mod_const(2)
// stack: y = e_first % 2 = e % 2, len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
ISZERO
// stack: y == 0, len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
%jumpi(modexp_y_0)
// if y == 1, modular-multiply output_loc by scratch_1, using scratch_2..scratch_4 as scratch space, and store in scratch_5.
PUSH modexp_mul_return
DUP10
DUP10
DUP10
DUP14
DUP9
DUP12
DUP12
DUP9
// stack: len, out_loc, s1, m_loc, s5, s2, s3, s4, modexp_mul_return, len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
%jump(modmul_bignum)
modexp_mul_return:
// stack: len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
// Copy scratch_5 to output_loc.
DUP1
DUP11
DUP7
// stack: out_loc, s5, len, len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
%memcpy_kernel_general
// stack: len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
// Zero out scratch_2..scratch_5.
DUP1
%mul_const(8)
DUP8
// stack: s2, 8 * len, len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
%clear_kernel_general
// stack: len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
modexp_y_0:
// if y == 0, do nothing
// Modular-square repeated-squares accumulator x_i (in scratch_1), using scratch_2..scratch_4 as scratch space, and store in scratch_5.
PUSH modexp_square_return
DUP10
DUP10
DUP10
DUP14
DUP9
DUP12
DUP1
DUP9
// stack: len, s1, s1, m_loc, s5, s2, s3, s4, modexp_square_return, len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
%jump(modmul_bignum)
// stack: len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
modexp_square_return:
// Copy scratch_5 to scratch_1.
DUP1
DUP11
DUP8
// stack: s1, s5, len, len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
%memcpy_kernel_general
// stack: len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
// Zero out scratch_2..scratch_5.
DUP1
%mul_const(8)
DUP8
// stack: s2, 8 * len, len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
%clear_kernel_general
// stack: len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
// e //= 2 (with shr_bignum)
PUSH modexp_shr_return
DUP4
DUP3
// stack: len, e_loc, modexp_shr_return, len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
%jump(shr_bignum)
modexp_shr_return:
// stack: len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
// check if e == 0 (with iszero_bignum)
PUSH modexp_iszero_return
DUP4
DUP3
// stack: len, e_loc, modexp_iszero_return, len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
%jump(iszero_bignum)
modexp_iszero_return:
// stack: e == 0, len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
ISZERO
// stack: e != 0, len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
%jumpi(modexp_loop)
// end of modexp_loop
len_zero:
// stack: len, b_loc, e_loc, m_loc, out_loc, s1, s2, s3, s4, s5, retdest
%pop10
// stack: retdest
JUMP

View File

@ -0,0 +1,167 @@
// Arithmetic on little-endian integers represented with 128-bit limbs.
// All integers must be under a given length bound, and are padded with leading zeroes.
// Stores a * b % m in output_loc, leaving a, b, and m unchanged.
// a, b, and m must have the same length.
// output_loc must have size length; scratch_2 must have size 2*length.
// Both scratch_2 and scratch_3 have size 2*length and be initialized with zeroes.
// The prover provides x := (a * b) % m, which is the output of this function.
// We first check that x < m.
// The prover also provides k := (a * b) / m, stored in scratch space.
// We then check that x + k * m = a * b, by computing both of those using
// bignum arithmetic, storing the results in scratch space.
// We assert equality between those two, limb by limb.
global modmul_bignum:
// stack: len, a_loc, b_loc, m_loc, out_loc, s1 (=scratch_1), s2, s3, retdest
DUP1
ISZERO
%jumpi(len_zero)
// STEP 1:
// The prover provides x := (a * b) % m, which we store in output_loc.
PUSH 0
// stack: i=0, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
modmul_remainder_loop:
// stack: i, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
PROVER_INPUT(bignum_modmul)
// stack: PI, i, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
DUP7
DUP3
ADD
// stack: out_loc[i], PI, i, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
%mstore_kernel_general
// stack: i, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
%increment
DUP2
DUP2
// stack: i+1, len, i+1, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
SUB // functions as NEQ
// stack: i+1!=len, i+1, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
%jumpi(modmul_remainder_loop)
// end of modmul_remainder_loop
// stack: i, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
POP
// stack: len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
// STEP 2:
// We check that x < m.
PUSH modmul_return_1
DUP6
DUP6
DUP4
// stack: len, m_loc, out_loc, modmul_return_1, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
// Should return 1 iff the value at m_loc > the value at out_loc; in other words, if x < m.
%jump(cmp_bignum)
modmul_return_1:
// stack: cmp_result, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
PUSH 1
%assert_eq
// STEP 3:
// The prover provides k := (a * b) / m, which we store in scratch_1.
// stack: len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
DUP1
// stack: len, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
%mul_const(2)
// stack: 2*len, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
PUSH 0
// stack: i=0, 2*len, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
modmul_quotient_loop:
// stack: i, 2*len, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
PROVER_INPUT(bignum_modmul)
// stack: PI, i, 2*len, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
DUP9
DUP3
ADD
// stack: s1[i], PI, i, 2*len, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
%mstore_kernel_general
// stack: i, 2*len, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
%increment
DUP2
DUP2
// stack: i+1, 2*len, i+1, 2*len, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
SUB // functions as NEQ
// stack: i+1!=2*len, i+1, 2*len, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
%jumpi(modmul_quotient_loop)
// end of modmul_quotient_loop
// stack: i, 2*len, len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
%pop2
// stack: len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
// STEP 4:
// We calculate x + k * m.
// STEP 4.1:
// Multiply k with m and store k * m in scratch_2.
PUSH modmul_return_2
%stack (return, len, a, b, m, out, s1, s2) -> (len, s1, m, s2, return, len, a, b, out, s2)
// stack: len, s1, m_loc, s2, modmul_return_2, len, a_loc, b_loc, out_loc, s2, s3, retdest
%jump(mul_bignum)
modmul_return_2:
// stack: len, a_loc, b_loc, out_loc, s2, s3, retdest
// STEP 4.2:
// Add x into k * m (in scratch_2).
PUSH modmul_return_3
%stack (return, len, a, b, out, s2) -> (len, s2, out, return, len, a, b, s2)
// stack: len, s2, out_loc, modmul_return_3, len, a_loc, b_loc, s2, s3, retdest
%jump(add_bignum)
modmul_return_3:
// stack: carry, len, a_loc, b_loc, s2, s3, retdest
POP
// stack: len, a_loc, b_loc, s2, s3, retdest
// STEP 5:
// We calculate a * b.
// Multiply a with b and store a * b in scratch_3.
PUSH modmul_return_4
%stack (return, len, a, b, s2, s3) -> (len, a, b, s3, return, len, s2, s3)
// stack: len, a_loc, b_loc, s3, modmul_return_4, len, s2, s3, retdest
%jump(mul_bignum)
modmul_return_4:
// stack: len, s2, s3, retdest
// STEP 6:
// Check that x + k * m = a * b.
// Walk through scratch_2 and scratch_3, checking that they are equal.
// stack: n=len, i=s2, j=s3, retdest
modmul_check_loop:
// stack: n, i, j, retdest
%stack (l, idx: 2) -> (idx, l, idx)
// stack: i, j, n, i, j, retdest
%mload_kernel_general
SWAP1
%mload_kernel_general
SWAP1
// stack: mem[i], mem[j], n, i, j, retdest
%assert_eq
// stack: n, i, j, retdest
%decrement
SWAP1
%increment
SWAP2
%increment
SWAP2
SWAP1
// stack: n-1, i+1, j+1, retdest
DUP1
// stack: n-1, n-1, i+1, j+1, retdest
%jumpi(modmul_check_loop)
// end of modmul_check_loop
// stack: n-1, i+1, j+1, retdest
%pop3
// stack: retdest
JUMP
len_zero:
// stack: len, a_loc, b_loc, m_loc, out_loc, s1, s2, s3, retdest
%pop8
// stack: retdest
JUMP

View File

@ -57,6 +57,7 @@ mul_end:
%pop5
// stack: retdest
JUMP
len_zero:
// stack: len, a_start_loc, b_start_loc, output_loc, retdest
%pop4

View File

@ -60,6 +60,7 @@ shr_end:
%pop3
// stack: retdest
JUMP
len_zero:
// stack: len, start_loc, retdest
%pop2

View File

@ -12,18 +12,20 @@ global sys_call:
// stack: kexit_info, gas, address, value, args_offset, args_size, ret_offset, ret_size
%create_context
// stack: new_ctx, kexit_info, gas, address, value, args_offset, args_size, ret_offset, ret_size
// TODO: Consider call depth
// Each line in the block below does not change the stack.
DUP4 %set_new_ctx_addr
%address %set_new_ctx_caller
DUP5 %set_new_ctx_value
DUP5 DUP5 %address %transfer_eth
%set_new_ctx_parent_ctx
DUP5 DUP5 %address %transfer_eth %jumpi(panic) // TODO: Fix this panic.
%set_new_ctx_parent_pc(after_call_instruction)
DUP3 %set_new_ctx_gas_limit // TODO: This is not correct in most cases. Use C_callgas as in the YP.
DUP4 %set_new_ctx_code
// TODO: Copy memory[args_offset..args_offset + args_size] CALLDATA
// TODO: Set child gas
// TODO: Populate code and codesize field.
%stack (new_ctx, kexit_info, gas, address, value, args_offset, args_size, ret_offset, ret_size) ->
(new_ctx, args_offset, args_size, new_ctx, kexit_info, gas, address, value, args_offset, args_size, ret_offset, ret_size)
%copy_mem_to_calldata
// stack: new_ctx, kexit_info, gas, address, value, args_offset, args_size, ret_offset, ret_size
%stack (new_ctx, kexit_info, gas, address, value, args_offset, args_size, ret_offset, ret_size)
@ -48,8 +50,7 @@ global sys_callcode:
%address %set_new_ctx_addr
%address %set_new_ctx_caller
DUP5 %set_new_ctx_value
DUP5 DUP5 %address %transfer_eth
%set_new_ctx_parent_ctx
DUP5 DUP5 %address %transfer_eth %jumpi(panic) // TODO: Fix this panic.
%set_new_ctx_parent_pc(after_call_instruction)
// stack: new_ctx, kexit_info, gas, address, value, args_offset, args_size, ret_offset, ret_size
@ -79,7 +80,6 @@ global sys_staticcall:
DUP4 %set_new_ctx_addr
%address %set_new_ctx_caller
PUSH 0 %set_new_ctx_value
%set_new_ctx_parent_ctx
%set_new_ctx_parent_pc(after_call_instruction)
%stack (new_ctx, kexit_info, gas, address, args_offset, args_size, ret_offset, ret_size)
@ -105,7 +105,6 @@ global sys_delegatecall:
%address %set_new_ctx_addr
%caller %set_new_ctx_caller
%callvalue %set_new_ctx_value
%set_new_ctx_parent_ctx
%set_new_ctx_parent_pc(after_call_instruction)
%stack (new_ctx, kexit_info, gas, address, args_offset, args_size, ret_offset, ret_size)
@ -122,10 +121,7 @@ global after_call_instruction:
// stack: kexit_info, new_ctx, success, ret_offset, ret_size
// The callee's terminal instruction will have populated RETURNDATA.
// TODO: Copy RETURNDATA to memory[ret_offset..ret_offset + ret_size].
%stack (kexit_info, new_ctx, success, ret_offset, ret_size)
-> (kexit_info, success)
%copy_returndata_to_mem
EXIT_KERNEL
// Set @CTX_METADATA_STATIC to 1. Note that there is no corresponding set_static_false routine
@ -203,6 +199,16 @@ global after_call_instruction:
// stack: new_ctx
%endmacro
%macro set_new_ctx_code
%stack (address, new_ctx) -> (address, new_ctx, @SEGMENT_CODE, %%after, new_ctx)
%jump(load_code)
%%after:
%stack (code_size, new_ctx)
-> (new_ctx, @SEGMENT_CONTEXT_METADATA, @CTX_METADATA_CODE_SIZE, code_size, new_ctx)
MSTORE_GENERAL
// stack: new_ctx
%endmacro
%macro enter_new_ctx
// stack: new_ctx
// Switch to the new context and go to usermode with PC=0.
@ -212,3 +218,35 @@ global after_call_instruction:
EXIT_KERNEL
// (Old context) stack: new_ctx
%endmacro
%macro copy_mem_to_calldata
// stack: new_ctx, args_offset, args_size
GET_CONTEXT
%stack (ctx, new_ctx, args_offset, args_size) ->
(
new_ctx, @SEGMENT_CALLDATA, 0, // DST
ctx, @SEGMENT_MAIN_MEMORY, args_offset, // SRC
args_size, %%after, // count, retdest
new_ctx, args_size
)
%jump(memcpy)
%%after:
%stack (new_ctx, args_size) ->
(new_ctx, @SEGMENT_CONTEXT_METADATA, @CTX_METADATA_CALLDATA_SIZE, args_size)
MSTORE_GENERAL
// stack: (empty)
%endmacro
%macro copy_returndata_to_mem
// stack: kexit_info, new_ctx, success, ret_offset, ret_size
GET_CONTEXT
%stack (ctx, kexit_info, new_ctx, success, ret_offset, ret_size) ->
(
ctx, @SEGMENT_MAIN_MEMORY, ret_offset, // DST
ctx, @SEGMENT_RETURNDATA, 0, // SRC
ret_size, %%after, // count, retdest
kexit_info, success
)
%jump(memcpy)
%%after:
%endmacro

View File

@ -87,13 +87,12 @@ global create_common:
run_constructor:
// stack: new_ctx, value, address, kexit_info
%set_new_ctx_value
SWAP1 %set_new_ctx_value
// stack: new_ctx, address, kexit_info
// Each line in the block below does not change the stack.
DUP2 %set_new_ctx_addr
%address %set_new_ctx_caller
%set_new_ctx_parent_ctx
%set_new_ctx_parent_pc(after_constructor)
// stack: new_ctx, address, kexit_info

View File

@ -3,21 +3,44 @@
global sys_stop:
// stack: kexit_info
// Set the parent context's return data size to 0.
%mstore_parent_context_metadata(@CTX_METADATA_RETURNDATA_SIZE, 0)
%leftover_gas
// stack: leftover_gas
// TODO: Set parent context's CTX_METADATA_RETURNDATA_SIZE to 0.
PUSH 1 // success
%jump(terminate_common)
global sys_return:
// stack: kexit_info, offset, size
// TODO: For now we're ignoring the returned data. Need to return it to the parent context.
%stack (kexit_info, offset, size) -> (kexit_info)
%stack (kexit_info, offset, size) -> (offset, size, kexit_info, offset, size)
ADD // TODO: Check for overflow?
DUP1 %ensure_reasonable_offset
%update_mem_bytes
// Load the parent's context.
%mload_context_metadata(@CTX_METADATA_PARENT_CONTEXT)
// Store the return data size in the parent context's metadata.
%stack (parent_ctx, kexit_info, offset, size) ->
(parent_ctx, @SEGMENT_CONTEXT_METADATA, @CTX_METADATA_RETURNDATA_SIZE, size, offset, size, parent_ctx, kexit_info)
MSTORE_GENERAL
// stack: offset, size, parent_ctx, kexit_info
// Store the return data in the parent context's returndata segment.
GET_CONTEXT
%stack (ctx, offset, size, parent_ctx, kexit_info) ->
(
parent_ctx, @SEGMENT_RETURNDATA, 0, // DST
ctx, @SEGMENT_MAIN_MEMORY, offset, // SRC
size, sys_return_finish, kexit_info // count, retdest, ...
)
%jump(memcpy)
sys_return_finish:
// stack: kexit_info
%leftover_gas
// stack: leftover_gas
// TODO: Set parent context's CTX_METADATA_RETURNDATA_SIZE.
// TODO: Copy returned memory to parent context's RETURNDATA.
PUSH 1 // success
%jump(terminate_common)
@ -30,6 +53,9 @@ global sys_selfdestruct:
// stack: balance, address, recipient, kexit_info
DUP3 %insert_accessed_addresses
// Set the parent context's return data size to 0.
%mstore_parent_context_metadata(@CTX_METADATA_RETURNDATA_SIZE, 0)
// Compute gas.
// stack: cold_access, balance, address, recipient, kexit_info
%mul_const(@GAS_COLDACCOUNTACCESS)
@ -81,14 +107,34 @@ sys_selfdestruct_same_addr:
global sys_revert:
// stack: kexit_info, offset, size
// TODO: For now we're ignoring the returned data. Need to return it to the parent context.
%stack (kexit_info, offset, size) -> (kexit_info)
%stack (kexit_info, offset, size) -> (offset, size, kexit_info, offset, size)
ADD // TODO: Check for overflow?
DUP1 %ensure_reasonable_offset
%update_mem_bytes
// Load the parent's context.
%mload_context_metadata(@CTX_METADATA_PARENT_CONTEXT)
// Store the return data size in the parent context's metadata.
%stack (parent_ctx, kexit_info, offset, size) ->
(parent_ctx, @SEGMENT_CONTEXT_METADATA, @CTX_METADATA_RETURNDATA_SIZE, size, offset, size, parent_ctx, kexit_info)
MSTORE_GENERAL
// stack: offset, size, parent_ctx, kexit_info
// Store the return data in the parent context's returndata segment.
GET_CONTEXT
%stack (ctx, offset, size, parent_ctx, kexit_info) ->
(
parent_ctx, @SEGMENT_RETURNDATA, 0, // DST
ctx, @SEGMENT_MAIN_MEMORY, offset, // SRC
size, sys_revert_finish, kexit_info // count, retdest, ...
)
%jump(memcpy)
sys_revert_finish:
%leftover_gas
// stack: leftover_gas
// TODO: Revert state changes.
// TODO: Set parent context's CTX_METADATA_RETURNDATA_SIZE.
// TODO: Copy returned memory to parent context's RETURNDATA.
PUSH 0 // success
%jump(terminate_common)
@ -103,7 +149,8 @@ global fault_exception:
// stack: (empty)
PUSH 0 // leftover_gas
// TODO: Revert state changes.
// TODO: Set parent context's CTX_METADATA_RETURNDATA_SIZE to 0.
// Set the parent context's return data size to 0.
%mstore_parent_context_metadata(@CTX_METADATA_RETURNDATA_SIZE, 0)
PUSH 0 // success
%jump(terminate_common)

View File

@ -1,13 +1,10 @@
// Return the next context ID, and record the old context ID in the new one's
// @CTX_METADATA_PARENT_CONTEXT field. Does not actually enter the new context.
%macro create_context
// stack: (empty)
%next_context_id
GET_CONTEXT
%stack (ctx, next_ctx)
-> (next_ctx, @SEGMENT_NORMALIZED_TXN, @CTX_METADATA_PARENT_CONTEXT,
ctx, next_ctx)
MSTORE_GENERAL
// stack: next_ctx
%set_new_ctx_parent_ctx
// stack: new_ctx
%endmacro
// Get and increment @GLOBAL_METADATA_LARGEST_CONTEXT to determine the next context ID.

View File

@ -73,7 +73,7 @@ recursion_return:
jump
global sys_exp:
// stack: x, e, return_info
%stack (return_info, x, e) -> (x, e, return_info)
push 0
// stack: shift, x, e, return_info
%jump(sys_exp_gas_loop_enter)
@ -95,7 +95,7 @@ sys_exp_gas_loop_enter:
%charge_gas
%stack(return_info, x, e) -> (x, e, sys_exp_return, return_info)
jump exp
%jump(exp)
sys_exp_return:
// stack: pow(x, e), return_info
swap1

View File

@ -34,6 +34,24 @@
// stack: (empty)
%endmacro
%macro mstore_parent_context_metadata(field)
// stack: value
%mload_context_metadata(@CTX_METADATA_PARENT_CONTEXT)
%stack (parent_ctx, value) ->
(parent_ctx, @SEGMENT_CONTEXT_METADATA, $field, value)
MSTORE_GENERAL
// stack: (empty)
%endmacro
%macro mstore_parent_context_metadata(field, value)
// stack: (empty)
%mload_context_metadata(@CTX_METADATA_PARENT_CONTEXT)
%stack (parent_ctx) ->
(parent_ctx, @SEGMENT_CONTEXT_METADATA, $field, $value)
MSTORE_GENERAL
// stack: (empty)
%endmacro
%macro address
%mload_context_metadata(@CTX_METADATA_ADDRESS)
%endmacro

View File

@ -121,7 +121,7 @@ sys_calldataload_after_mload_packing:
PANIC
// Macro for {CALLDATA,CODE,RETURNDATA}COPY (W_copy in Yellow Paper).
%macro wcopy(segment)
%macro wcopy(segment, context_metadata_size)
// stack: kexit_info, dest_offset, offset, size
PUSH @GAS_VERYLOW
DUP5
@ -136,25 +136,41 @@ sys_calldataload_after_mload_packing:
DUP1 %ensure_reasonable_offset
%update_mem_bytes
%mload_context_metadata($context_metadata_size)
// stack: total_size, kexit_info, dest_offset, offset, size
DUP4
// stack: offset, total_size, kexit_info, dest_offset, offset, size
GT %jumpi(%%wcopy_large_offset)
GET_CONTEXT
%stack (context, kexit_info, dest_offset, offset, size) ->
(context, @SEGMENT_MAIN_MEMORY, dest_offset, context, $segment, offset, size, %%after, kexit_info)
%jump(memcpy)
%%after:
// stack: kexit_info
EXIT_KERNEL
%%wcopy_empty:
// stack: Gverylow, kexit_info, dest_offset, offset, size
%charge_gas
%stack (kexit_info, dest_offset, offset, size) -> (kexit_info)
EXIT_KERNEL
%%wcopy_large_offset:
// offset is larger than the size of the {CALLDATA,CODE,RETURNDATA}. So we just have to write zeros.
// stack: kexit_info, dest_offset, offset, size
GET_CONTEXT
%stack (context, kexit_info, dest_offset, offset, size) ->
(context, @SEGMENT_MAIN_MEMORY, dest_offset, 0, size, %%after, kexit_info)
%jump(memset)
%endmacro
global sys_calldatacopy:
%wcopy(@SEGMENT_CALLDATA)
%wcopy(@SEGMENT_CALLDATA, @CTX_METADATA_CALLDATA_SIZE)
global sys_codecopy:
%wcopy(@SEGMENT_CODE)
%wcopy(@SEGMENT_CODE, @CTX_METADATA_CODE_SIZE)
global sys_returndatacopy:
%wcopy(@SEGMENT_RETURNDATA)
%wcopy(@SEGMENT_RETURNDATA, @CTX_METADATA_RETURNDATA_SIZE)

View File

@ -19,7 +19,7 @@ global mpt_hash_storage_trie:
%jump(mpt_hash)
%macro mpt_hash_storage_trie
PUSH %%after
%stack (node_ptr) -> (node_ptr, %%after)
%jump(mpt_hash_storage_trie)
%%after:
%endmacro
@ -83,12 +83,9 @@ global encode_account:
// stack: balance, rlp_pos_4, value_ptr, retdest
SWAP1 %encode_rlp_scalar
// stack: rlp_pos_5, value_ptr, retdest
PUSH encode_account_after_hash_storage_trie
PUSH encode_storage_value
DUP4 %add_const(2) %mload_trie_data // storage_root_ptr = value[2]
// stack: storage_root_ptr, encode_storage_value, encode_account_after_hash_storage_trie, rlp_pos_5, value_ptr, retdest
%jump(mpt_hash)
encode_account_after_hash_storage_trie:
DUP2 %add_const(2) %mload_trie_data // storage_root_ptr = value[2]
// stack: storage_root_ptr, rlp_pos_5, value_ptr, retdest
%mpt_hash_storage_trie
// stack: storage_root_digest, rlp_pos_5, value_ptr, retdest
SWAP1 %encode_rlp_256
// stack: rlp_pos_6, value_ptr, retdest
@ -113,7 +110,7 @@ global encode_storage_value:
// which seems to imply that this should be %encode_rlp_256. But %encode_rlp_scalar
// causes the tests to pass, so it seems storage values should be treated as variable-
// length after all.
%encode_rlp_scalar
%doubly_encode_rlp_scalar
// stack: rlp_pos', retdest
SWAP1
JUMP

View File

@ -1,55 +1,3 @@
// RLP-encode a scalar, i.e. a variable-length integer.
// Pre stack: pos, scalar, retdest
// Post stack: pos
global encode_rlp_scalar:
// stack: pos, scalar, retdest
// If scalar > 0x7f, this is the "medium" case.
DUP2
%gt_const(0x7f)
%jumpi(encode_rlp_scalar_medium)
// Else, if scalar != 0, this is the "small" case, where the value is its own encoding.
DUP2 %jumpi(encode_rlp_scalar_small)
// scalar = 0, so BE(scalar) is the empty string, which RLP encodes as a single byte 0x80.
// stack: pos, scalar, retdest
%stack (pos, scalar) -> (pos, 0x80, pos)
%mstore_rlp
// stack: pos, retdest
%increment
// stack: pos', retdest
SWAP1
JUMP
encode_rlp_scalar_small:
// stack: pos, scalar, retdest
%stack (pos, scalar) -> (pos, scalar, pos)
// stack: pos, scalar, pos, retdest
%mstore_rlp
// stack: pos, retdest
%increment
// stack: pos', retdest
SWAP1
JUMP
encode_rlp_scalar_medium:
// This is the "medium" case, where we write 0x80 + len followed by the
// (big-endian) scalar bytes. We first compute the minimal number of bytes
// needed to represent this scalar, then treat it as if it was a fixed-
// length string with that length.
// stack: pos, scalar, retdest
DUP2
%num_bytes
// stack: scalar_bytes, pos, scalar, retdest
%jump(encode_rlp_fixed)
// Convenience macro to call encode_rlp_scalar and return where we left off.
%macro encode_rlp_scalar
%stack (pos, scalar) -> (pos, scalar, %%after)
%jump(encode_rlp_scalar)
%%after:
%endmacro
// RLP-encode a fixed-length 160 bit (20 byte) string. Assumes string < 2^160.
// Pre stack: pos, string, retdest
// Post stack: pos
@ -79,7 +27,7 @@ global encode_rlp_256:
%endmacro
// RLP-encode a fixed-length string with the given byte length. Assumes string < 2^(8 * len).
encode_rlp_fixed:
global encode_rlp_fixed:
// stack: len, pos, string, retdest
DUP1
%add_const(0x80)
@ -99,6 +47,31 @@ encode_rlp_fixed_finish:
SWAP1
JUMP
// Doubly-RLP-encode a fixed-length string with the given byte length.
// I.e. writes encode(encode(string). Assumes string < 2^(8 * len).
global doubly_encode_rlp_fixed:
// stack: len, pos, string, retdest
DUP1
%add_const(0x81)
// stack: first_byte, len, pos, string, retdest
DUP3
// stack: pos, first_byte, len, pos, string, retdest
%mstore_rlp
// stack: len, pos, string, retdest
DUP1
%add_const(0x80)
// stack: second_byte, len, original_pos, string, retdest
DUP3 %increment
// stack: pos', second_byte, len, pos, string, retdest
%mstore_rlp
// stack: len, pos, string, retdest
SWAP1
%add_const(2) // advance past the two prefix bytes
// stack: pos'', len, string, retdest
%stack (pos, len, string) -> (pos, string, len, encode_rlp_fixed_finish)
// stack: context, segment, pos'', string, len, encode_rlp_fixed_finish, retdest
%jump(mstore_unpacking_rlp)
// Writes the RLP prefix for a string of the given length. This does not handle
// the trivial encoding of certain single-byte strings, as handling that would
// require access to the actual string, while this method only accesses its

View File

@ -0,0 +1,99 @@
// RLP-encode a scalar, i.e. a variable-length integer.
// Pre stack: pos, scalar, retdest
// Post stack: pos
global encode_rlp_scalar:
// stack: pos, scalar, retdest
// If scalar > 0x7f, this is the "medium" case.
DUP2
%gt_const(0x7f)
%jumpi(encode_rlp_scalar_medium)
// Else, if scalar != 0, this is the "small" case, where the value is its own encoding.
DUP2 %jumpi(encode_rlp_scalar_small)
// scalar = 0, so BE(scalar) is the empty string, which RLP encodes as a single byte 0x80.
// stack: pos, scalar, retdest
%stack (pos, scalar) -> (pos, 0x80, pos)
%mstore_rlp
// stack: pos, retdest
%increment
// stack: pos', retdest
SWAP1
JUMP
encode_rlp_scalar_medium:
// This is the "medium" case, where we write 0x80 + len followed by the
// (big-endian) scalar bytes. We first compute the minimal number of bytes
// needed to represent this scalar, then treat it as if it was a fixed-
// length string with that length.
// stack: pos, scalar, retdest
DUP2
%num_bytes
// stack: scalar_bytes, pos, scalar, retdest
%jump(encode_rlp_fixed)
// Doubly-RLP-encode a scalar, i.e. return encode(encode(scalar)).
// Pre stack: pos, scalar, retdest
// Post stack: pos
global doubly_encode_rlp_scalar:
// stack: pos, scalar, retdest
// If scalar > 0x7f, this is the "medium" case.
DUP2
%gt_const(0x7f)
%jumpi(doubly_encode_rlp_scalar_medium)
// Else, if scalar != 0, this is the "small" case, where the value is its own encoding.
DUP2 %jumpi(encode_rlp_scalar_small)
// scalar = 0, so BE(scalar) is the empty string, encode(scalar) = 0x80, and encode(encode(scalar)) = 0x8180.
// stack: pos, scalar, retdest
%stack (pos, scalar) -> (pos, 0x81, pos, 0x80, pos)
%mstore_rlp
// stack: pos, 0x80, pos, retdest
%increment
%mstore_rlp
// stack: pos, retdest
%increment
// stack: pos, retdest
SWAP1
JUMP
doubly_encode_rlp_scalar_medium:
// This is the "medium" case, where
// encode(scalar) = [0x80 + len] || BE(scalar)
// and so
// encode(encode(scalar)) = [0x80 + len + 1] || [0x80 + len] || BE(scalar)
// We first compute the length of the scalar with %num_bytes, then treat the scalar as if it was a
// fixed-length string with that length.
// stack: pos, scalar, retdest
DUP2
%num_bytes
// stack: scalar_bytes, pos, scalar, retdest
%jump(doubly_encode_rlp_fixed)
// The "small" case of RLP-encoding a scalar, where the value is its own encoding.
// This can be used for both for singly encoding or doubly encoding, since encode(encode(x)) = encode(x) = x.
encode_rlp_scalar_small:
// stack: pos, scalar, retdest
%stack (pos, scalar) -> (pos, scalar, pos)
// stack: pos, scalar, pos, retdest
%mstore_rlp
// stack: pos, retdest
%increment
// stack: pos', retdest
SWAP1
JUMP
// Convenience macro to call encode_rlp_scalar and return where we left off.
%macro encode_rlp_scalar
%stack (pos, scalar) -> (pos, scalar, %%after)
%jump(encode_rlp_scalar)
%%after:
%endmacro
// Convenience macro to call doubly_encode_rlp_scalar and return where we left off.
%macro doubly_encode_rlp_scalar
%stack (pos, scalar) -> (pos, scalar, %%after)
%jump(doubly_encode_rlp_scalar)
%%after:
%endmacro

View File

@ -50,6 +50,18 @@
%endrep
%endmacro
%macro pop9
%rep 9
POP
%endrep
%endmacro
%macro pop10
%rep 10
POP
%endrep
%endmacro
%macro and_const(c)
// stack: input, ...
PUSH $c

View File

@ -348,13 +348,13 @@ impl<'a> Interpreter<'a> {
0x3e => todo!(), // "RETURNDATACOPY",
0x3f => todo!(), // "EXTCODEHASH",
0x40 => todo!(), // "BLOCKHASH",
0x41 => todo!(), // "COINBASE",
0x42 => todo!(), // "TIMESTAMP",
0x43 => todo!(), // "NUMBER",
0x44 => todo!(), // "DIFFICULTY",
0x45 => todo!(), // "GASLIMIT",
0x46 => todo!(), // "CHAINID",
0x48 => todo!(), // "BASEFEE",
0x41 => self.run_coinbase(), // "COINBASE",
0x42 => self.run_timestamp(), // "TIMESTAMP",
0x43 => self.run_number(), // "NUMBER",
0x44 => self.run_difficulty(), // "DIFFICULTY",
0x45 => self.run_gaslimit(), // "GASLIMIT",
0x46 => self.run_chainid(), // "CHAINID",
0x48 => self.run_basefee(), // "BASEFEE",
0x49 => self.run_prover_input()?, // "PROVER_INPUT",
0x50 => self.run_pop(), // "POP",
0x51 => self.run_mload(), // "MLOAD",
@ -376,7 +376,11 @@ impl<'a> Interpreter<'a> {
0xa2 => todo!(), // "LOG2",
0xa3 => todo!(), // "LOG3",
0xa4 => todo!(), // "LOG4",
0xa5 => bail!("Executed PANIC, stack={:?}", self.stack()), // "PANIC",
0xa5 => bail!(
"Executed PANIC, stack={:?}, memory={:?}",
self.stack(),
self.get_kernel_general_memory()
), // "PANIC",
0xf0 => todo!(), // "CREATE",
0xf1 => todo!(), // "CALL",
0xf2 => todo!(), // "CALLCODE",
@ -655,6 +659,34 @@ impl<'a> Interpreter<'a> {
}
}
fn run_coinbase(&mut self) {
self.push(self.get_global_metadata_field(GlobalMetadata::BlockBeneficiary))
}
fn run_timestamp(&mut self) {
self.push(self.get_global_metadata_field(GlobalMetadata::BlockTimestamp))
}
fn run_number(&mut self) {
self.push(self.get_global_metadata_field(GlobalMetadata::BlockNumber))
}
fn run_difficulty(&mut self) {
self.push(self.get_global_metadata_field(GlobalMetadata::BlockDifficulty))
}
fn run_gaslimit(&mut self) {
self.push(self.get_global_metadata_field(GlobalMetadata::BlockGasLimit))
}
fn run_basefee(&mut self) {
self.push(self.get_global_metadata_field(GlobalMetadata::BlockBaseFee))
}
fn run_chainid(&mut self) {
self.push(self.get_global_metadata_field(GlobalMetadata::BlockChainId))
}
fn run_prover_input(&mut self) -> anyhow::Result<()> {
let prover_input_fn = self
.prover_inputs_map

View File

@ -32,24 +32,28 @@ pub(crate) fn keccakf_u8s(state_u8s: &mut [u8; KECCAK_WIDTH_BYTES]) {
mod tests {
use tiny_keccak::keccakf;
use crate::cpu::kernel::keccak_util::keccakf_u32s;
use crate::cpu::kernel::keccak_util::{keccakf_u32s, keccakf_u8s};
#[test]
#[rustfmt::skip]
fn test_consistency() {
// We will hash the same data using keccakf and keccakf_u32s.
// We will hash the same data using keccakf, keccakf_u32s and keccakf_u8s.
// The inputs were randomly generated in Python.
let mut state_u64s: [u64; 25] = [0x5dc43ed05dc64048, 0x7bb9e18cdc853880, 0xc1fde300665b008f, 0xeeab85e089d5e431, 0xf7d61298e9ef27ea, 0xc2c5149d1a492455, 0x37a2f4eca0c2d2f2, 0xa35e50c015b3e85c, 0xd2daeced29446ebe, 0x245845f1bac1b98e, 0x3b3aa8783f30a9bf, 0x209ca9a81956d241, 0x8b8ea714da382165, 0x6063e67e202c6d29, 0xf4bac2ded136b907, 0xb17301b461eae65, 0xa91ff0e134ed747c, 0xcc080b28d0c20f1d, 0xf0f79cbec4fb551c, 0x25e04cb0aa930cad, 0x803113d1b541a202, 0xfaf1e4e7cd23b7ec, 0x36a03bbf2469d3b0, 0x25217341908cdfc0, 0xe9cd83f88fdcd500];
let mut state_u32s: [u32; 50] = [0x5dc64048, 0x5dc43ed0, 0xdc853880, 0x7bb9e18c, 0x665b008f, 0xc1fde300, 0x89d5e431, 0xeeab85e0, 0xe9ef27ea, 0xf7d61298, 0x1a492455, 0xc2c5149d, 0xa0c2d2f2, 0x37a2f4ec, 0x15b3e85c, 0xa35e50c0, 0x29446ebe, 0xd2daeced, 0xbac1b98e, 0x245845f1, 0x3f30a9bf, 0x3b3aa878, 0x1956d241, 0x209ca9a8, 0xda382165, 0x8b8ea714, 0x202c6d29, 0x6063e67e, 0xd136b907, 0xf4bac2de, 0x461eae65, 0xb17301b, 0x34ed747c, 0xa91ff0e1, 0xd0c20f1d, 0xcc080b28, 0xc4fb551c, 0xf0f79cbe, 0xaa930cad, 0x25e04cb0, 0xb541a202, 0x803113d1, 0xcd23b7ec, 0xfaf1e4e7, 0x2469d3b0, 0x36a03bbf, 0x908cdfc0, 0x25217341, 0x8fdcd500, 0xe9cd83f8];
let mut state_u8s: [u8; 200] = [0x48, 0x40, 0xc6, 0x5d, 0xd0, 0x3e, 0xc4, 0x5d, 0x80, 0x38, 0x85, 0xdc, 0x8c, 0xe1, 0xb9, 0x7b, 0x8f, 0x0, 0x5b, 0x66, 0x0, 0xe3, 0xfd, 0xc1, 0x31, 0xe4, 0xd5, 0x89, 0xe0, 0x85, 0xab, 0xee, 0xea, 0x27, 0xef, 0xe9, 0x98, 0x12, 0xd6, 0xf7, 0x55, 0x24, 0x49, 0x1a, 0x9d, 0x14, 0xc5, 0xc2, 0xf2, 0xd2, 0xc2, 0xa0, 0xec, 0xf4, 0xa2, 0x37, 0x5c, 0xe8, 0xb3, 0x15, 0xc0, 0x50, 0x5e, 0xa3, 0xbe, 0x6e, 0x44, 0x29, 0xed, 0xec, 0xda, 0xd2, 0x8e, 0xb9, 0xc1, 0xba, 0xf1, 0x45, 0x58, 0x24, 0xbf, 0xa9, 0x30, 0x3f, 0x78, 0xa8, 0x3a, 0x3b, 0x41, 0xd2, 0x56, 0x19, 0xa8, 0xa9, 0x9c, 0x20, 0x65, 0x21, 0x38, 0xda, 0x14, 0xa7, 0x8e, 0x8b, 0x29, 0x6d, 0x2c, 0x20, 0x7e, 0xe6, 0x63, 0x60, 0x7, 0xb9, 0x36, 0xd1, 0xde, 0xc2, 0xba, 0xf4, 0x65, 0xae, 0x1e, 0x46, 0x1b, 0x30, 0x17, 0xb, 0x7c, 0x74, 0xed, 0x34, 0xe1, 0xf0, 0x1f, 0xa9, 0x1d, 0xf, 0xc2, 0xd0, 0x28, 0xb, 0x8, 0xcc, 0x1c, 0x55, 0xfb, 0xc4, 0xbe, 0x9c, 0xf7, 0xf0, 0xad, 0xc, 0x93, 0xaa, 0xb0, 0x4c, 0xe0, 0x25, 0x2, 0xa2, 0x41, 0xb5, 0xd1, 0x13, 0x31, 0x80, 0xec, 0xb7, 0x23, 0xcd, 0xe7, 0xe4, 0xf1, 0xfa, 0xb0, 0xd3, 0x69, 0x24, 0xbf, 0x3b, 0xa0, 0x36, 0xc0, 0xdf, 0x8c, 0x90, 0x41, 0x73, 0x21, 0x25, 0x0, 0xd5, 0xdc, 0x8f, 0xf8, 0x83, 0xcd, 0xe9];
// The first output was generated using tiny-keccak; the second was derived from it.
// The first output was generated using tiny-keccak; the others were derived from it.
let out_u64s: [u64; 25] = [0x8a541df597e79a72, 0x5c26b8c84faaebb3, 0xc0e8f4e67ca50497, 0x95d98a688de12dec, 0x1c837163975ffaed, 0x9481ec7ef948900e, 0x6a072c65d050a9a1, 0x3b2817da6d615bee, 0x7ffb3c4f8b94bf21, 0x85d6c418cced4a11, 0x18edbe0442884135, 0x2bf265ef3204b7fd, 0xc1e12ce30630d105, 0x8c554dbc61844574, 0x5504db652ce9e42c, 0x2217f3294d0dabe5, 0x7df8eebbcf5b74df, 0x3a56ebb61956f501, 0x7840219dc6f37cc, 0x23194159c967947, 0x9da289bf616ba14d, 0x5a90aaeeca9e9e5b, 0x885dcdc4a549b4e3, 0x46cb188c20947df7, 0x1ef285948ee3d8ab];
let out_u32s: [u32; 50] = [0x97e79a72, 0x8a541df5, 0x4faaebb3, 0x5c26b8c8, 0x7ca50497, 0xc0e8f4e6, 0x8de12dec, 0x95d98a68, 0x975ffaed, 0x1c837163, 0xf948900e, 0x9481ec7e, 0xd050a9a1, 0x6a072c65, 0x6d615bee, 0x3b2817da, 0x8b94bf21, 0x7ffb3c4f, 0xcced4a11, 0x85d6c418, 0x42884135, 0x18edbe04, 0x3204b7fd, 0x2bf265ef, 0x630d105, 0xc1e12ce3, 0x61844574, 0x8c554dbc, 0x2ce9e42c, 0x5504db65, 0x4d0dabe5, 0x2217f329, 0xcf5b74df, 0x7df8eebb, 0x1956f501, 0x3a56ebb6, 0xdc6f37cc, 0x7840219, 0x9c967947, 0x2319415, 0x616ba14d, 0x9da289bf, 0xca9e9e5b, 0x5a90aaee, 0xa549b4e3, 0x885dcdc4, 0x20947df7, 0x46cb188c, 0x8ee3d8ab, 0x1ef28594];
let out_u8s: [u8; 200] = [0x72, 0x9a, 0xe7, 0x97, 0xf5, 0x1d, 0x54, 0x8a, 0xb3, 0xeb, 0xaa, 0x4f, 0xc8, 0xb8, 0x26, 0x5c, 0x97, 0x4, 0xa5, 0x7c, 0xe6, 0xf4, 0xe8, 0xc0, 0xec, 0x2d, 0xe1, 0x8d, 0x68, 0x8a, 0xd9, 0x95, 0xed, 0xfa, 0x5f, 0x97, 0x63, 0x71, 0x83, 0x1c, 0xe, 0x90, 0x48, 0xf9, 0x7e, 0xec, 0x81, 0x94, 0xa1, 0xa9, 0x50, 0xd0, 0x65, 0x2c, 0x7, 0x6a, 0xee, 0x5b, 0x61, 0x6d, 0xda, 0x17, 0x28, 0x3b, 0x21, 0xbf, 0x94, 0x8b, 0x4f, 0x3c, 0xfb, 0x7f, 0x11, 0x4a, 0xed, 0xcc, 0x18, 0xc4, 0xd6, 0x85, 0x35, 0x41, 0x88, 0x42, 0x4, 0xbe, 0xed, 0x18, 0xfd, 0xb7, 0x4, 0x32, 0xef, 0x65, 0xf2, 0x2b, 0x5, 0xd1, 0x30, 0x6, 0xe3, 0x2c, 0xe1, 0xc1, 0x74, 0x45, 0x84, 0x61, 0xbc, 0x4d, 0x55, 0x8c, 0x2c, 0xe4, 0xe9, 0x2c, 0x65, 0xdb, 0x4, 0x55, 0xe5, 0xab, 0xd, 0x4d, 0x29, 0xf3, 0x17, 0x22, 0xdf, 0x74, 0x5b, 0xcf, 0xbb, 0xee, 0xf8, 0x7d, 0x1, 0xf5, 0x56, 0x19, 0xb6, 0xeb, 0x56, 0x3a, 0xcc, 0x37, 0x6f, 0xdc, 0x19, 0x2, 0x84, 0x7, 0x47, 0x79, 0x96, 0x9c, 0x15, 0x94, 0x31, 0x2, 0x4d, 0xa1, 0x6b, 0x61, 0xbf, 0x89, 0xa2, 0x9d, 0x5b, 0x9e, 0x9e, 0xca, 0xee, 0xaa, 0x90, 0x5a, 0xe3, 0xb4, 0x49, 0xa5, 0xc4, 0xcd, 0x5d, 0x88, 0xf7, 0x7d, 0x94, 0x20, 0x8c, 0x18, 0xcb, 0x46, 0xab, 0xd8, 0xe3, 0x8e, 0x94, 0x85, 0xf2, 0x1e];
keccakf(&mut state_u64s);
keccakf_u32s(&mut state_u32s);
keccakf_u8s(&mut state_u8s);
assert_eq!(state_u64s, out_u64s);
assert_eq!(state_u32s, out_u32s);
assert_eq!(state_u8s, out_u8s);
}
}

View File

@ -20,12 +20,15 @@ const MINUS_ONE: U256 = U256::MAX;
const TEST_DATA_BIGNUM_INPUTS: &str = "bignum_inputs";
const TEST_DATA_U128_INPUTS: &str = "u128_inputs";
const TEST_DATA_SHR_OUTPUTS: &str = "shr_outputs";
const TEST_DATA_ISZERO_OUTPUTS: &str = "iszero_outputs";
const TEST_DATA_CMP_OUTPUTS: &str = "cmp_outputs";
const TEST_DATA_ADD_OUTPUTS: &str = "add_outputs";
const TEST_DATA_ADDMUL_OUTPUTS: &str = "addmul_outputs";
const TEST_DATA_MUL_OUTPUTS: &str = "mul_outputs";
const TEST_DATA_MODMUL_OUTPUTS: &str = "modmul_outputs";
const TEST_DATA_MODEXP_OUTPUTS: &str = "modexp_outputs";
const BIT_SIZES_TO_TEST: [usize; 15] = [
0, 1, 2, 127, 128, 129, 255, 256, 257, 512, 1000, 1023, 1024, 1025, 31415,
@ -232,6 +235,76 @@ fn test_mul_bignum(a: BigUint, b: BigUint, expected_output: BigUint) -> Result<(
Ok(())
}
fn test_modmul_bignum(a: BigUint, b: BigUint, m: BigUint, expected_output: BigUint) -> Result<()> {
let len = bignum_len(&a).max(bignum_len(&b)).max(bignum_len(&m));
let output_len = len;
let memory = pad_bignums(&[a, b, m], len);
let a_start_loc = 0;
let b_start_loc = len;
let m_start_loc = 2 * len;
let output_start_loc = 3 * len;
let scratch_1 = 4 * len; // size 2*len
let scratch_2 = 6 * len; // size 2*len
let scratch_3 = 8 * len; // size 2*len
let (new_memory, _new_stack) = run_test(
"modmul_bignum",
memory,
vec![
len.into(),
a_start_loc.into(),
b_start_loc.into(),
m_start_loc.into(),
output_start_loc.into(),
scratch_1.into(),
scratch_2.into(),
scratch_3.into(),
],
)?;
let output = mem_vec_to_biguint(&new_memory[output_start_loc..output_start_loc + output_len]);
assert_eq!(output, expected_output);
Ok(())
}
fn test_modexp_bignum(b: BigUint, e: BigUint, m: BigUint, expected_output: BigUint) -> Result<()> {
let len = bignum_len(&b).max(bignum_len(&e)).max(bignum_len(&m));
let output_len = len;
let memory = pad_bignums(&[b, e, m], len);
let b_start_loc = 0;
let e_start_loc = len;
let m_start_loc = 2 * len;
let output_start_loc = 3 * len;
let scratch_1 = 4 * len;
let scratch_2 = 5 * len; // size 2*len
let scratch_3 = 7 * len; // size 2*len
let scratch_4 = 9 * len; // size 2*len
let scratch_5 = 11 * len; // size 2*len
let (new_memory, _new_stack) = run_test(
"modexp_bignum",
memory,
vec![
len.into(),
b_start_loc.into(),
e_start_loc.into(),
m_start_loc.into(),
output_start_loc.into(),
scratch_1.into(),
scratch_2.into(),
scratch_3.into(),
scratch_4.into(),
scratch_5.into(),
],
)?;
let output = mem_vec_to_biguint(&new_memory[output_start_loc..output_start_loc + output_len]);
assert_eq!(output, expected_output);
Ok(())
}
#[test]
fn test_shr_bignum_all() -> Result<()> {
for bit_size in BIT_SIZES_TO_TEST {
@ -394,3 +467,81 @@ fn test_mul_bignum_all() -> Result<()> {
Ok(())
}
#[test]
fn test_modmul_bignum_all() -> Result<()> {
for bit_size in BIT_SIZES_TO_TEST {
let a = gen_bignum(bit_size);
let b = gen_bignum(bit_size);
let m = gen_bignum(bit_size);
if !m.is_zero() {
let output = &a * &b % &m;
test_modmul_bignum(a, b, m, output)?;
}
let a = max_bignum(bit_size);
let b = max_bignum(bit_size);
let m = max_bignum(bit_size);
if !m.is_zero() {
let output = &a * &b % &m;
test_modmul_bignum(a, b, m, output)?;
}
}
let inputs = test_data_biguint(TEST_DATA_BIGNUM_INPUTS);
let modmul_outputs = test_data_biguint(TEST_DATA_MODMUL_OUTPUTS);
let mut modmul_outputs_iter = modmul_outputs.into_iter();
for a in &inputs {
for b in &inputs {
// For m, skip the first input, which is zero.
for m in &inputs[1..] {
let output = modmul_outputs_iter.next().unwrap();
test_modmul_bignum(a.clone(), b.clone(), m.clone(), output)?;
}
}
}
Ok(())
}
#[test]
fn test_modexp_bignum_all() -> Result<()> {
// Only test smaller values for exponent.
let exp_bit_sizes = vec![2, 100, 127, 128, 129];
for bit_size in &BIT_SIZES_TO_TEST[3..14] {
for exp_bit_size in &exp_bit_sizes {
let b = gen_bignum(*bit_size);
let e = gen_bignum(*exp_bit_size);
let m = gen_bignum(*bit_size);
if !m.is_zero() {
let output = b.clone().modpow(&e, &m);
test_modexp_bignum(b, e, m, output)?;
}
let b = max_bignum(*bit_size);
let e = max_bignum(*exp_bit_size);
let m = max_bignum(*bit_size);
if !m.is_zero() {
let output = b.modpow(&e, &m);
test_modexp_bignum(b, e, m, output)?;
}
}
}
let inputs = test_data_biguint(TEST_DATA_BIGNUM_INPUTS);
let modexp_outputs = test_data_biguint(TEST_DATA_MODEXP_OUTPUTS);
let mut modexp_outputs_iter = modexp_outputs.into_iter();
for b in &inputs {
// Include only smaller exponents, to keep tests from becoming too slow.
for e in &inputs[..7] {
// For m, skip the first input, which is zero.
for m in &inputs[1..] {
let output = modexp_outputs_iter.next().unwrap();
test_modexp_bignum(b.clone(), e.clone(), m.clone(), output)?;
}
}
}
Ok(())
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,7 @@
use std::collections::BTreeMap;
use std::ops::Range;
use hashbrown::HashMap;
use itertools::Itertools;
use plonky2::field::extension::Extendable;
use plonky2::fri::FriParams;
@ -17,6 +18,7 @@ use plonky2::plonk::circuit_data::{
use plonky2::plonk::config::{AlgebraicHasher, GenericConfig, Hasher};
use plonky2::plonk::proof::{ProofWithPublicInputs, ProofWithPublicInputsTarget};
use plonky2::recursion::cyclic_recursion::check_cyclic_proof_verifier_data;
use plonky2::recursion::dummy_circuit::cyclic_base_proof;
use plonky2::util::timing::TimingTree;
use plonky2_util::log2_ceil;
@ -453,6 +455,15 @@ where
if let Some(parent_block_proof) = opt_parent_block_proof {
block_inputs
.set_proof_with_pis_target(&self.block.parent_block_proof, parent_block_proof);
} else {
block_inputs.set_proof_with_pis_target(
&self.block.parent_block_proof,
&cyclic_base_proof(
&self.block.circuit.common,
&self.block.circuit.verifier_only,
HashMap::new(),
),
);
}
block_inputs.set_proof_with_pis_target(&self.block.agg_root_proof, agg_root_proof);

View File

@ -3,6 +3,7 @@ use std::str::FromStr;
use anyhow::{bail, Error};
use ethereum_types::{BigEndianHash, H256, U256, U512};
use itertools::Itertools;
use plonky2::field::types::Field;
use crate::extension_tower::{FieldExt, Fp12, BLS381, BN254};
@ -11,7 +12,9 @@ use crate::generation::prover_input::EvmField::{
};
use crate::generation::prover_input::FieldOp::{Inverse, Sqrt};
use crate::generation::state::GenerationState;
use crate::memory::segments::Segment;
use crate::memory::segments::Segment::BnPairing;
use crate::util::{biguint_to_mem_vec, mem_vec_to_biguint};
use crate::witness::util::{kernel_peek, stack_peek};
/// Prover input function represented as a scoped function name.
@ -35,6 +38,7 @@ impl<F: Field> GenerationState<F> {
"mpt" => self.run_mpt(),
"rlp" => self.run_rlp(),
"account_code" => self.run_account_code(input_fn),
"bignum_modmul" => self.run_bignum_modmul(),
_ => panic!("Unrecognized prover input function."),
}
}
@ -140,6 +144,69 @@ impl<F: Field> GenerationState<F> {
_ => panic!("Invalid prover input function."),
}
}
// Bignum modular multiplication.
// On the first call, calculates the remainder and quotient of the given inputs.
// These are stored, as limbs, in self.bignum_modmul_result_limbs.
// Subsequent calls return one limb at a time, in order (first remainder and then quotient).
fn run_bignum_modmul(&mut self) -> U256 {
if self.bignum_modmul_result_limbs.is_empty() {
let len = stack_peek(self, 1)
.expect("Stack does not have enough items")
.try_into()
.unwrap();
let a_start_loc = stack_peek(self, 2)
.expect("Stack does not have enough items")
.try_into()
.unwrap();
let b_start_loc = stack_peek(self, 3)
.expect("Stack does not have enough items")
.try_into()
.unwrap();
let m_start_loc = stack_peek(self, 4)
.expect("Stack does not have enough items")
.try_into()
.unwrap();
let (remainder, quotient) =
self.bignum_modmul(len, a_start_loc, b_start_loc, m_start_loc);
self.bignum_modmul_result_limbs = remainder
.iter()
.cloned()
.pad_using(len, |_| 0.into())
.chain(quotient.iter().cloned().pad_using(2 * len, |_| 0.into()))
.collect();
self.bignum_modmul_result_limbs.reverse();
}
self.bignum_modmul_result_limbs.pop().unwrap()
}
fn bignum_modmul(
&mut self,
len: usize,
a_start_loc: usize,
b_start_loc: usize,
m_start_loc: usize,
) -> (Vec<U256>, Vec<U256>) {
let a = &self.memory.contexts[0].segments[Segment::KernelGeneral as usize].content
[a_start_loc..a_start_loc + len];
let b = &self.memory.contexts[0].segments[Segment::KernelGeneral as usize].content
[b_start_loc..b_start_loc + len];
let m = &self.memory.contexts[0].segments[Segment::KernelGeneral as usize].content
[m_start_loc..m_start_loc + len];
let a_biguint = mem_vec_to_biguint(a);
let b_biguint = mem_vec_to_biguint(b);
let m_biguint = mem_vec_to_biguint(m);
let prod = a_biguint * b_biguint;
let quo = &prod / &m_biguint;
let rem = prod - m_biguint * &quo;
(biguint_to_mem_vec(rem), biguint_to_mem_vec(quo))
}
}
enum EvmField {

View File

@ -39,6 +39,11 @@ pub(crate) struct GenerationState<F: Field> {
/// useful to see the actual addresses for debugging. Here we store the mapping for all known
/// addresses.
pub(crate) state_key_to_address: HashMap<H256, Address>,
/// Prover inputs containing the result of a MODMUL operation, in little-endian order (so that
/// inputs are obtained in big-endian order via `pop()`). Contains both the remainder and the
/// quotient, in that order.
pub(crate) bignum_modmul_result_limbs: Vec<U256>,
}
impl<F: Field> GenerationState<F> {
@ -54,6 +59,7 @@ impl<F: Field> GenerationState<F> {
log::debug!("Input contract_code: {:?}", &inputs.contract_code);
let mpt_prover_inputs = all_mpt_prover_inputs_reversed(&inputs.tries);
let rlp_prover_inputs = all_rlp_prover_inputs_reversed(&inputs.signed_txns);
let bignum_modmul_result_limbs = Vec::new();
Self {
inputs,
@ -64,6 +70,7 @@ impl<F: Field> GenerationState<F> {
mpt_prover_inputs,
rlp_prover_inputs,
state_key_to_address: HashMap::new(),
bignum_modmul_result_limbs,
}
}

View File

@ -170,7 +170,6 @@ pub struct KeccakSpongeStark<F, const D: usize> {
}
impl<F: RichField + Extendable<D>, const D: usize> KeccakSpongeStark<F, D> {
#[allow(unused)] // TODO: Should be used soon.
pub(crate) fn generate_trace(
&self,
operations: Vec<KeccakSpongeOp>,
@ -361,40 +360,242 @@ impl<F: RichField + Extendable<D>, const D: usize> Stark<F, D> for KeccakSpongeS
fn eval_packed_generic<FE, P, const D2: usize>(
&self,
vars: StarkEvaluationVars<FE, P, { Self::COLUMNS }>,
_yield_constr: &mut ConstraintConsumer<P>,
yield_constr: &mut ConstraintConsumer<P>,
) where
FE: FieldExtension<D2, BaseField = F>,
P: PackedField<Scalar = FE>,
{
let _local_values: &KeccakSpongeColumnsView<P> = vars.local_values.borrow();
let local_values: &KeccakSpongeColumnsView<P> = vars.local_values.borrow();
let next_values: &KeccakSpongeColumnsView<P> = vars.next_values.borrow();
// TODO: Each flag (full-input block, final block or implied dummy flag) must be boolean.
// TODO: before_rate_bits, block_bits and is_final_input_len must contain booleans.
// Each flag (full-input block, final block or implied dummy flag) must be boolean.
let is_full_input_block = local_values.is_full_input_block;
yield_constr.constraint(is_full_input_block * (is_full_input_block - P::ONES));
// TODO: Sum of is_final_input_len should equal is_final_block (which will be 0 or 1).
let is_final_block = local_values.is_final_block;
yield_constr.constraint(is_final_block * (is_final_block - P::ONES));
// TODO: If this is the first row, the original sponge state should be 0 and already_absorbed_bytes = 0.
// TODO: If this is a final block, the next row's original sponge state should be 0 and already_absorbed_bytes = 0.
for &is_final_len in local_values.is_final_input_len.iter() {
yield_constr.constraint(is_final_len * (is_final_len - P::ONES));
}
// TODO: If this is a full-input block, the next row's address, time and len must match.
// TODO: If this is a full-input block, the next row's "before" should match our "after" state.
// TODO: If this is a full-input block, the next row's already_absorbed_bytes should be ours plus 136.
// Ensure that full-input block and final block flags are not set to 1 at the same time.
yield_constr.constraint(is_final_block * is_full_input_block);
// TODO: A dummy row is always followed by another dummy row, so the prover can't put dummy rows "in between" to avoid the above checks.
// Sum of is_final_input_len should equal is_final_block (which will be 0 or 1).
let is_final_input_len_sum: P = local_values.is_final_input_len.iter().copied().sum();
yield_constr.constraint(is_final_input_len_sum - is_final_block);
// TODO: is_final_input_len implies `len - already_absorbed == i`.
// If this is a full-input block, is_final_input_len should contain all 0s.
yield_constr.constraint(is_full_input_block * is_final_input_len_sum);
// If this is the first row, the original sponge state should be 0 and already_absorbed_bytes = 0.
let already_absorbed_bytes = local_values.already_absorbed_bytes;
yield_constr.constraint_first_row(already_absorbed_bytes);
for &original_rate_elem in local_values.original_rate_u32s.iter() {
yield_constr.constraint_first_row(original_rate_elem);
}
for &original_capacity_elem in local_values.original_capacity_u32s.iter() {
yield_constr.constraint_first_row(original_capacity_elem);
}
// If this is a final block, the next row's original sponge state should be 0 and already_absorbed_bytes = 0.
yield_constr.constraint_transition(is_final_block * next_values.already_absorbed_bytes);
for &original_rate_elem in next_values.original_rate_u32s.iter() {
yield_constr.constraint_transition(is_final_block * original_rate_elem);
}
for &original_capacity_elem in next_values.original_capacity_u32s.iter() {
yield_constr.constraint_transition(is_final_block * original_capacity_elem);
}
// If this is a full-input block, the next row's address, time and len must match as well as its timestamp.
yield_constr.constraint_transition(
is_full_input_block * (local_values.context - next_values.context),
);
yield_constr.constraint_transition(
is_full_input_block * (local_values.segment - next_values.segment),
);
yield_constr
.constraint_transition(is_full_input_block * (local_values.virt - next_values.virt));
yield_constr.constraint_transition(
is_full_input_block * (local_values.timestamp - next_values.timestamp),
);
// If this is a full-input block, the next row's "before" should match our "after" state.
for (&current_after, &next_before) in local_values
.updated_state_u32s
.iter()
.zip(next_values.original_rate_u32s.iter())
{
yield_constr.constraint_transition(is_full_input_block * (next_before - current_after));
}
for (&current_after, &next_before) in local_values
.updated_state_u32s
.iter()
.skip(KECCAK_RATE_U32S)
.zip(next_values.original_capacity_u32s.iter())
{
yield_constr.constraint_transition(is_full_input_block * (next_before - current_after));
}
// If this is a full-input block, the next row's already_absorbed_bytes should be ours plus 136.
yield_constr.constraint_transition(
is_full_input_block
* (already_absorbed_bytes + P::from(FE::from_canonical_u64(136))
- next_values.already_absorbed_bytes),
);
// A dummy row is always followed by another dummy row, so the prover can't put dummy rows "in between" to avoid the above checks.
let is_dummy = P::ONES - is_full_input_block - is_final_block;
yield_constr.constraint_transition(
is_dummy * (next_values.is_full_input_block + next_values.is_final_block),
);
// If this is a final block, is_final_input_len implies `len - already_absorbed == i`.
let offset = local_values.len - already_absorbed_bytes;
for (i, &is_final_len) in local_values.is_final_input_len.iter().enumerate() {
let entry_match = offset - P::from(FE::from_canonical_usize(i));
yield_constr.constraint(is_final_len * entry_match);
}
}
fn eval_ext_circuit(
&self,
_builder: &mut plonky2::plonk::circuit_builder::CircuitBuilder<F, D>,
builder: &mut plonky2::plonk::circuit_builder::CircuitBuilder<F, D>,
vars: StarkEvaluationTargets<D, { Self::COLUMNS }>,
_yield_constr: &mut RecursiveConstraintConsumer<F, D>,
yield_constr: &mut RecursiveConstraintConsumer<F, D>,
) {
let _local_values: &KeccakSpongeColumnsView<ExtensionTarget<D>> =
vars.local_values.borrow();
let local_values: &KeccakSpongeColumnsView<ExtensionTarget<D>> = vars.local_values.borrow();
let next_values: &KeccakSpongeColumnsView<ExtensionTarget<D>> = vars.next_values.borrow();
// TODO
let one = builder.one_extension();
// Each flag (full-input block, final block or implied dummy flag) must be boolean.
let is_full_input_block = local_values.is_full_input_block;
let constraint = builder.mul_sub_extension(
is_full_input_block,
is_full_input_block,
is_full_input_block,
);
yield_constr.constraint(builder, constraint);
let is_final_block = local_values.is_final_block;
let constraint = builder.mul_sub_extension(is_final_block, is_final_block, is_final_block);
yield_constr.constraint(builder, constraint);
for &is_final_len in local_values.is_final_input_len.iter() {
let constraint = builder.mul_sub_extension(is_final_len, is_final_len, is_final_len);
yield_constr.constraint(builder, constraint);
}
// Ensure that full-input block and final block flags are not set to 1 at the same time.
let constraint = builder.mul_extension(is_final_block, is_full_input_block);
yield_constr.constraint(builder, constraint);
// Sum of is_final_input_len should equal is_final_block (which will be 0 or 1).
let mut is_final_input_len_sum = builder.add_extension(
local_values.is_final_input_len[0],
local_values.is_final_input_len[1],
);
for &input_len in local_values.is_final_input_len.iter().skip(2) {
is_final_input_len_sum = builder.add_extension(is_final_input_len_sum, input_len);
}
let constraint = builder.sub_extension(is_final_input_len_sum, is_final_block);
yield_constr.constraint(builder, constraint);
// If this is a full-input block, is_final_input_len should contain all 0s.
let constraint = builder.mul_extension(is_full_input_block, is_final_input_len_sum);
yield_constr.constraint(builder, constraint);
// If this is the first row, the original sponge state should be 0 and already_absorbed_bytes = 0.
let already_absorbed_bytes = local_values.already_absorbed_bytes;
yield_constr.constraint_first_row(builder, already_absorbed_bytes);
for &original_rate_elem in local_values.original_rate_u32s.iter() {
yield_constr.constraint_first_row(builder, original_rate_elem);
}
for &original_capacity_elem in local_values.original_capacity_u32s.iter() {
yield_constr.constraint_first_row(builder, original_capacity_elem);
}
// If this is a final block, the next row's original sponge state should be 0 and already_absorbed_bytes = 0.
let constraint = builder.mul_extension(is_final_block, next_values.already_absorbed_bytes);
yield_constr.constraint_transition(builder, constraint);
for &original_rate_elem in next_values.original_rate_u32s.iter() {
let constraint = builder.mul_extension(is_final_block, original_rate_elem);
yield_constr.constraint_transition(builder, constraint);
}
for &original_capacity_elem in next_values.original_capacity_u32s.iter() {
let constraint = builder.mul_extension(is_final_block, original_capacity_elem);
yield_constr.constraint_transition(builder, constraint);
}
// If this is a full-input block, the next row's address, time and len must match as well as its timestamp.
let context_diff = builder.sub_extension(local_values.context, next_values.context);
let constraint = builder.mul_extension(is_full_input_block, context_diff);
yield_constr.constraint_transition(builder, constraint);
let segment_diff = builder.sub_extension(local_values.segment, next_values.segment);
let constraint = builder.mul_extension(is_full_input_block, segment_diff);
yield_constr.constraint_transition(builder, constraint);
let virt_diff = builder.sub_extension(local_values.virt, next_values.virt);
let constraint = builder.mul_extension(is_full_input_block, virt_diff);
yield_constr.constraint_transition(builder, constraint);
let timestamp_diff = builder.sub_extension(local_values.timestamp, next_values.timestamp);
let constraint = builder.mul_extension(is_full_input_block, timestamp_diff);
yield_constr.constraint_transition(builder, constraint);
// If this is a full-input block, the next row's "before" should match our "after" state.
for (&current_after, &next_before) in local_values
.updated_state_u32s
.iter()
.zip(next_values.original_rate_u32s.iter())
{
let diff = builder.sub_extension(next_before, current_after);
let constraint = builder.mul_extension(is_full_input_block, diff);
yield_constr.constraint_transition(builder, constraint);
}
for (&current_after, &next_before) in local_values
.updated_state_u32s
.iter()
.skip(KECCAK_RATE_U32S)
.zip(next_values.original_capacity_u32s.iter())
{
let diff = builder.sub_extension(next_before, current_after);
let constraint = builder.mul_extension(is_full_input_block, diff);
yield_constr.constraint_transition(builder, constraint);
}
// If this is a full-input block, the next row's already_absorbed_bytes should be ours plus 136.
let absorbed_bytes =
builder.add_const_extension(already_absorbed_bytes, F::from_canonical_u64(136));
let absorbed_diff =
builder.sub_extension(absorbed_bytes, next_values.already_absorbed_bytes);
let constraint = builder.mul_extension(is_full_input_block, absorbed_diff);
yield_constr.constraint_transition(builder, constraint);
// A dummy row is always followed by another dummy row, so the prover can't put dummy rows "in between" to avoid the above checks.
let is_dummy = {
let tmp = builder.sub_extension(one, is_final_block);
builder.sub_extension(tmp, is_full_input_block)
};
let constraint = {
let tmp =
builder.add_extension(next_values.is_final_block, next_values.is_full_input_block);
builder.mul_extension(is_dummy, tmp)
};
yield_constr.constraint_transition(builder, constraint);
// If this is a final block, is_final_input_len implies `len - already_absorbed == i`.
let offset = builder.sub_extension(local_values.len, already_absorbed_bytes);
for (i, &is_final_len) in local_values.is_final_input_len.iter().enumerate() {
let index = builder.constant_extension(F::from_canonical_usize(i).into());
let entry_match = builder.sub_extension(offset, index);
let constraint = builder.mul_extension(is_final_len, entry_match);
yield_constr.constraint(builder, constraint);
}
}
fn constraint_degree(&self) -> usize {

View File

@ -132,7 +132,7 @@ impl Segment {
Segment::KernelGeneral2 => 256,
Segment::KernelAccountCode => 8,
Segment::TxnFields => 256,
Segment::TxnData => 256,
Segment::TxnData => 8,
Segment::RlpRaw => 8,
Segment::TrieData => 256,
Segment::TrieEncodedChild => 256,

View File

@ -145,11 +145,11 @@ pub(crate) fn biguint_to_u256(x: BigUint) -> U256 {
U256::from_little_endian(&bytes)
}
#[cfg(test)]
pub(crate) fn le_limbs_to_biguint(x: &[u128]) -> BigUint {
pub(crate) fn mem_vec_to_biguint(x: &[U256]) -> BigUint {
BigUint::from_slice(
&x.iter()
.flat_map(|&a| {
.map(|&n| n.try_into().unwrap())
.flat_map(|a: u128| {
[
(a % (1 << 32)) as u32,
((a >> 32) % (1 << 32)) as u32,
@ -161,28 +161,15 @@ pub(crate) fn le_limbs_to_biguint(x: &[u128]) -> BigUint {
)
}
#[cfg(test)]
pub(crate) fn mem_vec_to_biguint(x: &[U256]) -> BigUint {
le_limbs_to_biguint(&x.iter().map(|&n| n.try_into().unwrap()).collect_vec())
}
#[cfg(test)]
pub(crate) fn biguint_to_le_limbs(x: BigUint) -> Vec<u128> {
let mut digits = x.to_u32_digits();
// Pad to a multiple of 4.
digits.resize((digits.len() + 3) / 4 * 4, 0);
digits
.chunks(4)
.map(|c| (c[3] as u128) << 96 | (c[2] as u128) << 64 | (c[1] as u128) << 32 | c[0] as u128)
.collect()
}
#[cfg(test)]
pub(crate) fn biguint_to_mem_vec(x: BigUint) -> Vec<U256> {
biguint_to_le_limbs(x)
.into_iter()
.map(|n| n.into())
.collect()
let num_limbs = ((x.bits() + 127) / 128) as usize;
let mut digits = x.iter_u64_digits();
let mut mem_vec = Vec::with_capacity(num_limbs);
while let Some(lo) = digits.next() {
let hi = digits.next().unwrap_or(0);
mem_vec.push(U256::from(lo as u128 | (hi as u128) << 64));
}
mem_vec
}

View File

@ -127,7 +127,12 @@ pub(crate) fn generate_keccak_general<F: Field>(
log::debug!("Hashing {:?}", input);
let hash = keccak(&input);
let log_push = stack_push_log_and_fill(state, &mut row, hash.into_uint())?;
let val_u64s: [u64; 4] =
core::array::from_fn(|i| u64::from_le_bytes(core::array::from_fn(|j| hash.0[i * 8 + j])));
let hash_int = U256(val_u64s);
let mut log_push = stack_push_log_and_fill(state, &mut row, hash_int)?;
log_push.value = hash.into_uint();
keccak_sponge_log(state, base_address, input);

View File

@ -309,10 +309,11 @@ pub(crate) fn transition<F: Field>(state: &mut GenerationState<F>) -> anyhow::Re
if state.registers.is_kernel {
let offset_name = KERNEL.offset_name(state.registers.program_counter);
bail!(
"{:?} in kernel at pc={}, stack={:?}",
"{:?} in kernel at pc={}, stack={:?}, memory={:?}",
e,
offset_name,
state.stack()
state.stack(),
state.memory.contexts[0].segments[Segment::KernelGeneral as usize].content,
);
}
state.rollback(checkpoint);

View File

@ -0,0 +1,38 @@
#![allow(clippy::upper_case_acronyms)]
use anyhow::Result;
use plonky2::field::types::Field;
use plonky2::iop::witness::{PartialWitness, WitnessWrite};
use plonky2::plonk::circuit_builder::CircuitBuilder;
use plonky2::plonk::circuit_data::CircuitConfig;
use plonky2::plonk::config::{GenericConfig, PoseidonGoldilocksConfig};
/// An example of using Plonky2 to prove that a given value lies in a given range.
fn main() -> Result<()> {
const D: usize = 2;
type C = PoseidonGoldilocksConfig;
type F = <C as GenericConfig<D>>::F;
let config = CircuitConfig::standard_recursion_config();
let mut builder = CircuitBuilder::<F, D>::new(config);
// The secret value.
let value = builder.add_virtual_target();
builder.register_public_input(value);
let log_max = 6;
builder.range_check(value, log_max);
let mut pw = PartialWitness::new();
pw.set_target(value, F::from_canonical_usize(42));
let data = builder.build::<C>();
let proof = data.prove(pw)?;
println!(
"Value {} is less than 2^{}",
proof.public_inputs[0], log_max,
);
data.verify(proof)
}