Skip to content

Commit

Permalink
Merge pull request #77 from ethereum-optimism/cl/rust-fmt-toml
Browse files Browse the repository at this point in the history
  • Loading branch information
refcell authored Apr 3, 2024
2 parents d442891 + 23c3d1b commit 05a4a10
Show file tree
Hide file tree
Showing 65 changed files with 484 additions and 890 deletions.
6 changes: 3 additions & 3 deletions crates/common/src/asterisc/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ pub struct AsteriscIO;
/// See https://jborza.com/post/2021-05-11-riscv-linux-syscalls/
///
/// **Note**: This is not an exhaustive list of system calls available to the `client` program,
/// only the ones necessary for the [BasicKernelInterface] trait implementation. If an extension trait for
/// the [BasicKernelInterface] trait is created for the `asterisc` kernel, this list should be extended
/// accordingly.
/// only the ones necessary for the [BasicKernelInterface] trait implementation. If an extension
/// trait for the [BasicKernelInterface] trait is created for the `asterisc` kernel, this list
/// should be extended accordingly.
#[repr(u32)]
pub(crate) enum SyscallNumber {
/// Sets the Exited and ExitCode states to true and $a0 respectively.
Expand Down
4 changes: 2 additions & 2 deletions crates/common/src/asterisc/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! This module contains raw syscall bindings for the `riscv64gc` target architecture, as well as a high-level
//! implementation of the [crate::BasicKernelInterface] trait for the `asterisc` kernel.
//! This module contains raw syscall bindings for the `riscv64gc` target architecture, as well as a
//! high-level implementation of the [crate::BasicKernelInterface] trait for the `asterisc` kernel.
pub(crate) mod io;
mod syscall;
10 changes: 5 additions & 5 deletions crates/common/src/cannon/io.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::{cannon::syscall, BasicKernelInterface, FileDescriptor, RegisterSize};
use anyhow::{anyhow, Result};

/// Concrete implementation of the [BasicKernelInterface] trait for the `MIPS32rel1` target architecture. Exposes a safe
/// interface for performing IO operations within the FPVM kernel.
/// Concrete implementation of the [BasicKernelInterface] trait for the `MIPS32rel1` target
/// architecture. Exposes a safe interface for performing IO operations within the FPVM kernel.
#[derive(Debug)]
pub struct CannonIO;

Expand All @@ -11,9 +11,9 @@ pub struct CannonIO;
/// See [Cannon System Call Specification](https://specs.optimism.io/experimental/fault-proof/cannon-fault-proof-vm.html#syscalls)
///
/// **Note**: This is not an exhaustive list of system calls available to the `client` program,
/// only the ones necessary for the [BasicKernelInterface] trait implementation. If an extension trait for
/// the [BasicKernelInterface] trait is created for the `Cannon` kernel, this list should be extended
/// accordingly.
/// only the ones necessary for the [BasicKernelInterface] trait implementation. If an extension
/// trait for the [BasicKernelInterface] trait is created for the `Cannon` kernel, this list should
/// be extended accordingly.
#[repr(u32)]
pub(crate) enum SyscallNumber {
/// Sets the Exited and ExitCode states to true and $a0 respectively.
Expand Down
4 changes: 2 additions & 2 deletions crates/common/src/cannon/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! This module contains raw syscall bindings for the `MIPS32r2` target architecture, as well as a high-level
//! implementation of the [crate::BasicKernelInterface] trait for the `Cannon` kernel.
//! This module contains raw syscall bindings for the `MIPS32r2` target architecture, as well as a
//! high-level implementation of the [crate::BasicKernelInterface] trait for the `Cannon` kernel.
pub(crate) mod io;
mod syscall;
22 changes: 8 additions & 14 deletions crates/common/src/cannon/syscall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,7 @@ pub(crate) unsafe fn syscall1(n: RegisterSize, arg1: RegisterSize) -> RegisterSi
options(nostack, preserves_flags)
);

(err == 0)
.then_some(ret)
.unwrap_or_else(|| ret.wrapping_neg())
(err == 0).then_some(ret).unwrap_or_else(|| ret.wrapping_neg())
}

/// Issues a raw system call with 3 arguments. (e.g. read, write)
Expand Down Expand Up @@ -97,16 +95,12 @@ pub(crate) unsafe fn syscall3(
options(nostack, preserves_flags)
);

let value = (err == 0)
.then_some(ret)
.unwrap_or_else(|| ret.wrapping_neg());
let value = (err == 0).then_some(ret).unwrap_or_else(|| ret.wrapping_neg());

(value <= -4096isize as RegisterSize)
.then_some(value)
.ok_or_else(|| {
// Truncation of the error value is guaranteed to never occur due to
// the above check. This is the same check that musl uses:
// https://git.musl-libc.org/cgit/musl/tree/src/internal/syscall_ret.c?h=v1.1.15
-(value as i32)
})
(value <= -4096isize as RegisterSize).then_some(value).ok_or_else(|| {
// Truncation of the error value is guaranteed to never occur due to
// the above check. This is the same check that musl uses:
// https://git.musl-libc.org/cgit/musl/tree/src/internal/syscall_ret.c?h=v1.1.15
-(value as i32)
})
}
8 changes: 4 additions & 4 deletions crates/common/src/executor.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
//! This module contains utilities for handling async functions in the no_std environment. This allows for usage of
//! async/await syntax for futures in a single thread.
//! This module contains utilities for handling async functions in the no_std environment. This
//! allows for usage of async/await syntax for futures in a single thread.
use alloc::boxed::Box;
use core::{
future::Future,
task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
};

/// This function busy waits on a future until it is ready. It uses a no-op waker to poll the future in a
/// thread-blocking loop.
/// This function busy waits on a future until it is ready. It uses a no-op waker to poll the future
/// in a thread-blocking loop.
pub fn block_on<T>(f: impl Future<Output = T>) -> T {
let mut f = Box::pin(f);

Expand Down
11 changes: 4 additions & 7 deletions crates/common/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,22 +85,19 @@ mod native_io {
// forget the file descriptor so that the `Drop` impl doesn't close it.
std::mem::forget(file);

n.try_into()
.map_err(|_| anyhow!("Failed to convert usize to RegisterSize"))
n.try_into().map_err(|_| anyhow!("Failed to convert usize to RegisterSize"))
}

fn read(fd: FileDescriptor, buf: &mut [u8]) -> Result<RegisterSize> {
let raw_fd: RegisterSize = fd.into();
let mut file = unsafe { File::from_raw_fd(raw_fd as i32) };
let n = file
.read(buf)
.map_err(|e| anyhow!("Error reading from file descriptor: {e}"))?;
let n =
file.read(buf).map_err(|e| anyhow!("Error reading from file descriptor: {e}"))?;

// forget the file descriptor so that the `Drop` impl doesn't close it.
std::mem::forget(file);

n.try_into()
.map_err(|_| anyhow!("Failed to convert usize to RegisterSize"))
n.try_into().map_err(|_| anyhow!("Failed to convert usize to RegisterSize"))
}

fn exit(code: RegisterSize) -> ! {
Expand Down
7 changes: 1 addition & 6 deletions crates/common/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
#![doc = include_str!("../README.md")]
#![warn(
missing_debug_implementations,
missing_docs,
unreachable_pub,
rustdoc::all
)]
#![warn(missing_debug_implementations, missing_docs, unreachable_pub, rustdoc::all)]
#![deny(unused_must_use, rust_2018_idioms)]
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
#![cfg_attr(target_arch = "mips", feature(asm_experimental_arch))]
Expand Down
4 changes: 2 additions & 2 deletions crates/common/src/malloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ pub mod global_allocator {
/// This function is unsafe because the caller must ensure:
/// * The allocator has not already been initialized.
/// * The provided memory region must be valid, non-null, and not used by anything else.
/// * After aligning the start and end addresses, the size of the heap must be > 0, or the function
/// will panic.
/// * After aligning the start and end addresses, the size of the heap must be > 0, or the
/// function will panic.
pub unsafe fn init_allocator(heap_start_addr: *mut u8, heap_size: usize) {
ALLOCATOR.lock().init(heap_start_addr, heap_size)
}
Expand Down
15 changes: 8 additions & 7 deletions crates/common/src/traits/basic.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
//! Defines the [BasicKernelInterface] trait, which describes the functionality of several system calls inside of
//! the FPVM kernel.
//! Defines the [BasicKernelInterface] trait, which describes the functionality of several system
//! calls inside of the FPVM kernel.
use crate::{FileDescriptor, RegisterSize};
use anyhow::Result;

/// The [BasicKernelInterface] trait describes the functionality of several core system calls inside of
/// the FPVM kernel. Commonly, FPVMs delegate IO operations to custom file descriptors in the `client` program. It is
/// a safe wrapper around the raw system calls available to the `client` program.
/// The [BasicKernelInterface] trait describes the functionality of several core system calls inside
/// of the FPVM kernel. Commonly, FPVMs delegate IO operations to custom file descriptors in the
/// `client` program. It is a safe wrapper around the raw system calls available to the `client`
/// program.
///
/// In cases where the set of system calls defined in this trait need to be extended, an additional trait should be
/// created that extends this trait.
/// In cases where the set of system calls defined in this trait need to be extended, an additional
/// trait should be created that extends this trait.
pub trait BasicKernelInterface {
/// Write the given buffer to the given file descriptor.
fn write(fd: FileDescriptor, buf: &[u8]) -> Result<RegisterSize>;
Expand Down
7 changes: 1 addition & 6 deletions crates/derive/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
#![doc = include_str!("../README.md")]
#![warn(
missing_debug_implementations,
missing_docs,
unreachable_pub,
rustdoc::all
)]
#![warn(missing_debug_implementations, missing_docs, unreachable_pub, rustdoc::all)]
#![deny(unused_must_use, rust_2018_idioms)]
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
#![no_std]
Expand Down
61 changes: 24 additions & 37 deletions crates/derive/src/stages/channel_bank.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ use crate::{
traits::{ChainProvider, DataAvailabilityProvider, ResettableStage},
types::{BlockInfo, Channel, Frame, RollupConfig, StageError, StageResult, SystemConfig},
};
use alloc::sync::Arc;
use alloc::{boxed::Box, collections::VecDeque};
use alloc::{boxed::Box, collections::VecDeque, sync::Arc};
use alloy_primitives::Bytes;
use anyhow::anyhow;
use async_trait::async_trait;
Expand All @@ -23,8 +22,8 @@ use hashbrown::HashMap;
/// Note: we prune before we ingest data.
/// As we switch between ingesting data & reading, the prune step occurs at an odd point
/// Specifically, the channel bank is not allowed to become too large between successive calls
/// to `IngestData`. This means that we can do an ingest and then do a read while becoming too large.
/// [ChannelBank] buffers channel frames, and emits full channel data
/// to `IngestData`. This means that we can do an ingest and then do a read while becoming too
/// large. [ChannelBank] buffers channel frames, and emits full channel data
#[derive(Debug)]
pub struct ChannelBank<DAP, CP>
where
Expand All @@ -48,12 +47,7 @@ where
{
/// Create a new [ChannelBank] stage.
pub fn new(cfg: RollupConfig, prev: FrameQueue<DAP, CP>) -> Self {
Self {
cfg: Arc::new(cfg),
channels: HashMap::new(),
channel_queue: VecDeque::new(),
prev,
}
Self { cfg: Arc::new(cfg), channels: HashMap::new(), channel_queue: VecDeque::new(), prev }
}

/// Returns the L1 origin [BlockInfo].
Expand All @@ -71,14 +65,8 @@ where
pub fn prune(&mut self) -> StageResult<()> {
let mut total_size = self.size();
while total_size > MAX_CHANNEL_BANK_SIZE {
let id = self
.channel_queue
.pop_front()
.ok_or(anyhow!("No channel to prune"))?;
let channel = self
.channels
.remove(&id)
.ok_or(anyhow!("Could not find channel"))?;
let id = self.channel_queue.pop_front().ok_or(anyhow!("No channel to prune"))?;
let channel = self.channels.remove(&id).ok_or(anyhow!("Could not find channel"))?;
total_size -= channel.size();
}
Ok(())
Expand Down Expand Up @@ -120,10 +108,7 @@ where
// Return an `Ok(None)` if the first channel is timed out. There may be more timed
// out channels at the head of the queue and we want to remove them all.
let first = self.channel_queue[0];
let channel = self
.channels
.get(&first)
.ok_or(anyhow!("Channel not found"))?;
let channel = self.channels.get(&first).ok_or(anyhow!("Channel not found"))?;
let origin = self.origin().ok_or(anyhow!("No origin present"))?;

// Remove all timed out channels from the front of the `channel_queue`.
Expand All @@ -133,11 +118,12 @@ where
return Ok(None);
}

// At this point we have removed all timed out channels from the front of the `channel_queue`.
// Pre-Canyon we simply check the first index.
// At this point we have removed all timed out channels from the front of the
// `channel_queue`. Pre-Canyon we simply check the first index.
// Post-Canyon we read the entire channelQueue for the first ready channel.
// If no channel is available, we return StageError::Eof.
// Canyon is activated when the first L1 block whose time >= CanyonTime, not on the L2 timestamp.
// Canyon is activated when the first L1 block whose time >= CanyonTime, not on the L2
// timestamp.
if !self.cfg.is_canyon_active(origin.timestamp) {
return self.try_read_channel_at_index(0).map(Some);
}
Expand All @@ -150,8 +136,9 @@ where
}
}

/// Pulls the next piece of data from the channel bank. Note that it attempts to pull data out of the channel bank prior to
/// loading data in (unlike most other stages). This is to ensure maintain consistency around channel bank pruning which depends upon the order
/// Pulls the next piece of data from the channel bank. Note that it attempts to pull data out
/// of the channel bank prior to loading data in (unlike most other stages). This is to
/// ensure maintain consistency around channel bank pruning which depends upon the order
/// of operations.
pub async fn next_data(&mut self) -> StageResult<Option<Bytes>> {
match self.read() {
Expand All @@ -170,15 +157,12 @@ where
Err(StageError::NotEnoughData)
}

/// Attempts to read the channel at the specified index. If the channel is not ready or timed out,
/// it will return an error.
/// Attempts to read the channel at the specified index. If the channel is not ready or timed
/// out, it will return an error.
/// If the channel read was successful, it will remove the channel from the channel queue.
fn try_read_channel_at_index(&mut self, index: usize) -> StageResult<Bytes> {
let channel_id = self.channel_queue[index];
let channel = self
.channels
.get(&channel_id)
.ok_or(anyhow!("Channel not found"))?;
let channel = self.channels.get(&channel_id).ok_or(anyhow!("Channel not found"))?;
let origin = self.origin().ok_or(anyhow!("No origin present"))?;

let timed_out = channel.open_block_number() + self.cfg.channel_timeout < origin.number;
Expand Down Expand Up @@ -210,10 +194,13 @@ where
#[cfg(test)]
mod tests {
use super::*;
use crate::stages::frame_queue::tests::new_test_frames;
use crate::stages::l1_retrieval::L1Retrieval;
use crate::stages::l1_traversal::tests::new_test_traversal;
use crate::traits::test_utils::TestDAP;
use crate::{
stages::{
frame_queue::tests::new_test_frames, l1_retrieval::L1Retrieval,
l1_traversal::tests::new_test_traversal,
},
traits::test_utils::TestDAP,
};
use alloc::vec;

#[test]
Expand Down
17 changes: 3 additions & 14 deletions crates/derive/src/stages/channel_reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,7 @@ where
{
/// Create a new [ChannelReader] stage.
pub fn new(prev: ChannelBank<DAP, CP>) -> Self {
Self {
prev,
next_batch: None,
}
Self { prev, next_batch: None }
}

/// Pulls out the next Batch from the available channel.
Expand Down Expand Up @@ -114,21 +111,13 @@ impl BatchReader {

impl From<&[u8]> for BatchReader {
fn from(data: &[u8]) -> Self {
Self {
data: Some(data.to_vec()),
decompressed: Vec::new(),
cursor: 0,
}
Self { data: Some(data.to_vec()), decompressed: Vec::new(), cursor: 0 }
}
}

impl From<Vec<u8>> for BatchReader {
fn from(data: Vec<u8>) -> Self {
Self {
data: Some(data),
decompressed: Vec::new(),
cursor: 0,
}
Self { data: Some(data), decompressed: Vec::new(), cursor: 0 }
}
}

Expand Down
Loading

0 comments on commit 05a4a10

Please sign in to comment.