Skip to content

Commit

Permalink
feat(prt-rollups): add integration test with fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenctw committed Dec 8, 2024
1 parent bb95715 commit d72610f
Show file tree
Hide file tree
Showing 56 changed files with 1,233 additions and 310 deletions.
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ target/
snapshots/
common-rs/Cargo.lock
prt/client-rs/Cargo.lock
prt/lua_poc/outputs/
prt/lua_poc/pixels/
prt/tests/compute/outputs/
prt/tests/compute/pixels/
node_modules
**/contract-bindings/src/contract
**/contract-bindings/Cargo.lock
15 changes: 15 additions & 0 deletions cartesi-rollups/contracts/deploy_anvil.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env bash

set -euo pipefail

INITIAL_HASH=`xxd -p -c32 "${MACHINE_PATH}/hash"`

export PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80

forge script \
script/DaveConsensus.s.sol \
--fork-url "http://127.0.0.1:8545" \
--broadcast \
--sig "run(bytes32)" \
"${INITIAL_HASH}" \
-vvvv
2 changes: 2 additions & 0 deletions cartesi-rollups/contracts/foundry.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,6 @@ allow_paths = [
'../../machine/step/',
]

solc-version = "0.8.27"

# See more config options https://github.com/foundry-rs/foundry/blob/master/crates/config/README.md#all-options
26 changes: 26 additions & 0 deletions cartesi-rollups/contracts/script/DaveConsensus.s.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)

pragma solidity ^0.8.17;

import {Script} from "forge-std/Script.sol";

import {Machine} from "prt-contracts/Machine.sol";

import "prt-contracts/tournament/factories/MultiLevelTournamentFactory.sol";
import "rollups-contracts/inputs/InputBox.sol";
import "src/DaveConsensus.sol";

contract DaveConcensusScript is Script {
function run(Machine.Hash initialHash) external {
vm.startBroadcast(vm.envUint("PRIVATE_KEY"));

InputBox inputBox = new InputBox();
MultiLevelTournamentFactory factory = new MultiLevelTournamentFactory(
new TopTournamentFactory(), new MiddleTournamentFactory(), new BottomTournamentFactory()
);
new DaveConsensus(inputBox, address(0x0), factory, initialHash);

vm.stopBroadcast();
}
}
1 change: 1 addition & 0 deletions cartesi-rollups/node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,6 @@ clap = { version = "4.5.7", features = ["derive", "env"] }
clap_derive = "=4.5.13"
futures = "0.3"
log = "0.4"
num-traits = "0.2.19"
thiserror = "1.0"
tokio = { version = "1", features = ["full"] }
2 changes: 1 addition & 1 deletion cartesi-rollups/node/Dockerfile.test
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ WORKDIR /app

RUN wget https://github.com/cartesi/image-kernel/releases/download/v0.20.0/linux-6.5.13-ctsi-1-v0.20.0.bin \
-O ./linux.bin
RUN wget https://github.com/cartesi/machine-emulator-tools/releases/download/v0.15.0/rootfs-tools-v0.15.0.ext2 \
RUN wget https://github.com/cartesi/machine-emulator-tools/releases/download/v0.16.1/rootfs-tools-v0.16.1.ext2 \
-O ./rootfs.ext2

RUN cartesi-machine --ram-image=./linux.bin \
Expand Down
11 changes: 6 additions & 5 deletions cartesi-rollups/node/blockchain-reader/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@ repository = { workspace = true }

[dependencies]
rollups-state-manager = { workspace = true }
alloy = { workspace = true }
async-recursion = { workspace = true }
cartesi-dave-contracts = { workspace = true }
cartesi-rollups-contracts = { workspace = true }

alloy = { workspace = true }
alloy-rpc-types-eth = "0.3.1"
async-recursion = { workspace = true }
clap = { workspace = true }
clap_derive = { workspace = true }
log = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }

alloy-rpc-types-eth = "0.3.1"
num-traits = "0.2.19"
num-traits = { workspace = true }
128 changes: 78 additions & 50 deletions cartesi-rollups/node/blockchain-reader/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::error::{ProviderErrors, Result};
use alloy::{
contract::{Error, Event},
eips::BlockNumberOrTag::Finalized,
hex::ToHexExt,
providers::{
network::primitives::BlockTransactionsKind, Provider, ProviderBuilder, RootProvider,
},
Expand All @@ -17,8 +18,10 @@ use alloy_rpc_types_eth::Topic;
use async_recursion::async_recursion;
use clap::Parser;
use error::BlockchainReaderError;
use log::debug;
use num_traits::cast::ToPrimitive;
use std::{
iter::Peekable,
marker::{Send, Sync},
str::FromStr,
sync::Arc,
Expand All @@ -29,18 +32,21 @@ use cartesi_dave_contracts::daveconsensus::DaveConsensus::EpochSealed;
use cartesi_rollups_contracts::inputbox::InputBox::InputAdded;
use rollups_state_manager::{Epoch, Input, InputId, StateManager};

const DEVNET_CONCENSUS_ADDRESS: &str = "0x5FC8d32690cc91D4c39d9d3abcBD16989F875707";
const DEVNET_INPUT_BOX_ADDRESS: &str = "0x5FbDB2315678afecb367f032d93F642f64180aa3";

#[derive(Debug, Clone, Parser)]
#[command(name = "cartesi_rollups_config")]
#[command(about = "Addresses of Cartesi Rollups")]
pub struct AddressBook {
/// address of app
#[arg(long, env)]
#[arg(long, env, default_value_t = Address::ZERO)]
app: Address,
/// address of Dave consensus
#[arg(long, env)]
#[arg(long, env, default_value = DEVNET_CONCENSUS_ADDRESS)]
pub consensus: Address,
/// address of input box
#[arg(long, env)]
#[arg(long, env, default_value = DEVNET_INPUT_BOX_ADDRESS)]
input_box: Address,
}

Expand Down Expand Up @@ -85,9 +91,11 @@ where
pub async fn start(&mut self) -> Result<(), SM> {
loop {
let current_block = self.provider.latest_finalized_block().await?;
self.advance(self.prev_block, current_block).await?;
self.prev_block = current_block;

if current_block > self.prev_block {
self.advance(self.prev_block, current_block).await?;
self.prev_block = current_block;
}
tokio::time::sleep(self.sleep_duration).await;
}
}
Expand Down Expand Up @@ -116,13 +124,23 @@ where
.collect_sealed_epochs(prev_block, current_block)
.await?;

let last_sealed_epoch_opt = self
.state_manager
.last_sealed_epoch()
.map_err(|e| BlockchainReaderError::StateManagerError(e))?;
let mut merged_sealed_epochs = Vec::new();
if let Some(last_sealed_epoch) = last_sealed_epoch_opt {
merged_sealed_epochs.push(last_sealed_epoch);
}
merged_sealed_epochs.extend(sealed_epochs.clone());
let merged_sealed_epochs_iter = merged_sealed_epochs
.iter()
.collect::<Vec<&Epoch>>()
.into_iter();

// read inputs from blockchain
let inputs = self
.collect_inputs(
prev_block,
current_block,
sealed_epochs.iter().collect::<Vec<&Epoch>>().into_iter(),
)
.collect_inputs(prev_block, current_block, merged_sealed_epochs_iter)
.await?;

Ok((inputs, sealed_epochs))
Expand All @@ -144,18 +162,25 @@ where
)
.await?
.iter()
.map(|e| Epoch {
epoch_number: e
.0
.epochNumber
.to_u64()
.expect("fail to convert epoch number"),
epoch_boundary: e
.0
.blockNumberUpperBound
.to_u64()
.expect("fail to convert epoch boundary"),
root_tournament: e.0.tournament.to_string(),
.map(|e| {
let epoch = Epoch {
epoch_number: e
.0
.epochNumber
.to_u64()
.expect("fail to convert epoch number"),
epoch_boundary: e
.0
.blockNumberUpperBound
.to_u64()
.expect("fail to convert epoch boundary"),
root_tournament: e.0.tournament.to_string(),
};
debug!(
"epoch received: epoch_number {}, epoch_boundary {}, root_tournament {}",
epoch.epoch_number, epoch.epoch_boundary, epoch.root_tournament
);
epoch
})
.collect())
}
Expand Down Expand Up @@ -193,61 +218,64 @@ where
};

let mut inputs = vec![];
let mut input_events_iter = input_events.iter();
let mut input_events_peekable = input_events.iter().peekable();
for epoch in sealed_epochs_iter {
if last_epoch_number > epoch.epoch_number {
continue;
}
// iterate through newly sealed epochs, fill in the inputs accordingly
let inputs_of_epoch = self
.construct_input_ids(
epoch.epoch_number,
epoch.epoch_boundary,
&mut next_input_index_in_epoch,
&mut input_events_iter,
)
.await;
let inputs_of_epoch = self.construct_input_ids(
epoch.epoch_number,
epoch.epoch_boundary,
&mut next_input_index_in_epoch,
&mut input_events_peekable,
);

inputs.extend(inputs_of_epoch);
last_epoch_number = epoch.epoch_number + 1;
}

// all remaining inputs belong to an epoch that's not sealed yet
let inputs_of_epoch = self
.construct_input_ids(
last_epoch_number,
u64::MAX,
&mut next_input_index_in_epoch,
&mut input_events_iter,
)
.await;
let inputs_of_epoch = self.construct_input_ids(
last_epoch_number,
u64::MAX,
&mut next_input_index_in_epoch,
&mut input_events_peekable,
);

inputs.extend(inputs_of_epoch);

Ok(inputs)
}

async fn construct_input_ids(
fn construct_input_ids<'a>(
&self,
epoch_number: u64,
epoch_boundary: u64,
next_input_index_in_epoch: &mut u64,
input_events_iter: &mut impl Iterator<Item = &(InputAdded, u64)>,
input_events_peekable: &mut Peekable<impl Iterator<Item = &'a (InputAdded, u64)>>,
) -> Vec<Input> {
let mut inputs = vec![];

while input_events_iter
.peekable()
.peek()
.expect("fail to get peek next input")
.1
< epoch_boundary
{
while let Some(input_added) = input_events_peekable.peek() {
if input_added.1 >= epoch_boundary {
break;
}
let input = Input {
id: InputId {
epoch_number,
input_index_in_epoch: *next_input_index_in_epoch,
},
data: input_events_iter.next().unwrap().0.input.to_vec(),
data: input_added.0.input.to_vec(),
};

debug!(
"input received: epoch_number {}, input_index {}, data 0x{}",
input.id.epoch_number,
input.id.input_index_in_epoch,
input.data.encode_hex()
);

input_events_peekable.next();
*next_input_index_in_epoch += 1;
inputs.push(input);
}
Expand Down
1 change: 1 addition & 0 deletions cartesi-rollups/node/compute-runner/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ cartesi-prt-core = { workspace = true }
rollups-state-manager = { workspace = true }

alloy = { workspace = true }
log = { workspace = true }
Loading

0 comments on commit d72610f

Please sign in to comment.