Skip to content
This repository has been archived by the owner on Mar 12, 2024. It is now read-only.

Commit

Permalink
feat(advance-runner): get off-chain machine hash
Browse files Browse the repository at this point in the history
  • Loading branch information
torives committed Aug 1, 2023
1 parent a3c403f commit dccc3a7
Show file tree
Hide file tree
Showing 5 changed files with 110 additions and 3 deletions.
10 changes: 10 additions & 0 deletions offchain/advance-runner/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ pub enum RunnerError<SnapError: snafu::Error + 'static> {
got
))]
ParentIdMismatchError { expected: String, got: String },

#[snafu(display("failed to get hash from snapshot "))]
GetSnapshotHashError { source: SnapError },
}

type Result<T, SnapError> = std::result::Result<T, RunnerError<SnapError>>;
Expand Down Expand Up @@ -127,6 +130,13 @@ impl<Snap: SnapshotManager + std::fmt::Debug + 'static> Runner<Snap> {
.context(GetLatestSnapshotSnafu)?;
tracing::info!(?snapshot, "got latest snapshot");

let offchain_hash = self
.snapshot_manager
.get_template_hash(&snapshot)
.await
.context(GetSnapshotHashSnafu)?;
tracing::info!(?offchain_hash, "got snapshot hash");

let event_id = self
.broker
.find_previous_finish_epoch(snapshot.epoch)
Expand Down
9 changes: 9 additions & 0 deletions offchain/advance-runner/src/snapshot/disabled.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
// specific language governing permissions and limitations under the License.

use super::{Snapshot, SnapshotManager};
use rollups_events::Hash;

#[derive(Debug)]
pub struct SnapshotDisabled {}
Expand Down Expand Up @@ -50,4 +51,12 @@ impl SnapshotManager for SnapshotDisabled {
tracing::trace!("snapshots disabled; ignoring");
Ok(())
}

async fn get_template_hash(
&self,
_: &Snapshot,
) -> Result<Hash, SnapshotDisabledError> {
tracing::trace!("snapshots disabled; returning default");
Ok(Hash::default())
}
}
81 changes: 80 additions & 1 deletion offchain/advance-runner/src/snapshot/fs_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,18 @@
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.

use rollups_events::{Hash, HASH_SIZE};
use snafu::{ensure, OptionExt, ResultExt, Snafu};
use std::collections::HashSet;
use std::fs;
use std::fs::{self, File};
use std::io::Read;
use std::path::{Path, PathBuf};

use super::config::FSManagerConfig;
use super::{Snapshot, SnapshotManager};

const HASH_FILE: &str = "hash";

#[derive(Debug, Snafu)]
pub enum FSSnapshotError {
#[snafu(display("failed to follow latest symlink"))]
Expand Down Expand Up @@ -75,6 +79,18 @@ pub enum FSSnapshotError {
path: PathBuf,
source: std::io::Error,
},

#[snafu(display("failed to open hash file for snapshot ({})", path.display()))]
HashNotFoundError {
path: PathBuf,
source: std::io::Error,
},

#[snafu(display("failed to read hash file for snapshot ({})", path.display()))]
ReadHashError {
path: PathBuf,
source: std::io::Error,
},
}

#[derive(Debug)]
Expand Down Expand Up @@ -204,6 +220,22 @@ impl SnapshotManager for FSSnapshotManager {

Ok(())
}

//TODO: logs
async fn get_template_hash(
&self,
snapshot: &Snapshot,
) -> Result<Hash, FSSnapshotError> {
let path = snapshot.path.with_file_name(HASH_FILE);
let file = File::open(path.clone())
.context(HashNotFoundSnafu { path: path.clone() })?;

let mut buffer = [0_u8; HASH_SIZE];
file.take(HASH_SIZE as u64)
.read(&mut buffer)
.context(ReadHashSnafu { path: path.clone() })?;
Ok(Hash::new(buffer))
}
}

fn encode_filename(epoch: u64, processed_input_count: u64) -> String {
Expand Down Expand Up @@ -534,4 +566,51 @@ mod tests {
state.tempdir.path().join("2_2"),
);
}

#[test_log::test(tokio::test)]
async fn test_it_gets_snapshot_hash() {
let state = TestState::setup();
let path = state.create_snapshot("0_0");
let hash_path = path.with_file_name(HASH_FILE);
let hash = [
160, 170, 75, 88, 113, 141, 144, 31, 252, 78, 159, 6, 79, 114, 6,
16, 196, 49, 44, 208, 62, 83, 66, 97, 4, 151, 159, 105, 124, 85,
51, 87,
];
fs::write(hash_path, hash).expect("should write hash to file");

let snap = Snapshot {
epoch: 0,
processed_input_count: 0,
path,
};

assert_eq!(
state
.manager
.get_template_hash(&snap)
.await
.expect("get template hash should work"),
Hash::new(hash)
);
}

#[test_log::test(tokio::test)]
async fn test_it_fails_to_get_hash_when_hash_file_does_not_exist() {
let state = TestState::setup();
let path = state.create_snapshot("0_0");
let snap = Snapshot {
epoch: 0,
processed_input_count: 0,
path,
};

let err = state
.manager
.get_template_hash(&snap)
.await
.expect_err("get template hash should fail");

assert!(matches!(err, FSSnapshotError::HashNotFoundError { .. }))
}
}
11 changes: 10 additions & 1 deletion offchain/advance-runner/src/snapshot/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.

use rollups_events::Hash;
use std::path::PathBuf;

pub mod config;
pub mod disabled;
pub mod fs_manager;

//TODO: improve this description. Create a Metadata struct maybe?
/// Cartesi Machine snapshot description
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Snapshot {
pub path: PathBuf,
pub epoch: u64,
Expand All @@ -31,6 +33,7 @@ pub trait SnapshotManager {
/// Get the most recent snapshot
async fn get_latest(&self) -> Result<Snapshot, Self::Error>;

//TODO: maybe rename to new_empty_snapshot?
/// Get the target storage directory for the snapshot
async fn get_storage_directory(
&self,
Expand All @@ -40,4 +43,10 @@ pub trait SnapshotManager {

/// Set the most recent snapshot
async fn set_latest(&self, snapshot: Snapshot) -> Result<(), Self::Error>;

/// Get the snapshot's template hash
async fn get_template_hash(
&self,
snapshot: &Snapshot,
) -> Result<Hash, Self::Error>;
}
2 changes: 1 addition & 1 deletion offchain/rollups-events/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub const ADDRESS_SIZE: usize = 20;
pub const HASH_SIZE: usize = 32;

/// A binary array that is converted to a hex string when serialized
#[derive(Clone, Hash, Eq, PartialEq)]
#[derive(Clone, Hash, Eq, PartialEq, PartialOrd, Ord)]
pub struct HexArray<const N: usize>([u8; N]);

impl<const N: usize> HexArray<N> {
Expand Down

0 comments on commit dccc3a7

Please sign in to comment.