Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Rlp decode circuit #14

Draft
wants to merge 21 commits into
base: mpt-sync
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,327 changes: 698 additions & 629 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ members = [
"testool"
]

[patch.crates-io]
halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2.git", tag = "v2023_02_02" }
[patch."https://github.com/privacy-scaling-explorations/halo2.git"]
halo2_proofs = { path = "../halo2/halo2_proofs" }

# Definition of benchmarks profile to use.
[profile.bench]
Expand Down
4 changes: 2 additions & 2 deletions bus-mapping/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ gadgets = { path = "../gadgets" }
keccak256 = { path = "../keccak256" }
mock = { path = "../mock", optional = true }

ethers-core = "0.17.0"
ethers-providers = "0.17.0"
ethers-core = "2.0.0"
ethers-providers = "2.0.0"
halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2.git", tag = "v2023_02_02" }
itertools = "0.10"
lazy_static = "1.4"
Expand Down
2 changes: 1 addition & 1 deletion circuit-benchmarks/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ rand = "0.8"
itertools = "0.10"
eth-types = { path = "../eth-types" }
env_logger = "0.9"
ethers-signers = "0.17.0"
ethers-signers = "2.0.2"
mock = { path="../mock" }
rand_chacha = "0.3"

Expand Down
4 changes: 2 additions & 2 deletions eth-types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ authors = ["The appliedzkp team"]
license = "MIT OR Apache-2.0"

[dependencies]
ethers-core = "0.17.0"
ethers-signers = "0.17.0"
ethers-core = "2.0.2"
ethers-signers = "2.0.2"
hex = "0.4"
lazy_static = "1.4"
halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2.git", tag = "v2023_02_02" }
Expand Down
4 changes: 3 additions & 1 deletion eth-types/src/geth_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,9 @@ impl GethData {
assert_eq!(Word::from(wallet.chain_id()), self.chain_id);
let geth_tx: Transaction = (&*tx).into();
let req: TransactionRequest = (&geth_tx).into();
let sig = wallet.sign_transaction_sync(&req.chain_id(self.chain_id.as_u64()).into());
let sig = wallet
.sign_transaction_sync(&req.chain_id(self.chain_id.as_u64()).into())
.unwrap();
tx.v = U64::from(sig.v);
tx.r = sig.r;
tx.s = sig.s;
Expand Down
257 changes: 257 additions & 0 deletions gadgets/src/is_equal.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,257 @@
//! IsEqual chip can be used to check equality of two expressions.

use eth_types::Field;
use halo2_proofs::{
arithmetic::FieldExt,
circuit::{Chip, Region, Value},
plonk::{ConstraintSystem, Error, Expression, VirtualCells},
};

use crate::util::Expr;

use super::is_zero::{IsZeroChip, IsZeroInstruction};

/// Instruction that the IsEqual chip needs to implement.
pub trait IsEqualInstruction<F: FieldExt> {
/// Assign lhs and rhs witnesses to the IsEqual chip's region.
fn assign(
&self,
region: &mut Region<'_, F>,
offset: usize,
lhs: Value<F>,
rhs: Value<F>,
) -> Result<(), Error>;
}

/// Config for the IsEqual chip.
#[derive(Clone, Debug)]
pub struct IsEqualConfig<F> {
/// Stores an IsZero chip.
pub is_zero_chip: IsZeroChip<F>,
/// Expression that denotes whether the chip evaluated to equal or not.
pub is_equal_expression: Expression<F>,
}

impl<F: Field> IsEqualConfig<F> {
/// Returns the expression that denotes whether the chip evaluated to equal or not.
pub fn is_equal(&self) -> Expression<F> {
self.is_equal_expression.expr()
}
}

/// Chip that compares equality between two expressions.
#[derive(Clone, Debug)]
pub struct IsEqualChip<F> {
/// Config for the IsEqual chip.
pub(crate) config: IsEqualConfig<F>,
}

impl<F: Field> IsEqualChip<F> {
/// Configure the IsEqual chip.
pub fn configure(
meta: &mut ConstraintSystem<F>,
q_enable: impl FnOnce(&mut VirtualCells<'_, F>) -> Expression<F>,
lhs: impl FnOnce(&mut VirtualCells<'_, F>) -> Expression<F>,
rhs: impl FnOnce(&mut VirtualCells<'_, F>) -> Expression<F>,
) -> IsEqualConfig<F> {
let value = |meta: &mut VirtualCells<F>| lhs(meta) - rhs(meta);
let value_inv = meta.advice_column();

let is_zero_config = IsZeroChip::configure(meta, q_enable, value, value_inv);
let is_equal_expression = is_zero_config.is_zero_expression.clone();

IsEqualConfig {
is_zero_chip: IsZeroChip::construct(is_zero_config),
is_equal_expression,
}
}

/// Construct an IsEqual chip given a config.
pub fn construct(config: IsEqualConfig<F>) -> Self {
Self { config }
}
}

impl<F: Field> IsEqualInstruction<F> for IsEqualChip<F> {
fn assign(
&self,
region: &mut Region<'_, F>,
offset: usize,
lhs: Value<F>,
rhs: Value<F>,
) -> Result<(), Error> {
self.config.is_zero_chip.assign(region, offset, lhs - rhs)?;

Ok(())
}
}

impl<F: Field> Chip<F> for IsEqualChip<F> {
type Config = IsEqualConfig<F>;
type Loaded = ();

fn config(&self) -> &Self::Config {
&self.config
}

fn loaded(&self) -> &Self::Loaded {
&()
}
}

#[cfg(test)]
mod tests {
use std::marker::PhantomData;

use eth_types::Field;
use halo2_proofs::{
arithmetic::FieldExt,
circuit::{Layouter, SimpleFloorPlanner, Value},
dev::MockProver,
halo2curves::bn256::Fr as Fp,
plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Selector, VirtualCells},
poly::Rotation,
};
use rand::Rng;

use super::{IsEqualChip, IsEqualConfig, IsEqualInstruction};
use crate::util::Expr;

#[derive(Clone, Debug)]
struct TestCircuitConfig<F, const RHS: u64> {
q_enable: Selector,
value: Column<Advice>,
check: Column<Advice>,
is_equal: IsEqualConfig<F>,
}

#[derive(Default)]
struct TestCircuit<F: FieldExt, const RHS: u64> {
values: Vec<u64>,
checks: Vec<bool>,
_marker: PhantomData<F>,
}

impl<F: Field, const RHS: u64> Circuit<F> for TestCircuit<F, RHS> {
type Config = TestCircuitConfig<F, RHS>;
type FloorPlanner = SimpleFloorPlanner;

fn without_witnesses(&self) -> Self {
Self::default()
}

fn configure(meta: &mut ConstraintSystem<F>) -> Self::Config {
let q_enable = meta.complex_selector();
let value = meta.advice_column();
let check = meta.advice_column();

let lhs = |meta: &mut VirtualCells<F>| meta.query_advice(value, Rotation::cur());
let rhs = |_meta: &mut VirtualCells<F>| RHS.expr();

let is_equal =
IsEqualChip::configure(meta, |meta| meta.query_selector(q_enable), lhs, rhs);

let config = Self::Config {
q_enable,
value,
check,
is_equal,
};

meta.create_gate("check is_equal", |meta| {
let q_enable = meta.query_selector(q_enable);

let check = meta.query_advice(check, Rotation::cur());

vec![q_enable * (config.is_equal.is_equal_expression.clone() - check)]
});

config
}

fn synthesize(
&self,
config: Self::Config,
mut layouter: impl Layouter<F>,
) -> Result<(), Error> {
let chip = IsEqualChip::construct(config.is_equal.clone());

layouter.assign_region(
|| "witness",
|mut region| {
let checks = self.checks.clone();

for (idx, (value, check)) in self.values.iter().cloned().zip(checks).enumerate()
{
region.assign_advice(
|| "value",
config.value,
idx + 1,
|| Value::known(F::from(value)),
)?;
region.assign_advice(
|| "check",
config.check,
idx + 1,
|| Value::known(F::from(check as u64)),
)?;
config.q_enable.enable(&mut region, idx + 1)?;
chip.assign(
&mut region,
idx + 1,
Value::known(F::from(value)),
Value::known(F::from(RHS)),
)?;
}

Ok(())
},
)
}
}

macro_rules! try_test {
($values:expr, $checks:expr, $rhs:expr, $is_ok_or_err:ident) => {
let k = usize::BITS - $values.len().leading_zeros() + 2;
let circuit = TestCircuit::<Fp, $rhs> {
values: $values,
checks: $checks,
_marker: PhantomData,
};
let prover = MockProver::<Fp>::run(k, &circuit, vec![]).unwrap();
assert!(prover.verify().$is_ok_or_err());
};
}

fn random() -> u64 {
rand::thread_rng().gen::<u64>()
}

#[test]
fn is_equal_gadget() {
try_test!(
vec![random(), 123, random(), 123, 123, random()],
vec![false, true, false, true, true, false],
123,
is_ok
);
try_test!(
vec![random(), 321321, 321321, random()],
vec![false, true, true, false],
321321,
is_ok
);
try_test!(
vec![random(), random(), random(), 1846123],
vec![false, false, false, true],
1846123,
is_ok
);
try_test!(
vec![123, 234, 345, 456],
vec![true, true, false, false],
234,
is_err
);
}
}
1 change: 1 addition & 0 deletions gadgets/src/is_zero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ impl<F: Field> IsZeroConfig<F> {
}
}

#[derive(Clone, Debug)]
/// Wrapper arround [`IsZeroConfig`] for which [`Chip`] is implemented.
pub struct IsZeroChip<F> {
config: IsZeroConfig<F>,
Expand Down
1 change: 1 addition & 0 deletions gadgets/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
pub mod batched_is_zero;
pub mod binary_number;
pub mod evm_word;
pub mod is_equal;
pub mod is_zero;
pub mod less_than;
pub mod monotone;
Expand Down
2 changes: 1 addition & 1 deletion integration-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ license = "MIT OR Apache-2.0"

[dependencies]
lazy_static = "1.4"
ethers = { version = "0.17.0", features = ["ethers-solc"] }
ethers = { version = "2.0.0", features = ["ethers-solc"] }
serde_json = "1.0.66"
serde = { version = "1.0.130", features = ["derive"] }
bus-mapping = { path = "../bus-mapping" }
Expand Down
4 changes: 2 additions & 2 deletions mock/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ eth-types = { path = "../eth-types" }
external-tracer = { path = "../external-tracer" }
lazy_static = "1.4"
itertools = "0.10.3"
ethers-signers = "0.17.0"
ethers-core = "0.17.0"
ethers-signers = "2.0.2"
ethers-core = "2.0.2"
rand_chacha = "0.3"
rand = "0.8"
3 changes: 2 additions & 1 deletion mock/src/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,8 @@ impl MockTransaction {
.from
.as_wallet()
.with_chain_id(self.chain_id.low_u64())
.sign_transaction_sync(&tx.into());
.sign_transaction_sync(&tx.into())
.unwrap();
// Set sig parameters
self.sig_data((sig.v, sig.r, sig.s));
}
Expand Down
2 changes: 1 addition & 1 deletion rust-toolchain
Original file line number Diff line number Diff line change
@@ -1 +1 @@
nightly-2022-08-23
nightly-2023-03-28
4 changes: 2 additions & 2 deletions testool/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ bus-mapping = { path = "../bus-mapping" }
clap = { version = "3.1", features = ["derive"] }
env_logger = "0.9"
eth-types = { path="../eth-types" }
ethers-core = "0.17.0"
ethers-signers = "0.17.0"
ethers-core = "2.0.2"
ethers-signers = "2.0.2"
external-tracer = { path="../external-tracer" }
glob = "0.3"
handlebars = "4.3"
Expand Down
4 changes: 2 additions & 2 deletions testool/src/statetest/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ fn into_traceconfig(st: StateTest) -> (String, TraceConfig, StateTestResult) {
}
let tx: TypedTransaction = tx.into();

let sig = wallet.sign_transaction_sync(&tx);
let sig = wallet.sign_transaction_sync(&tx).unwrap();

(
st.id,
Expand Down Expand Up @@ -242,7 +242,7 @@ pub fn run_test(
..eth_types::Block::default()
};

let wallet: LocalWallet = SigningKey::from_bytes(&st.secret_key).unwrap().into();
let wallet: LocalWallet = SigningKey::from_slice(&st.secret_key).unwrap().into();
let mut wallets = HashMap::new();
wallets.insert(
wallet.address(),
Expand Down
2 changes: 1 addition & 1 deletion testool/src/statetest/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ impl<'a> JsonStateTestBuilder<'a> {

let to = parse::parse_to_address(&test.transaction.to)?;
let secret_key = parse::parse_bytes(&test.transaction.secret_key)?;
let from = secret_key_to_address(&SigningKey::from_bytes(&secret_key.to_vec())?);
let from = secret_key_to_address(&SigningKey::from_slice(&secret_key)?);
let nonce = parse::parse_u256(&test.transaction.nonce)?;
let gas_price = parse::parse_u256(&test.transaction.gas_price)?;

Expand Down
Loading