Skip to content

Commit

Permalink
feat(prt-rs): create Input and Leaf type, update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenctw committed Oct 11, 2024
1 parent 6178645 commit a986f29
Show file tree
Hide file tree
Showing 7 changed files with 118 additions and 109 deletions.
15 changes: 13 additions & 2 deletions cartesi-rollups/node/compute-runner/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::{str::FromStr, sync::Arc, time::Duration};

use cartesi_prt_core::{
arena::{BlockchainConfig, EthArenaSender},
db::dispute_state_access::{Input, Leaf},
strategy::player::Player,
};
use rollups_state_manager::StateManager;
Expand Down Expand Up @@ -41,8 +42,18 @@ where
.state_manager
.machine_state_hashes(last_sealed_epoch.epoch_number)?;
let mut player = Player::new(
inputs,
leafs,
inputs.into_iter().map(|i| Input(i)).collect(),
leafs
.into_iter()
.map(|l| {
Leaf(
l.0.as_slice()
.try_into()
.expect("fail to convert leaf from machine state hash"),
l.1,
)
})
.collect(),
&self.config,
snapshot,
Address::from_str(&last_sealed_epoch.root_tournament)
Expand Down
4 changes: 4 additions & 0 deletions common-rs/merkle/src/digest/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ impl Digest {
Self::from_digest(&data)
}

pub fn data(&self) -> [u8; 32] {
self.data
}

pub fn slice(&self) -> &[u8] {
self.data.as_slice()
}
Expand Down
110 changes: 52 additions & 58 deletions prt/prt-rs/src/db/dispute_state_access.rs
Original file line number Diff line number Diff line change
@@ -1,71 +1,31 @@
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)

use crate::db::{
sql::{dispute_data, error::*, migrations},
Input,
};
use crate::db::sql::{dispute_data, error::*, migrations};
use cartesi_dave_merkle::{Digest, MerkleBuilder, MerkleTree};

use alloy::hex as alloy_hex;
use log::info;
use rusqlite::{Connection, OpenFlags};
use serde::{Deserialize, Deserializer, Serialize};
use serde::{Deserialize, Serialize};
use std::{
fs,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};

#[derive(Debug, Serialize)]
#[derive(Debug, Serialize, Deserialize)]
pub struct InputsAndLeafs {
inputs: Vec<Vec<u8>>,
leafs: Vec<(Vec<u8>, u64)>,
#[serde(default)]
inputs: Vec<Input>,
leafs: Vec<Leaf>,
}

impl<'de> Deserialize<'de> for InputsAndLeafs {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// Create a temporary struct to deserialize the data
#[derive(Deserialize)]
struct TempInputsAndLeafs {
leafs: Vec<TempLeaf>, // Use a temporary struct for deserialization
inputs: Option<Vec<String>>, // Temporarily keep inputs as vec of String
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Input(#[serde(with = "alloy_hex::serde")] pub Vec<u8>);

#[derive(Deserialize)]
struct TempLeaf {
hash: String,
repetitions: u64,
}

let temp: TempInputsAndLeafs = TempInputsAndLeafs::deserialize(deserializer)?;

// Default inputs to an empty vector if it is None
let inputs = temp.inputs.unwrap_or_else(|| Vec::new());

// Convert TempLeaf to the desired tuple format
let leafs = temp
.leafs
.into_iter()
.map(|leaf| {
let hex_string = leaf.hash.strip_prefix("0x").unwrap_or(&leaf.hash);
(hex::decode(hex_string).unwrap(), leaf.repetitions)
})
.collect();
// Convert TempInput
let inputs = inputs
.into_iter()
.map(|input| {
let hex_string = input.strip_prefix("0x").unwrap_or(&input);
hex::decode(hex_string).unwrap()
})
.collect();

Ok(InputsAndLeafs { leafs, inputs })
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Leaf(#[serde(with = "alloy_hex::serde")] pub [u8; 32], pub u64);

#[derive(Debug)]
pub struct DisputeStateAccess {
Expand All @@ -86,8 +46,8 @@ fn read_json_file(file_path: &Path) -> Result<InputsAndLeafs> {

impl DisputeStateAccess {
pub fn new(
inputs: Vec<Vec<u8>>,
leafs: Vec<(Vec<u8>, u64)>,
inputs: Vec<Input>,
leafs: Vec<Leaf>,
root_tournament: String,
dispute_data_path: &str,
) -> Result<Self> {
Expand Down Expand Up @@ -141,7 +101,7 @@ impl DisputeStateAccess {
}
}

pub fn input(&self, id: u64) -> Result<Option<Input>> {
pub fn input(&self, id: u64) -> Result<Option<Vec<u8>>> {
let conn = self.connection.lock().unwrap();
dispute_data::input(&conn, id)
}
Expand All @@ -150,7 +110,7 @@ impl DisputeStateAccess {
&self,
level: u64,
base_cycle: u64,
leafs: impl Iterator<Item = &'a (Vec<u8>, u64)>,
leafs: impl Iterator<Item = &'a Leaf>,
) -> Result<()> {
let conn = self.connection.lock().unwrap();
dispute_data::insert_compute_leafs(&conn, level, base_cycle, leafs)
Expand Down Expand Up @@ -185,7 +145,7 @@ impl DisputeStateAccess {
pub fn insert_compute_tree<'a>(
&self,
tree_root: &[u8],
tree_leafs: impl Iterator<Item = &'a (Vec<u8>, u64)>,
tree_leafs: impl Iterator<Item = &'a Leaf>,
) -> Result<()> {
let conn = self.connection.lock().unwrap();
dispute_data::insert_compute_tree(&conn, tree_root, tree_leafs)
Expand Down Expand Up @@ -307,11 +267,11 @@ mod dispute_state_access_tests {
DisputeStateAccess::new(Vec::new(), Vec::new(), String::from("0x12345678"), "/tmp")
.unwrap();

let root = vec![
let root = [
1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1,
2, 3, 4,
];
let leafs = vec![(root.clone(), 2)];
let leafs = vec![Leaf(root, 2)];

access.insert_compute_leafs(0, 0, leafs.iter()).unwrap();
let mut compute_leafs = access.compute_leafs(0, 0).unwrap();
Expand All @@ -323,4 +283,38 @@ mod dispute_state_access_tests {
tree = compute_leafs.last().unwrap();
assert!(tree.0.subtrees().is_some());
}

#[test]
fn test_deserialize() {
let json_str_1 = r#"{"leafs": [["0x01020304050607abcdef01020304050607abcdef01020304050607abcdef0102", 20], ["0x01020304050607fedcba01020304050607fedcba01020304050607fedcba0102", 13]]}"#;
let inputs_and_leafs_1: InputsAndLeafs = serde_json::from_str(json_str_1).unwrap();
assert_eq!(inputs_and_leafs_1.inputs.len(), 0);
assert_eq!(inputs_and_leafs_1.leafs.len(), 2);
assert_eq!(
inputs_and_leafs_1.leafs[0].0,
[
1, 2, 3, 4, 5, 6, 7, 171, 205, 239, 1, 2, 3, 4, 5, 6, 7, 171, 205, 239, 1, 2, 3, 4,
5, 6, 7, 171, 205, 239, 1, 2
]
);
assert_eq!(
inputs_and_leafs_1.leafs[1].0,
[
1, 2, 3, 4, 5, 6, 7, 254, 220, 186, 1, 2, 3, 4, 5, 6, 7, 254, 220, 186, 1, 2, 3, 4,
5, 6, 7, 254, 220, 186, 1, 2
]
);

let json_str_2 = r#"{"inputs": [], "leafs": [["0x01020304050607abcdef01020304050607abcdef01020304050607abcdef0102", 20], ["0x01020304050607fedcba01020304050607fedcba01020304050607fedcba0102", 13]]}"#;
let inputs_and_leafs_2: InputsAndLeafs = serde_json::from_str(json_str_2).unwrap();
assert_eq!(inputs_and_leafs_2.inputs.len(), 0);
assert_eq!(inputs_and_leafs_2.leafs.len(), 2);

let json_str_3 = r#"{"inputs": ["0x12345678", "0x22345678"], "leafs": [["0x01020304050607abcdef01020304050607abcdef01020304050607abcdef0102", 20], ["0x01020304050607fedcba01020304050607fedcba01020304050607fedcba0102", 13]]}"#;
let inputs_and_leafs_3: InputsAndLeafs = serde_json::from_str(json_str_3).unwrap();
assert_eq!(inputs_and_leafs_3.inputs.len(), 2);
assert_eq!(inputs_and_leafs_3.leafs.len(), 2);
assert_eq!(inputs_and_leafs_3.inputs[0].0, [18, 52, 86, 120]);
assert_eq!(inputs_and_leafs_3.inputs[1].0, [34, 52, 86, 120]);
}
}
13 changes: 0 additions & 13 deletions prt/prt-rs/src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,3 @@
pub mod dispute_state_access;

pub(crate) mod sql;

#[derive(Clone, Debug)]
pub struct Input {
pub id: u64,
pub data: Vec<u8>,
}

#[derive(Clone, Debug)]
pub struct StateHash {
pub id: u64,
pub data: Vec<u8>,
pub repetition: u64,
}
Loading

0 comments on commit a986f29

Please sign in to comment.