Skip to content
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
14 changes: 14 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions bench_vs/lambda/recursion/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

122 changes: 116 additions & 6 deletions crypto/ethrex-crypto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,17 @@
//! Every other `Crypto` method inherits the trait default (vetted pure-Rust
//! crates: `ark-bn254`, `bls12_381`, `p256`, `sha2`, `ripemd`, …).

// Only the host `keccak256` falls back to software keccak; the guest routes
// through the precompile, so on riscv64 this import would be unused.
#[cfg(not(target_arch = "riscv64"))]
use ethrex_crypto::keccak::keccak_hash;
use ethrex_crypto::{Crypto, CryptoError};
use k256::elliptic_curve::group::prime::PrimeCurveAffine;
use k256::elliptic_curve::ops::{Invert, LinearCombination, Reduce};
use k256::elliptic_curve::point::DecompressPoint;
use k256::elliptic_curve::ops::{LinearCombination, Reduce};
// `Invert` (software `x.invert()`) is only used by the host fallback; on the
// riscv64 guest all inversions go through the `hint` ecall.
#[cfg(not(target_arch = "riscv64"))]
use k256::elliptic_curve::ops::Invert;
use k256::elliptic_curve::sec1::ToEncodedPoint;
use k256::elliptic_curve::PrimeField;
use k256::{AffinePoint, FieldBytes, ProjectivePoint, Scalar, U256};
Expand Down Expand Up @@ -77,6 +83,83 @@ impl Crypto for LambdaVmEcsmCrypto {
/// We compute the recovery directly rather than calling k256's
/// `recover_from_prehash`, which internally runs a *second* lincomb to
/// re-verify the key — doubling the ECSM ecalls for no gain here.
/// Obtain a 32-byte big-endian hint for `x_be` via the executor `hint` ecall
/// (the host computes the modular inverse / sqrt; the value is provable via the
/// prover's HINT table). The result is UNVERIFIED — every caller MUST check it
/// in-guest (`x·inv == 1`, `y² == x³+7`), since the ecall adds no correctness
/// constraint. BENCH scaffolding.
#[cfg(target_arch = "riscv64")]
fn get_hint(hint_id: usize, x_be: &[u8; 32]) -> [u8; 32] {
let mut out = [0u8; 32];
lambda_vm_syscalls::syscalls::hint(hint_id, &mut out, x_be);
out
}

/// Scalar-field inverse `x⁻¹ mod n`. On riscv64 (guest) the inverse comes from the
/// `hint` ecall and we verify `x·inv == 1`; off-target (host tests) it computes the
/// inverse in software. BENCH scaffolding.
fn scalar_inv(x: &Scalar) -> Option<Scalar> {
#[cfg(target_arch = "riscv64")]
{
use k256::elliptic_curve::subtle::ConstantTimeEq;
let x_be: [u8; 32] = x.to_bytes().into();
let inv_be = get_hint(lambda_vm_syscalls::syscalls::HINT_SCALAR_INV, &x_be);
let inv: Scalar = Option::from(Scalar::from_repr(inv_be.into()))?;
// Verify the untrusted hint: x·inv must equal 1 (mod n).
if bool::from((*x * inv).ct_eq(&Scalar::ONE)) {
Some(inv)
} else {
None
}
}
#[cfg(not(target_arch = "riscv64"))]
{
x.invert_vartime().into()
}
}

/// Decompress R from its x-coordinate + parity. On riscv64 the `y = sqrt(x³+7)`
/// is an `hint`-ecall value verified in-guest (`y² == x³+7`), with parity
/// selection; off-target it uses k256's software `decompress`. BENCH scaffolding.
fn decompress_r(r_bytes: &FieldBytes, y_is_odd: bool) -> Option<AffinePoint> {
#[cfg(target_arch = "riscv64")]
{
let x: FieldElement = Option::from(FieldElement::from_bytes(r_bytes))?;
// secp256k1: y² = x³ + 7.
let mut seven_bytes = [0u8; 32];
seven_bytes[31] = 7;
let seven: FieldElement = Option::from(FieldElement::from_bytes(&seven_bytes.into()))?;
let x3: FieldElement = x.square() * x;
let rhs: FieldElement = x3 + seven;
// Hinted sqrt (BE in/out), then verify y² == rhs canonically.
let rhs_be: [u8; 32] = rhs.to_bytes().into();
let y_be = get_hint(lambda_vm_syscalls::syscalls::HINT_FIELD_SQRT, &rhs_be);
let mut y: FieldElement = Option::from(FieldElement::from_bytes(&y_be.into()))?;
let y2: FieldElement = y.square();
// Verify the untrusted root: y² must equal x³+7. Negate `y2`, not `rhs`:
// `Neg` is `negate(1)` and only accepts magnitude 1, which `square()` always
// returns, whereas `rhs` is a sum and carries magnitude 2 — negating it would
// silently compute the wrong value in release, where the debug assert is gone.
// (`ct_eq` is unusable here for the same reason as in `field_inv`.)
if !bool::from((rhs + y2.negate(1)).normalizes_to_zero()) {
return None;
}
// Select the root whose canonical LSB matches the requested parity.
let y_odd = (y.to_bytes()[31] & 1) == 1;
if y_odd != y_is_odd {
y = -y;
}
// Build the affine point; `from_encoded_point` re-checks it's on-curve.
let ep = EncodedPoint::from_affine_coordinates(&x.to_bytes(), &y.to_bytes(), false);
Option::from(AffinePoint::from_encoded_point(&ep))
}
#[cfg(not(target_arch = "riscv64"))]
{
use k256::elliptic_curve::point::DecompressPoint;
AffinePoint::decompress(r_bytes, u8::from(y_is_odd).into()).into()
}
}

fn ecsm_ecrecover(sig: &[u8; 64], recid: u8, msg: &[u8; 32]) -> Result<[u8; 64], CryptoError> {
let r_bytes = <&FieldBytes>::from(&sig[..32]);
let s_bytes = <&FieldBytes>::from(&sig[32..]);
Expand All @@ -96,15 +179,14 @@ fn ecsm_ecrecover(sig: &[u8; 64], recid: u8, msg: &[u8; 32]) -> Result<[u8; 64],
// precompile; we don't handle it (decompression simply fails), matching the
// trait default.
let y_is_odd = (recid & 1) != 0;
let r_point: Option<AffinePoint> =
AffinePoint::decompress(r_bytes, u8::from(y_is_odd).into()).into();
let r_point: Option<AffinePoint> = decompress_r(r_bytes, y_is_odd);
let Some(r_point) = r_point else {
return Err(CryptoError::RecoveryFailed);
};
let r_proj = ProjectivePoint::from(r_point);

let z = <Scalar as Reduce<U256>>::reduce_bytes(&FieldBytes::from(*msg));
let r_inv: Option<Scalar> = r.invert_vartime().into();
let r_inv: Option<Scalar> = scalar_inv(&r);
let Some(r_inv) = r_inv else {
return Err(CryptoError::RecoveryFailed);
};
Expand Down Expand Up @@ -194,6 +276,34 @@ fn ecsm_oracle(x: &FieldElement, k: &Scalar) -> Option<FieldElement> {
/// then `Q = A + B` is one affine addition. All three inversions are batched.
///
/// Generic over the oracle so unit tests can substitute a software stand-in.
/// Base-field inverse `x⁻¹ mod p`. On riscv64 the host supplies it via the
/// `hint` ecall and we verify `x·inv == 1`; off-target it inverts in software.
#[cfg(any(target_arch = "riscv64", test))]
fn field_inv(x: &FieldElement) -> Option<FieldElement> {
#[cfg(target_arch = "riscv64")]
{
let x_be: [u8; 32] = x.to_bytes().into();
let inv_be = get_hint(lambda_vm_syscalls::syscalls::HINT_FIELD_INV, &x_be);
let inv: FieldElement = Option::from(FieldElement::from_bytes(&inv_be.into()))?;
// Verify the untrusted hint: x·inv must equal 1 (mod p). Compare by asking
// whether the difference normalizes to zero — a value-level test that skips
// the two full normalizations a `to_bytes()` compare pays. `ct_eq` is NOT a
// substitute: k256's FieldElement compares raw limbs *and* the magnitude and
// `normalized` tags, so a `mul` result (magnitude 1, unnormalized) never
// compares equal to the normalized `ONE` constant whatever its value.
// `Neg` is `negate(1)`, valid here because `mul` yields magnitude 1.
if bool::from((*x * inv - FieldElement::ONE).normalizes_to_zero()) {
Some(inv)
} else {
None
}
}
#[cfg(not(target_arch = "riscv64"))]
{
Option::from(x.invert())
}
}

#[cfg(any(target_arch = "riscv64", test))]
fn lincomb2_with_oracle<O>(
a1: &AffinePoint,
Expand Down Expand Up @@ -232,7 +342,7 @@ where
// One shared inversion for the two λ denominators and the final chord.
let den1 = y1.double() * dx1;
let den2 = y2.double() * dx2;
let inv = Option::<FieldElement>::from((den1 * den2 * dxq).invert())?;
let inv = field_inv(&(den1 * den2 * dxq))?;
let inv_den1 = inv * den2 * dxq;
let inv_den2 = inv * den1 * dxq;
let inv_dxq = inv * den1 * den2;
Expand Down
38 changes: 38 additions & 0 deletions crypto/tiny-keccak/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Vendored fork of tiny-keccak 2.0.2 (CC0-1.0), used ONLY as a `[patch.crates-io]`
# override in the ethrex guest so every Keccak permutation (Ethereum trie/RLP hashing
# via ethrex-crypto's `keccak_hash` + `ethbloom`) routes through the lambda_vm
# `keccak_permute` accelerator syscall instead of the software ARX permutation.
#
# The ONLY change vs upstream 2.0.2 is `src/keccakf.rs`: on riscv64 the `keccakf`
# permutation calls `lambda_vm_syscalls::syscalls::keccak_permute`; on every other
# target it runs the original software permutation (so host builds/tests are unchanged).
# Keep name/version = tiny-keccak/2.0.2 so the crates.io patch resolves.
[package]
name = "tiny-keccak"
version = "2.0.2"
authors = ["debris <marek.kotewicz@gmail.com>"]
description = "An implementation of Keccak derived functions (lambda_vm keccak-syscall fork)."
edition = "2018"
license = "CC0-1.0"
homepage = "https://github.com/debris/tiny-keccak"

[dependencies]
crunchy = "0.2.2"

# The keccak-permute accelerator syscall only exists on the riscv64 guest; on host
# the software permutation is used, so this dependency is guest-only.
[target.'cfg(target_arch = "riscv64")'.dependencies]
lambda-vm-syscalls = { path = "../../syscalls" }

[features]
cshake = []
default = []
fips202 = ["keccak", "shake", "sha3"]
k12 = []
keccak = []
kmac = ["cshake"]
parallel_hash = ["cshake"]
sha3 = []
shake = []
sp800 = ["cshake", "kmac", "tuple_hash"]
tuple_hash = ["cshake"]
121 changes: 121 additions & 0 deletions crypto/tiny-keccak/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
Creative Commons Legal Code

CC0 1.0 Universal

CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.

Statement of Purpose

The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").

Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.

For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.

1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:

i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.

2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.

3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.

4. Limitations and Disclaimers.

a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.
Loading
Loading