Skip to content

Commit

Permalink
feat(cartesi-machine): update machine bindings
Browse files Browse the repository at this point in the history
  • Loading branch information
GCdePaula committed Jan 29, 2025
1 parent 4dc5078 commit 9bfa057
Show file tree
Hide file tree
Showing 34 changed files with 2,540 additions and 1,530 deletions.
551 changes: 305 additions & 246 deletions Cargo.lock

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,13 @@ cartesi-prt-core = { path = "prt/client-rs/core" }
cartesi-rollups-contracts = "=2.0.0-rc.13"

# eth
alloy = { version = "0.8", features = ["sol-types", "contract", "network", "reqwest", "signers", "signer-local"] }
alloy = { version = "0.8", features = ["contract", "network", "reqwest", "rpc-types", "signers", "signer-local", "sol-types"] }
ruint = "1.12"
tiny-keccak = { version = "2.0", features = ["keccak"] }

# error handling
anyhow = "1.0"
thiserror = "1.0"
thiserror = "2.0"

# async
async-recursion = "1"
Expand Down
3 changes: 1 addition & 2 deletions cartesi-rollups/node/blockchain-reader/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ cartesi-dave-contracts = { workspace = true }
cartesi-rollups-contracts = { workspace = true }

alloy = { workspace = true }
alloy-rpc-types-eth = "0.8.0"
async-recursion = { workspace = true }
clap = { workspace = true }
log = { workspace = true }
Expand All @@ -25,7 +24,7 @@ tokio = { workspace = true }
num-traits = { workspace = true }

[dev-dependencies]
alloy = { workspace = true, features = ["node-bindings"] }
alloy = { workspace = true, features = ["node-bindings", "rpc-types"] }
cartesi-dave-merkle = { workspace = true }
cartesi-prt-core = { workspace = true }
cartesi-prt-contracts = { workspace = true }
Expand Down
22 changes: 8 additions & 14 deletions cartesi-rollups/node/blockchain-reader/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,18 @@ use alloy::{
contract::{Error, Event},
eips::BlockNumberOrTag::Finalized,
hex::ToHexExt,
primitives::Address,
primitives::{Address, U256},
providers::{
network::primitives::BlockTransactionsKind, Provider, ProviderBuilder, RootProvider,
},
rpc::types::Topic,
sol_types::SolEvent,
transports::http::{reqwest::Url, Client, Http},
};
use alloy_rpc_types_eth::Topic;
use async_recursion::async_recursion;
use clap::Parser;
use error::BlockchainReaderError;
use log::{info, trace};
use num_traits::cast::ToPrimitive;
use std::{
iter::Peekable,
marker::{Send, Sync},
Expand Down Expand Up @@ -167,11 +166,11 @@ where
let epoch = Epoch {
epoch_number: e
.epochNumber
.to_u64()
.try_into()
.expect("fail to convert epoch number"),
input_index_boundary: e
.inputIndexUpperBound
.to_u64()
.try_into()
.expect("fail to convert epoch boundary"),
root_tournament: e.tournament.to_string(),
};
Expand Down Expand Up @@ -257,12 +256,7 @@ where
let mut inputs = vec![];

while let Some(input_added) = input_events_peekable.peek() {
if input_added
.index
.to_u64()
.expect("fail to convert input index")
>= input_index_boundary
{
if input_added.index >= U256::from(input_index_boundary) {
break;
}
let input = Input {
Expand Down Expand Up @@ -319,9 +313,9 @@ impl<E: SolEvent + Send + Sync> EventReader<E> {
current_finalized,
)
.await
.map_err(|err_arr| ProviderErrors(err_arr))?;
.map_err(ProviderErrors)?;

return Ok(logs);
Ok(logs)
}
}

Expand Down Expand Up @@ -362,7 +356,7 @@ impl PartitionProvider {
let mut e = Event::new_sol(&self.inner, read_from)
.from_block(start_block)
.to_block(end_block)
.event(&E::SIGNATURE);
.event(E::SIGNATURE);

if let Some(t) = topic1 {
e = e.topic1(t.clone());
Expand Down
2 changes: 1 addition & 1 deletion cartesi-rollups/node/machine-runner/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)

use cartesi_dave_merkle::DigestError;
use cartesi_machine::errors::MachineError;
use cartesi_machine::error::MachineError;
use rollups_state_manager::StateManager;

use thiserror::Error;
Expand Down
24 changes: 12 additions & 12 deletions cartesi-rollups/node/machine-runner/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ use std::{

use cartesi_dave_merkle::{Digest, DigestError, MerkleBuilder};
use cartesi_machine::{
break_reason, configuration::RuntimeConfig, hash::Hash, htif, machine::Machine,
config::runtime::RuntimeConfig,
constants::break_reason,
machine::Machine,
types::{cmio::CmioResponseReason, Hash},
};
use cartesi_prt_core::machine::constants::{LOG2_EMULATOR_SPAN, LOG2_INPUT_SPAN, LOG2_UARCH_SPAN};
use rollups_state_manager::{InputId, StateManager};
Expand Down Expand Up @@ -52,7 +55,7 @@ where
None => (initial_machine.to_string(), 0, 0),
};

let machine = Machine::load(Path::new(&snapshot), RuntimeConfig::default())?;
let machine = Machine::load(Path::new(&snapshot), &RuntimeConfig::default())?;

Ok(Self {
machine,
Expand Down Expand Up @@ -140,10 +143,7 @@ where
if state_hashes.is_empty() {
// no inputs in current epoch, add machine state hash repeatedly
let machine_state_hash = self.add_state_hash(stride_count_in_epoch)?;
state_hashes.push((
machine_state_hash.as_bytes().to_vec(),
stride_count_in_epoch,
));
state_hashes.push((machine_state_hash.to_vec(), stride_count_in_epoch));
}

let (computation_hash, total_repetitions) =
Expand Down Expand Up @@ -172,7 +172,7 @@ where
self.run_machine(big_steps_in_stride)?;

let mut i: u64 = 0;
while !self.machine.read_iflags_y()? {
while !self.machine.iflags_y()? {
self.add_state_hash(1)?;
i += 1;
self.run_machine(big_steps_in_stride)?;
Expand All @@ -184,12 +184,12 @@ where

fn feed_input(&mut self, input: &[u8]) -> Result<(), SM> {
self.machine
.send_cmio_response(htif::fromhost::ADVANCE_STATE, input)?;
.send_cmio_response(CmioResponseReason::Advance, input)?;
Ok(())
}

fn run_machine(&mut self, cycles: u64) -> Result<(), SM> {
let mcycle = self.machine.read_mcycle()?;
let mcycle = self.machine.mcycle()?;

loop {
let reason = self.machine.run(mcycle + cycles)?;
Expand All @@ -204,10 +204,10 @@ where
}

fn add_state_hash(&mut self, repetitions: u64) -> Result<Hash, SM> {
let machine_state_hash = self.machine.get_root_hash()?;
let machine_state_hash = self.machine.root_hash()?;
self.state_manager
.add_machine_state_hash(
machine_state_hash.as_bytes(),
&machine_state_hash,
self.epoch_number,
self.state_hash_index_in_epoch,
repetitions,
Expand All @@ -218,7 +218,7 @@ where
Ok(machine_state_hash)
}

fn take_snapshot(&self) -> Result<(), SM> {
fn take_snapshot(&mut self) -> Result<(), SM> {
let epoch_path = self
.state_dir
.join("snapshots")
Expand Down
4 changes: 2 additions & 2 deletions common-rs/merkle/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@ alloy = { workspace = true, features = ["sol-types"] }
ruint = { workspace = true }

hex = "0.4"
sha3 = "0.10"
thiserror = "1.0"
tiny-keccak = { workspace = true }
thiserror = { workspace = true }
50 changes: 43 additions & 7 deletions common-rs/merkle/src/digest/keccak.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,60 @@
//! Keccak256 hash for the Digest Type. It's used to hash the data in the Digest.
use sha3::{Digest as Keccak256Digest, Keccak256};
use tiny_keccak::{Hasher, Keccak};

use super::Digest;

impl Digest {
/// Computes the Keccak256 hash of the given data and returns a new Digest.
pub fn from_data(data: &[u8]) -> Digest {
let mut keccak = Keccak256::new();
let mut keccak = Keccak::v256();
keccak.update(data);
let digest: [u8; 32] = keccak.finalize().into();
let mut digest: [u8; 32] = [0; 32];
keccak.finalize(&mut digest);
Digest::from(digest)
}

/// Joins the current Digest with another Digest to create a new Digest.
pub fn join(&self, digest: &Digest) -> Digest {
let mut keccak = Keccak256::new();
keccak.update(self.data);
keccak.update(digest.data);
let digest: [u8; 32] = keccak.finalize().into();
let mut keccak = Keccak::v256();
keccak.update(&self.data);
keccak.update(&digest.data);
let mut digest: [u8; 32] = [0; 32];
keccak.finalize(&mut digest);
Digest::from(digest)
}
}

#[cfg(test)]
mod tests {
use super::Digest;

fn assert_data_eq(expected_digest_hex: &str, digest: Digest) {
assert_eq!(
Digest::from_digest_hex(expected_digest_hex).expect("invalid hex"),
digest
);
}

#[test]
fn test_from_data() {
assert_data_eq(
"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470",
Digest::from_data(&[]), // cast keccak ""
);

assert_data_eq(
"0x6228290203658fd4987e40cbb257cabf258f9c288cdee767eaba6b234a73a2f9",
Digest::from_data("bananas".as_bytes()), // cast keccak "bananas"
);
}

#[test]
fn test_join() {
assert_data_eq(
"0x4441036546894c6fcf905b48b722f6b149ec0902955a6445c63cfec478568268",
// cast keccak (cast concat-hex (cast keccak "minhas") (cast keccak "bananas"))
Digest::from_data("minhas".as_bytes()).join(&Digest::from_data("bananas".as_bytes())),
);
}
}
6 changes: 2 additions & 4 deletions common-rs/merkle/src/digest/mod.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
//! Definition of the [Digest] type and its associated methods. A digest is the output of a hash
//! function. It's used to identify the data in the MerkleTree.
use alloy::sol_types::private::B256;
use alloy::primitives::B256;
use hex::FromHex;
use std::fmt;
use thiserror::Error;

pub mod keccak;

use hex;
use thiserror::Error;

const HASH_SIZE: usize = 32;

#[derive(Error, Debug)]
Expand Down
2 changes: 1 addition & 1 deletion machine/emulator
Submodule emulator updated 215 files
2 changes: 1 addition & 1 deletion machine/rust-bindings/cartesi-machine-sys/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ link-cplusplus = "1.0"


[build-dependencies]
bindgen = "0.69"
bindgen = "0.71"
cfg-if = "1.0"

hex-literal = "0.4.1"
Expand Down
Loading

0 comments on commit 9bfa057

Please sign in to comment.