Skip to content

Commit

Permalink
chore: apply cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
alexmikhalevich committed Apr 16, 2024
1 parent 7ac28e5 commit 1f337be
Show file tree
Hide file tree
Showing 11 changed files with 93 additions and 258 deletions.
32 changes: 18 additions & 14 deletions rollup-http/rollup-http-client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@
// limitations under the License.
//

use crate::rollup::{AdvanceRequest, Exception, IndexResponse, InspectRequest, Notice, Report, RollupRequest, RollupResponse, Voucher, GIORequest};
use crate::rollup::{
AdvanceRequest, Exception, GIORequest, IndexResponse, InspectRequest, Notice, Report,
RollupRequest, RollupResponse, Voucher,
};
use hyper::Response;
use serde::{Deserialize, Serialize};
use std::io::ErrorKind;
Expand All @@ -23,13 +26,9 @@ use std::io::ErrorKind;
#[serde(tag = "request_type")]
enum RollupHttpRequest {
#[serde(rename = "advance_state")]
Advance {
data: AdvanceRequest,
},
Advance { data: AdvanceRequest },
#[serde(rename = "inspect_state")]
Inspect {
data: InspectRequest,
},
Inspect { data: InspectRequest },
}

pub async fn send_voucher(rollup_http_server_addr: &str, voucher: Voucher) {
Expand Down Expand Up @@ -99,14 +98,19 @@ pub async fn send_report(rollup_http_server_addr: &str, report: Report) {
}
}

pub async fn send_gio_request(rollup_http_server_addr: &str, gio_request: GIORequest) -> Response<hyper::Body> {
pub async fn send_gio_request(
rollup_http_server_addr: &str,
gio_request: GIORequest,
) -> Response<hyper::Body> {
log::debug!("sending gio request to {}", rollup_http_server_addr);
let client = hyper::Client::new();
let req = hyper::Request::builder()
.method(hyper::Method::POST)
.header(hyper::header::CONTENT_TYPE, "application/json")
.uri(rollup_http_server_addr.to_string() + "/gio")
.body(hyper::Body::from(serde_json::to_string(&gio_request).unwrap()))
.body(hyper::Body::from(
serde_json::to_string(&gio_request).unwrap(),
))
.expect("gio request");
match client.request(req).await {
Ok(res) => {
Expand All @@ -115,16 +119,16 @@ pub async fn send_gio_request(rollup_http_server_addr: &str, gio_request: GIOReq
}
Err(e) => {
log::error!("failed to send gio request to rollup http server: {}", e);
Response::builder().status(500).body(hyper::Body::empty()).unwrap()
Response::builder()
.status(500)
.body(hyper::Body::empty())
.unwrap()
}
}
}

pub async fn throw_exception(rollup_http_server_addr: &str, exception: Exception) {
log::debug!(
"throwing exception request to {}",
rollup_http_server_addr
);
log::debug!("throwing exception request to {}", rollup_http_server_addr);
let client = hyper::Client::new();
let req = hyper::Request::builder()
.method(hyper::Method::POST)
Expand Down
2 changes: 1 addition & 1 deletion rollup-http/rollup-http-client/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
pub mod client;
pub mod rollup;
pub mod rollup;
14 changes: 8 additions & 6 deletions rollup-http/rollup-http-server/src/http_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@ use actix_web::{middleware::Logger, web::Data, App, HttpResponse, HttpServer};
use actix_web_validator::Json;
use async_mutex::Mutex;
use serde::{Deserialize, Serialize};
use tokio::sync::Notify;
use serde_json::json;
use tokio::sync::Notify;

use crate::config::Config;
use crate::rollup::{self, RollupFd, GIORequest};
use crate::rollup::{self, GIORequest, RollupFd};
use crate::rollup::{
AdvanceRequest, Exception, InspectRequest, Notice, Report, RollupRequest, FinishRequest, Voucher,
AdvanceRequest, Exception, FinishRequest, InspectRequest, Notice, Report, RollupRequest,
Voucher,
};

#[derive(Debug, Serialize, Deserialize)]
Expand Down Expand Up @@ -155,16 +156,17 @@ async fn report(report: Json<Report>, data: Data<Mutex<Context>>) -> HttpRespons
async fn gio(request: Json<GIORequest>, data: Data<Mutex<Context>>) -> HttpResponse {
log::debug!("received gio request {:#?}", request);
let context = data.lock().await;
// Write report to linux rollup device
return match rollup::gio_request(&*context.rollup_fd.lock().await, &request.0) {
Ok(result) => {
log::debug!("gio successfully processed, response: {:#?}", result);
HttpResponse::Accepted().body(json!(result).to_string())
}
Err(e) => {
log::error!("unable to process gio request, error details: '{}'", e);
HttpResponse::BadRequest()
.body(format!("unable to process gio request, error details: '{}'", e))
HttpResponse::BadRequest().body(format!(
"unable to process gio request, error details: '{}'",
e
))
}
};
}
Expand Down
59 changes: 35 additions & 24 deletions rollup-http/rollup-http-server/src/rollup/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@

use std::io::ErrorKind;

use lazy_static::lazy_static;
use libc::c_void;
use regex::Regex;
use serde::{Deserialize, Serialize};
use validator::Validate;
use regex::Regex;
use lazy_static::lazy_static;

include!(concat!(env!("OUT_DIR"), "/bindings.rs"));

Expand Down Expand Up @@ -116,7 +116,7 @@ impl From<&mut RollupFinish> for cmt_rollup_finish_t {

#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct GIORequest {
#[validate(range(min = 0x10))] // avoid overlapping with our HTIF_YIELD_MANUAL_REASON_*
#[validate(range(min = 0x10))] // avoid overlapping with our HTIF_YIELD_MANUAL_REASON_*
pub domain: u16,
pub payload: String,
}
Expand Down Expand Up @@ -181,7 +181,7 @@ pub struct FinishRequest {

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InspectReport {
pub reports: Vec<Report>
pub reports: Vec<Report>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
Expand Down Expand Up @@ -239,7 +239,6 @@ pub fn rollup_finish_request(
pub fn rollup_read_advance_state_request(
fd: &RollupFd,
) -> Result<AdvanceRequest, Box<dyn std::error::Error>> {

let mut advance_request = Box::new(cmt_rollup_advance_t {
chain_id: 0,
msg_sender: Default::default(),
Expand All @@ -251,9 +250,7 @@ pub fn rollup_read_advance_state_request(
payload: std::ptr::null::<::std::os::raw::c_uchar>() as *mut c_void,
});

let res = unsafe {
cmt_rollup_read_advance_state(fd.0, advance_request.as_mut())
};
let res = unsafe { cmt_rollup_read_advance_state(fd.0, advance_request.as_mut()) };

if res != 0 {
return Err(Box::new(RollupError::new(&format!(
Expand All @@ -269,7 +266,11 @@ pub fn rollup_read_advance_state_request(
let mut payload: Vec<u8> = Vec::with_capacity(advance_request.payload_length as usize);
if advance_request.payload_length > 0 {
unsafe {
std::ptr::copy(advance_request.payload, payload.as_mut_ptr() as *mut c_void, advance_request.payload_length as usize);
std::ptr::copy(
advance_request.payload,
payload.as_mut_ptr() as *mut c_void,
advance_request.payload_length as usize,
);
payload.set_len(advance_request.payload_length as usize);
}
}
Expand All @@ -282,19 +283,15 @@ pub fn rollup_read_advance_state_request(
Ok(result)
}


pub fn rollup_read_inspect_state_request(
fd: &RollupFd,
) -> Result<InspectRequest, Box<dyn std::error::Error>> {

let mut inspect_request = Box::new(cmt_rollup_inspect_t {
payload_length: 0,
payload: std::ptr::null::<::std::os::raw::c_uchar>() as *mut c_void,
});

let res = unsafe {
cmt_rollup_read_inspect_state(fd.0, inspect_request.as_mut())
};
let res = unsafe { cmt_rollup_read_inspect_state(fd.0, inspect_request.as_mut()) };

if res != 0 {
return Err(Box::new(RollupError::new(&format!(
Expand All @@ -307,11 +304,18 @@ pub fn rollup_read_inspect_state_request(
log::info!("read zero size payload from inspect state request");
}

println!("inspect_request.payload_length: {}", inspect_request.payload_length);
println!(
"inspect_request.payload_length: {}",
inspect_request.payload_length
);
let mut payload: Vec<u8> = Vec::with_capacity(inspect_request.payload_length as usize);
if inspect_request.payload_length > 0 {
unsafe {
std::ptr::copy(inspect_request.payload, payload.as_mut_ptr() as *mut c_void, inspect_request.payload_length as usize);
std::ptr::copy(
inspect_request.payload,
payload.as_mut_ptr() as *mut c_void,
inspect_request.payload_length as usize,
);
payload.set_len(inspect_request.payload_length as usize);
}
}
Expand Down Expand Up @@ -349,7 +353,12 @@ pub fn rollup_write_notice(
binary_payload.len(),
);

cmt_rollup_emit_notice(fd.0, length as u32, buffer.as_mut_ptr() as *mut c_void, &mut notice_index)
cmt_rollup_emit_notice(
fd.0,
length as u32,
buffer.as_mut_ptr() as *mut c_void,
&mut notice_index,
)
};

if res != 0 {
Expand All @@ -364,7 +373,6 @@ pub fn rollup_write_notice(
Ok(notice_index as u64)
}


pub fn rollup_write_voucher(
fd: &RollupFd,
voucher: &mut Voucher,
Expand Down Expand Up @@ -442,7 +450,10 @@ pub fn rollup_write_voucher(
Ok(voucher_index as u64)
}

pub fn rollup_write_report(fd: &RollupFd, report: &Report) -> Result<(), Box<dyn std::error::Error>> {
pub fn rollup_write_report(
fd: &RollupFd,
report: &Report,
) -> Result<(), Box<dyn std::error::Error>> {
print_report(report);

let binary_payload = match hex::decode(&report.payload[2..]) {
Expand Down Expand Up @@ -480,7 +491,10 @@ pub fn rollup_write_report(fd: &RollupFd, report: &Report) -> Result<(), Box<dyn
Ok(())
}

pub fn gio_request(fd: &RollupFd, gio: &GIORequest) -> Result<GIOResponse, Box<dyn std::error::Error>> {
pub fn gio_request(
fd: &RollupFd,
gio: &GIORequest,
) -> Result<GIOResponse, Box<dyn std::error::Error>> {
println!("going to do gio_request");
let binary_payload = match hex::decode(&gio.payload[2..]) {
Ok(payload) => payload,
Expand Down Expand Up @@ -510,9 +524,7 @@ pub fn gio_request(fd: &RollupFd, gio: &GIORequest) -> Result<GIOResponse, Box<d
response_data: std::ptr::null::<::std::os::raw::c_uchar>() as *mut c_void,
});

let res = unsafe {
cmt_gio_request(fd.0, gio_request.as_mut())
};
let res = unsafe { cmt_gio_request(fd.0, gio_request.as_mut()) };

if res != 0 {
return Err(Box::new(RollupError::new(&format!(
Expand Down Expand Up @@ -689,7 +701,6 @@ pub fn print_notice(notice: &Notice) {
);
}


pub fn print_voucher(voucher: &Voucher) {
let mut voucher_request_printout = String::new();
voucher_request_printout.push_str("voucher: {{ destination: ");
Expand Down
51 changes: 25 additions & 26 deletions rollup-http/rollup-http-server/tests/rollup-http-server-tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,19 @@ extern crate rollup_http_server;

use actix_server::ServerHandle;
use async_mutex::Mutex;
use rand::Rng;
use rollup_http_client::rollup::{
Exception, Notice, Report, RollupRequest, RollupResponse, Voucher, GIORequest,
Exception, GIORequest, Notice, Report, RollupRequest, RollupResponse, Voucher,
};
use rollup_http_server::config::Config;
use rollup_http_server::rollup::RollupFd;
use rollup_http_server::*;
use rstest::*;
use std::future::Future;
use std::sync::Arc;
use rand::Rng;
use std::env;
use std::fs::File;
use std::future::Future;
use std::io::Write;
use std::sync::Arc;

const HOST: &str = "127.0.0.1";

Expand Down Expand Up @@ -156,7 +156,10 @@ async fn test_finish_request(
let mut inspect_file = File::create(inspect_path)?;
inspect_file.write_all(&inspect_binary_data)?;

env::set_var("CMT_INPUTS", format!("0:{0},1:{1}", advance_path, inspect_path));
env::set_var(
"CMT_INPUTS",
format!("0:{0},1:{1}", advance_path, inspect_path),
);
env::set_var("CMT_DEBUG", "yes");

let context = context_future.await;
Expand Down Expand Up @@ -216,18 +219,20 @@ async fn test_finish_request(
Ok(())
}

fn check_voucher_or_fail(
original_voucher: Voucher,
output_filename: &str,
) {
fn check_voucher_or_fail(original_voucher: Voucher, output_filename: &str) {
// we try to decode the produced voucher with a third-party lib to see if it matches
// the expected values
let data =
std::fs::read(output_filename).expect("error reading voucher file");
let data = std::fs::read(output_filename).expect("error reading voucher file");
let decoded_voucher = ethabi::decode(
&[ethabi::ParamType::Address, ethabi::ParamType::Uint(256), ethabi::ParamType::Bytes],
&[
ethabi::ParamType::Address,
ethabi::ParamType::Uint(256),
ethabi::ParamType::Bytes,
],
&data[4..], // skip the first 4 bytes that are the function signature
).ok().unwrap();
)
.ok()
.unwrap();

assert_eq!(
"0x".to_string() + &decoded_voucher[0].to_string(),
Expand Down Expand Up @@ -292,12 +297,13 @@ async fn test_write_notice(

// we try to decode the produced voucher with a third-party lib to see if it matches
// the expected values
let data =
std::fs::read("none.output-0.bin").expect("error reading test notice file");
let data = std::fs::read("none.output-0.bin").expect("error reading test notice file");
let decoded_notice = ethabi::decode(
&[ethabi::ParamType::Bytes],
&data[4..], // skip the first 4 bytes that are the function signature
).ok().unwrap();
)
.ok()
.unwrap();

assert_eq!(
"0x".to_string() + &decoded_notice[0].to_string(),
Expand All @@ -324,10 +330,7 @@ async fn test_write_report(
//Read text file with results
let report1 =
std::fs::read_to_string("none.report-0.bin").expect("error reading test report file");
assert_eq!(
report1,
"report test payload 01"
);
assert_eq!(report1, "report test payload 01");
std::fs::remove_file("none.report-0.bin")?;

Ok(())
Expand All @@ -349,12 +352,8 @@ async fn test_gio_request(
context.server_handle.stop(true).await;

//Read text file with results
let gio =
std::fs::read_to_string("none.gio-0.bin").expect("error reading test gio file");
assert_eq!(
gio,
"gio test payload 01"
);
let gio = std::fs::read_to_string("none.gio-0.bin").expect("error reading test gio file");
assert_eq!(gio, "gio test payload 01");
std::fs::remove_file("none.gio-0.bin")?;

Ok(())
Expand Down
Loading

0 comments on commit 1f337be

Please sign in to comment.