Skip to content

Commit

Permalink
migrated to felt
Browse files Browse the repository at this point in the history
  • Loading branch information
matzayonc committed Aug 1, 2024
1 parent 8ff1d40 commit dd9274e
Show file tree
Hide file tree
Showing 8 changed files with 85 additions and 96 deletions.
24 changes: 12 additions & 12 deletions proof-parser/src/bin/register_fact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ async fn main() -> anyhow::Result<()> {
let mut hashes = vec![];

for fragment in serialized_proof.into_iter().chunks(2000).into_iter() {
let mut fragment: Vec<FieldElement> = fragment.collect();
let mut fragment: Vec<Felt> = fragment.collect();
let hash = poseidon_hash_many(&fragment);
hashes.push(hash);

Expand All @@ -92,14 +92,14 @@ async fn main() -> anyhow::Result<()> {
let tx = publish_fragment(&account, nonce, fragment).await?;
println!("Publish transaction: {tx:#x} .");

nonce += 1u64.into();
nonce += &1u64.into();
}

let calldata = vec![hashes.len().into()]
.into_iter()
.chain(hashes.into_iter())
.chain(vec![1u64.into()].into_iter())
.collect::<Vec<FieldElement>>();
.collect::<Vec<Felt>>();

let tx = verify_and_register_fact(account, calldata, nonce).await?;
println!("Verify transaction: {:#x} .", tx);
Expand All @@ -112,12 +112,12 @@ async fn main() -> anyhow::Result<()> {

async fn publish_fragment(
account: &SingleOwnerAccount<JsonRpcClient<HttpTransport>, LocalWallet>,
nonce: FieldElement,
serialized_proof: Vec<FieldElement>,
) -> anyhow::Result<FieldElement> {
nonce: Felt,
serialized_proof: Vec<Felt>,
) -> anyhow::Result<Felt> {
let tx = account
.execute(vec![Call {
to: FieldElement::from_hex_be(FACT_REGISTRY).expect("invalid world address"),
.execute_v1(vec![Call {
to: Felt::from_hex(FACT_REGISTRY).expect("invalid world address"),
selector: get_selector_from_name("publish_fragment").expect("invalid selector"),
calldata: serialized_proof,
}])
Expand All @@ -135,11 +135,11 @@ async fn verify_and_register_fact(
account: SingleOwnerAccount<JsonRpcClient<HttpTransport>, LocalWallet>,
serialized_proof: Vec<Felt>,
nonce: Felt,
) -> anyhow::Result<FieldElement> {
) -> anyhow::Result<Felt> {
println!("Sending transaction...");
let tx = account
.execute(vec![Call {
to: Felt::from_hex_be(FACT_REGISTRY).expect("invalid world address"),
.execute_v1(vec![Call {
to: Felt::from_hex(FACT_REGISTRY).expect("invalid world address"),
selector: get_selector_from_name("verify_and_register_fact_from_fragments")
.expect("invalid selector"),
calldata: serialized_proof,
Expand All @@ -155,7 +155,7 @@ async fn verify_and_register_fact(
async fn wait_for(
account: &SingleOwnerAccount<JsonRpcClient<HttpTransport>, LocalWallet>,
tx: InvokeTransactionResult,
) -> anyhow::Result<FieldElement> {
) -> anyhow::Result<Felt> {
let start_fetching = std::time::Instant::now();
let wait_for = Duration::from_secs(360);
let execution_status = loop {
Expand Down
26 changes: 12 additions & 14 deletions proof-parser/src/json_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use anyhow::{anyhow, Context};
use num_bigint::BigUint;
use serde::Deserialize;
use serde_felt::from_felts_with_lengths;
use starknet_crypto::FieldElement;
use starknet_crypto::Felt;

use crate::{
annotations::Annotations,
Expand Down Expand Up @@ -59,11 +59,11 @@ pub struct PublicInput {
rc_max: u32,
}

pub fn bigint_to_fe(bigint: &BigUint) -> FieldElement {
FieldElement::from_hex_be(&bigint.to_str_radix(16)).unwrap()
pub fn bigint_to_fe(bigint: &BigUint) -> Felt {
Felt::from_hex(&bigint.to_str_radix(16)).unwrap()
}

pub fn bigints_to_fe(bigint: &[BigUint]) -> Vec<FieldElement> {
pub fn bigints_to_fe(bigint: &[BigUint]) -> Vec<Felt> {
bigint.iter().map(bigint_to_fe).collect()
}

Expand Down Expand Up @@ -176,7 +176,7 @@ impl ProofJSON {
public_input: PublicInput,
// z: BigUint,
// alpha: BigUint,
) -> anyhow::Result<CairoPublicInput<FieldElement>> {
) -> anyhow::Result<CairoPublicInput<Felt>> {
let continuous_page_headers = vec![];
// Self::continuous_page_headers(&public_input.public_memory, z, alpha)?; this line does for now anyway
let main_page = Self::main_page(&public_input.public_memory)?;
Expand All @@ -187,8 +187,7 @@ impl ProofJSON {
.map(|e| {
Ok((
e.0,
FieldElement::from_hex_be(&e.1.to_str_radix(16))
.context("Invalid dynamic param")?,
Felt::from_hex(&e.1.to_str_radix(16)).context("Invalid dynamic param")?,
))
})
.collect::<anyhow::Result<_>>()?;
Expand All @@ -199,10 +198,9 @@ impl ProofJSON {
stop_ptr: s.stop_ptr,
})
.collect::<Vec<_>>();
let layout =
FieldElement::from_hex_be(&prefix_hex::encode(public_input.layout.bytes_encode()))?;
let layout = Felt::from_hex(&prefix_hex::encode(public_input.layout.bytes_encode()))?;
let (padding_addr, padding_value) = match public_input.public_memory.first() {
Some(m) => (m.address, FieldElement::from_hex_be(&m.value)?),
Some(m) => (m.address, Felt::from_hex(&m.value)?),
None => anyhow::bail!("Invalid public memory"),
};
Ok(CairoPublicInput {
Expand All @@ -225,14 +223,14 @@ impl ProofJSON {

fn main_page(
public_memory: &[PublicMemoryElement],
) -> anyhow::Result<Vec<PublicMemoryCell<FieldElement>>> {
) -> anyhow::Result<Vec<PublicMemoryCell<Felt>>> {
public_memory
.iter()
.filter(|m| m.page == 0)
.map(|m| {
Ok(PublicMemoryCell {
address: m.address,
value: FieldElement::from_hex_be(&m.value).context("Invalid memory value")?,
value: Felt::from_hex(&m.value).context("Invalid memory value")?,
})
})
.collect::<anyhow::Result<Vec<_>>>()
Expand Down Expand Up @@ -286,15 +284,15 @@ impl ProofJSON {
}

#[derive(Debug)]
struct HexProof(Vec<FieldElement>);
struct HexProof(Vec<Felt>);

impl TryFrom<&str> for HexProof {
type Error = anyhow::Error;
fn try_from(value: &str) -> anyhow::Result<Self> {
let hex: Vec<u8> = prefix_hex::decode(value).map_err(|_| anyhow!("Invalid hex"))?;
let mut result = vec![];
for chunk in hex.chunks(32) {
result.push(FieldElement::from_byte_slice_be(chunk)?);
result.push(Felt::from_bytes_be_slice(chunk));
}

Ok(HexProof(result))
Expand Down
7 changes: 2 additions & 5 deletions proof-parser/src/output.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use starknet_crypto::poseidon_hash_many;
use starknet_types_core::felt::Felt;
use std::collections::HashMap;
use std::convert::TryInto;
use starknet_crypto::{poseidon_hash_many, Felt};

use crate::StarkProof;

Expand Down Expand Up @@ -30,7 +27,7 @@ impl StarkProof {
let program_output = self.public_input.main_page[start..end]
.iter()
.map(|cell| cell.value)
.collect_vec();
.collect();

// Calculate the Poseidon hash of the program output
let program_output_hash = poseidon_hash_many(&program_output);
Expand Down
7 changes: 3 additions & 4 deletions proof-parser/src/program.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use starknet_crypto::poseidon_hash_many;
use starknet_types_core::felt::Felt;
use starknet_crypto::{poseidon_hash_many, Felt};
use std::collections::HashMap;

use crate::StarkProof;
Expand Down Expand Up @@ -43,8 +42,8 @@ impl StarkProof {
.map(|el| (el.address, el.value))
.collect::<HashMap<_, _>>();

let program: Vec<FieldElement> = (start..end)
.map(|addr| *main_page_map.get(&addr).unwrap_or(&FieldElement::ZERO))
let program: Vec<Felt> = (start..end)
.map(|addr| *main_page_map.get(&addr).unwrap_or(&Felt::ZERO))
.collect();

// Calculate the Poseidon hash of the program output
Expand Down
50 changes: 25 additions & 25 deletions proof-parser/src/stark_proof.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use starknet_crypto::FieldElement;

use serde_felt::{deserialize_montgomery_vec, to_felts_with_options, SerializerOptions};
use starknet_crypto::Felt;

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct StarkProof {
pub config: StarkConfig,
pub public_input: CairoPublicInput<FieldElement>,
pub public_input: CairoPublicInput<Felt>,
pub unsent_commitment: StarkUnsentCommitment,
pub witness: StarkWitnessReordered,
}
Expand Down Expand Up @@ -60,52 +60,52 @@ pub struct ProofOfWorkConfig {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StarkUnsentCommitment {
pub traces: TracesUnsentCommitment,
pub composition: FieldElement,
pub oods_values: Vec<FieldElement>,
pub composition: Felt,
pub oods_values: Vec<Felt>,
pub fri: FriUnsentCommitment,
pub proof_of_work_nonce: FieldElement,
pub proof_of_work_nonce: Felt,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TracesUnsentCommitment {
pub original: FieldElement,
pub interaction: FieldElement,
pub original: Felt,
pub interaction: Felt,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FriUnsentCommitment {
pub inner_layers: Vec<FieldElement>,
pub last_layer_coefficients: Vec<FieldElement>,
pub inner_layers: Vec<Felt>,
pub last_layer_coefficients: Vec<Felt>,
}

#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct StarkWitness {
#[serde(deserialize_with = "deserialize_montgomery_vec")]
pub original_leaves: Vec<FieldElement>,
pub original_authentications: Vec<FieldElement>,
pub original_leaves: Vec<Felt>,
pub original_authentications: Vec<Felt>,
#[serde(deserialize_with = "deserialize_montgomery_vec")]
pub interaction_leaves: Vec<FieldElement>,
pub interaction_authentications: Vec<FieldElement>,
pub interaction_leaves: Vec<Felt>,
pub interaction_authentications: Vec<Felt>,
#[serde(deserialize_with = "deserialize_montgomery_vec")]
pub composition_leaves: Vec<FieldElement>,
pub composition_authentications: Vec<FieldElement>,
pub composition_leaves: Vec<Felt>,
pub composition_authentications: Vec<Felt>,
pub fri_witness: FriWitness,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct StarkWitnessReordered {
#[serde(serialize_with = "double_len_serialize")]
pub original_leaves: Vec<FieldElement>,
pub original_leaves: Vec<Felt>,
#[serde(serialize_with = "double_len_serialize")]
pub interaction_leaves: Vec<FieldElement>,
pub interaction_leaves: Vec<Felt>,
#[serde(serialize_with = "double_len_serialize")]
pub original_authentications: Vec<FieldElement>,
pub original_authentications: Vec<Felt>,
#[serde(serialize_with = "double_len_serialize")]
pub interaction_authentications: Vec<FieldElement>,
pub interaction_authentications: Vec<Felt>,
#[serde(serialize_with = "double_len_serialize")]
pub composition_leaves: Vec<FieldElement>,
pub composition_leaves: Vec<Felt>,
#[serde(serialize_with = "double_len_serialize")]
pub composition_authentications: Vec<FieldElement>,
pub composition_authentications: Vec<Felt>,
pub fri_witness: FriWitness,
}

Expand All @@ -123,7 +123,7 @@ impl From<StarkWitness> for StarkWitnessReordered {
}
}

pub fn double_len_serialize<S>(value: &[FieldElement], serializer: S) -> Result<S::Ok, S::Error>
pub fn double_len_serialize<S>(value: &[Felt], serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
Expand All @@ -148,8 +148,8 @@ pub struct FriWitness {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FriLayerWitness {
#[serde(deserialize_with = "deserialize_montgomery_vec")]
pub leaves: Vec<FieldElement>,
pub table_witness: Vec<FieldElement>,
pub leaves: Vec<Felt>,
pub table_witness: Vec<Felt>,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
Expand Down Expand Up @@ -182,7 +182,7 @@ pub struct SegmentInfo {
}

impl StarkProof {
pub fn to_felts(&self) -> Vec<FieldElement> {
pub fn to_felts(&self) -> Vec<Felt> {
to_felts_with_options(
self,
SerializerOptions {
Expand Down
20 changes: 10 additions & 10 deletions serde-felt/src/deser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,39 @@ use std::collections::HashMap;

use serde::de::{self, DeserializeSeed, IntoDeserializer, MapAccess, SeqAccess, Visitor};
use serde::Deserialize;
use starknet_crypto::FieldElement;
use starknet_crypto::Felt;

use super::error::{Error, Result};

pub type Lengths = HashMap<String, Vec<usize>>;

pub struct Deserializer<'de> {
input: &'de [FieldElement],
input: &'de [Felt],
lengths: Option<Lengths>, // Workaround around serde limit to 32 element tuples.
next_length: Option<usize>,
}

impl<'de> Deserializer<'de> {
pub fn peek(&self) -> Result<FieldElement> {
pub fn peek(&self) -> Result<Felt> {
self.input.first().copied().ok_or(Error::NoDataLeft)
}

pub fn take(&mut self) -> Result<FieldElement> {
pub fn take(&mut self) -> Result<Felt> {
let el = self.peek()?;
self.input = &self.input[1..];

Ok(el)
}

pub fn from_felts(input: &'de Vec<FieldElement>) -> Self {
pub fn from_felts(input: &'de Vec<Felt>) -> Self {
Deserializer {
input,
lengths: None,
next_length: None,
}
}

pub fn from_felts_with_lengths(input: &'de Vec<FieldElement>, lengths: Lengths) -> Self {
pub fn from_felts_with_lengths(input: &'de Vec<Felt>, lengths: Lengths) -> Self {
Deserializer {
input,
lengths: Some(lengths),
Expand Down Expand Up @@ -67,21 +67,21 @@ impl<'de> Deserializer<'de> {
}
}

pub fn from_felts<'a, T>(s: &'a Vec<FieldElement>) -> Result<T>
pub fn from_felts<'a, T>(s: &'a Vec<Felt>) -> Result<T>
where
T: Deserialize<'a>,
{
from_felts_inner(s, None)
}

pub fn from_felts_with_lengths<'a, T>(s: &'a Vec<FieldElement>, lengths: Lengths) -> Result<T>
pub fn from_felts_with_lengths<'a, T>(s: &'a Vec<Felt>, lengths: Lengths) -> Result<T>
where
T: Deserialize<'a>,
{
from_felts_inner(s, Some(lengths))
}

fn from_felts_inner<'a, T>(s: &'a Vec<FieldElement>, lengths: Option<Lengths>) -> Result<T>
fn from_felts_inner<'a, T>(s: &'a Vec<Felt>, lengths: Option<Lengths>) -> Result<T>
where
T: Deserialize<'a>,
{
Expand Down Expand Up @@ -224,7 +224,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
where
V: Visitor<'de>,
{
visitor.visit_string(self.take()?.to_string())
visitor.visit_string(self.take()?.to_hex_string())
}

fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
Expand Down
Loading

0 comments on commit dd9274e

Please sign in to comment.