Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stronger types for: address, u256 and bytes #63

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions rollup-http/rollup-http-server/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ fn main() {
};

let header_path = if mock_build {
"../../sys-utils/libcmt/src/rollup.h".into()
"../../sys-utils/libcmt/include/libcmt/rollup.h".into()
} else {
pkg_config::get_variable("libcmt", "includedir").expect("Could not find include directory")
+ "/libcmt/rollup.h"
};

let include_path = if mock_build {
"-I../../sys-utils/libcmt/src".into()
"-I../../sys-utils/libcmt/include/libcmt".into()
} else {
"-I".to_string()
+ &pkg_config::get_variable("libcmt", "includedir")
Expand Down
185 changes: 95 additions & 90 deletions rollup-http/rollup-http-server/src/rollup/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,36 @@ impl From<&mut RollupFinish> for cmt_rollup_finish_t {
}
}

impl cmt_abi_u256_t {
fn from_hex(hex: &str) -> Result<cmt_abi_u256_t, hex::FromHexError> {
let mut value: cmt_abi_u256_t = unsafe { std::mem::zeroed() };
let mut binary = hex::decode(hex)?;
unsafe {
if cmt_abi_encode_uint_nn(binary.len(),
binary.as_mut_ptr() as *const u8,
value.data.as_mut_ptr()) != 0 {
return Err(hex::FromHexError::InvalidStringLength);
}
}
return Ok(value);
}
}

impl cmt_abi_address_t {
fn from_hex(hex: &str) -> Result<cmt_abi_address_t, hex::FromHexError> {
let mut value: cmt_abi_address_t = unsafe { std::mem::zeroed() };
let mut binary = hex::decode(hex)?;
unsafe {
if cmt_abi_encode_uint_nn(binary.len(),
binary.as_mut_ptr() as *const u8,
value.data.as_mut_ptr()) != 0 {
return Err(hex::FromHexError::InvalidStringLength);
}
}
return Ok(value);
}
}

#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct GIORequest {
#[validate(range(min = 0x10))] // avoid overlapping with our HTIF_YIELD_MANUAL_REASON_*
Expand All @@ -127,23 +157,36 @@ pub struct GIOResponse {
pub response: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, Validate)]
pub struct AdvanceMetadata {
pub chain_id: u64,
#[validate(regex = "ETH_ADDR_REGEXP")]
pub app_contract: String,
#[validate(regex = "ETH_ADDR_REGEXP")]
pub msg_sender: String,
pub input_index: u64,
pub block_number: u64,
pub block_timestamp: u64,
#[validate(regex = "ETH_U256_REGEXP")]
pub prev_randao: String,
pub input_index: u64,
}

impl From<cmt_rollup_advance_t> for AdvanceMetadata {
fn from(other: cmt_rollup_advance_t) -> Self {
let mut address = "0x".to_string();
address.push_str(&hex::encode(&other.msg_sender));
let mut msg_sender = "0x".to_string();
msg_sender.push_str(&hex::encode(&other.msg_sender.data));
let mut app_contract = "0x".to_string();
app_contract.push_str(&hex::encode(&other.app_contract.data));
let mut prev_randao = "0x".to_string();
prev_randao.push_str(&hex::encode(&other.prev_randao.data));
AdvanceMetadata {
input_index: other.index,
chain_id: other.chain_id,
app_contract: app_contract,
msg_sender: msg_sender,
block_timestamp: other.block_timestamp,
block_number: other.block_number,
msg_sender: address,
input_index: other.index,
prev_randao: prev_randao,
}
}
}
Expand Down Expand Up @@ -241,13 +284,22 @@ pub fn rollup_read_advance_state_request(
) -> Result<AdvanceRequest, Box<dyn std::error::Error>> {
let mut advance_request = Box::new(cmt_rollup_advance_t {
chain_id: 0,
msg_sender: Default::default(),
app_contract: Default::default(),
msg_sender: { cmt_abi_address_t {
data: Default::default(),
}},
app_contract: { cmt_abi_address_t {
data: Default::default(),
}},
block_number: 0,
block_timestamp: 0,
prev_randao: { cmt_abi_u256_t {
data: Default::default(),
}},
index: 0,
payload_length: 0,
payload: std::ptr::null::<::std::os::raw::c_uchar>() as *mut c_void,
payload: { cmt_abi_bytes_t {
length: 0,
data: 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()) };
Expand All @@ -259,19 +311,19 @@ pub fn rollup_read_advance_state_request(
))));
}

if advance_request.payload_length == 0 {
if advance_request.payload.length == 0 {
log::info!("read zero size payload from advance state request");
}

let mut payload: Vec<u8> = Vec::with_capacity(advance_request.payload_length as usize);
if advance_request.payload_length > 0 {
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,
advance_request.payload.data,
payload.as_mut_ptr() as *mut c_void,
advance_request.payload_length as usize,
advance_request.payload.length as usize,
);
payload.set_len(advance_request.payload_length as usize);
payload.set_len(advance_request.payload.length as usize);
}
}

Expand Down Expand Up @@ -333,7 +385,7 @@ pub fn rollup_write_notice(
) -> Result<u64, Box<dyn std::error::Error>> {
print_notice(notice);

let binary_payload = match hex::decode(&notice.payload[2..]) {
let mut binary_payload = match hex::decode(&notice.payload[2..]) {
Ok(payload) => payload,
Err(_err) => {
return Err(Box::new(RollupError::new(&format!(
Expand All @@ -342,21 +394,16 @@ pub fn rollup_write_notice(
}
};

let mut buffer: Vec<u8> = Vec::with_capacity(binary_payload.len());
let length = binary_payload.len() as u64;
let mut notice_index: std::os::raw::c_ulong = 0;
let payload = cmt_abi_bytes_t {
data: binary_payload.as_mut_ptr() as *mut c_void,
length: binary_payload.len()
};

let res = unsafe {
std::ptr::copy(
binary_payload.as_ptr(),
buffer.as_mut_ptr(),
binary_payload.len(),
);

cmt_rollup_emit_notice(
fd.0,
length as u32,
buffer.as_mut_ptr() as *mut c_void,
&payload,
&mut notice_index,
)
};
Expand All @@ -379,61 +426,28 @@ pub fn rollup_write_voucher(
) -> Result<u64, Box<dyn std::error::Error>> {
print_voucher(voucher);

let binary_payload = match hex::decode(&voucher.payload[2..]) {
let mut binary_payload = match hex::decode(&voucher.payload[2..]) {
Ok(payload) => payload,
Err(_err) => {
return Err(Box::new(RollupError::new(&format!(
"Error decoding voucher payload, it must be in Ethereum hex binary format"
))));
}
};
let mut payload_buffer: Vec<u8> = Vec::with_capacity(binary_payload.len());
let payload_data = payload_buffer.as_mut_ptr();
let payload_length = binary_payload.len();

let binary_value = match hex::decode(&voucher.value[2..]) {
Ok(data) => data,
Err(_err) => {
return Err(Box::new(RollupError::new(&format!(
"Error decoding voucher value, it must be in Ethereum hex binary format"
))));
}
};
let mut value_buffer: Vec<u8> = Vec::with_capacity(binary_value.len());
let value_data = value_buffer.as_mut_ptr();
let value_length = binary_value.len();

let address_c = match hex::decode(&voucher.destination[2..]) {
Ok(res) => res,
Err(e) => {
return Err(Box::new(RollupError::new(&format!(
"address not valid: {}",
e
))));
}
let value = cmt_abi_u256_t::from_hex(&voucher.value[2..])?;
let address = cmt_abi_address_t::from_hex(&voucher.destination[2..])?;
let payload = cmt_abi_bytes_t {
data: binary_payload.as_mut_ptr() as *mut c_void,
length: binary_payload.len(),
};

let mut voucher_index: std::os::raw::c_ulong = 0;
let res = unsafe {
std::ptr::copy(
binary_payload.as_ptr(),
payload_buffer.as_mut_ptr(),
binary_payload.len(),
);
std::ptr::copy(
binary_value.as_ptr(),
value_buffer.as_mut_ptr(),
binary_value.len(),
);

cmt_rollup_emit_voucher(
fd.0,
address_c.len() as u32,
address_c.as_ptr() as *const c_void,
value_length as u32,
value_data as *mut c_void,
payload_length as u32,
payload_data as *mut c_void,
&address,
&value,
&payload,
&mut voucher_index,
)
};
Expand All @@ -456,7 +470,7 @@ pub fn rollup_write_report(
) -> Result<(), Box<dyn std::error::Error>> {
print_report(report);

let binary_payload = match hex::decode(&report.payload[2..]) {
let mut binary_payload = match hex::decode(&report.payload[2..]) {
Ok(payload) => payload,
Err(_err) => {
return Err(Box::new(RollupError::new(&format!(
Expand All @@ -465,18 +479,13 @@ pub fn rollup_write_report(
}
};

let mut buffer: Vec<u8> = Vec::with_capacity(binary_payload.len());

let data = buffer.as_mut_ptr() as *mut c_void;
let length = binary_payload.len();
let payload = cmt_abi_bytes_t {
data: binary_payload.as_mut_ptr() as *mut c_void,
length: binary_payload.len(),
};

let res = unsafe {
std::ptr::copy(
binary_payload.as_ptr(),
buffer.as_mut_ptr(),
binary_payload.len(),
);
cmt_rollup_emit_report(fd.0, length as u32, data)
cmt_rollup_emit_report(fd.0, &payload)
};

if res != 0 {
Expand Down Expand Up @@ -562,7 +571,7 @@ pub fn rollup_throw_exception(
) -> Result<(), Box<dyn std::error::Error>> {
print_exception(exception);

let binary_payload = match hex::decode(&exception.payload[2..]) {
let mut binary_payload = match hex::decode(&exception.payload[2..]) {
Ok(payload) => payload,
Err(_err) => {
return Err(Box::new(RollupError::new(&format!(
Expand All @@ -571,17 +580,13 @@ pub fn rollup_throw_exception(
}
};

let mut buffer: Vec<u8> = Vec::with_capacity(binary_payload.len());
let length = binary_payload.len();
let data = buffer.as_mut_ptr() as *mut c_void;
let payload = cmt_abi_bytes_t {
data: binary_payload.as_mut_ptr() as *mut c_void,
length: binary_payload.len(),
};

let res = unsafe {
std::ptr::copy(
binary_payload.as_ptr(),
buffer.as_mut_ptr(),
binary_payload.len(),
);
cmt_rollup_emit_exception(fd.0, length as u32, data)
cmt_rollup_emit_exception(fd.0, &payload)
};
if res != 0 {
return Err(Box::new(RollupError::new(&format!(
Expand Down
9 changes: 5 additions & 4 deletions sys-utils/libcmt/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ TARGET_PREFIX ?= $(PREFIX)
TOOLCHAIN_PREFIX ?= riscv64-linux-gnu-
TARGET_CC := $(TOOLCHAIN_PREFIX)gcc
TARGET_AR := $(TOOLCHAIN_PREFIX)ar
COMMON_CFLAGS := -Wvla -O2 -g -Wall -pedantic -Wextra -Isrc \
COMMON_CFLAGS := -Wvla -O2 -g -Wall -pedantic -Wextra -Iinclude \
-fno-strict-aliasing -fno-strict-overflow -fPIC
TARGET_CFLAGS := $(COMMON_CFLAGS) -ftrivial-auto-var-init=zero -Wstrict-aliasing=3
CFLAGS := $(COMMON_CFLAGS)
Expand Down Expand Up @@ -85,7 +85,7 @@ install: $(libcmt_LIB) $(libcmt_SO) build/ffi.h
mkdir -p $(TARGET_DESTDIR)$(TARGET_PREFIX)/lib
cp -f $(libcmt_LIB) $(libcmt_SO) $(TARGET_DESTDIR)$(TARGET_PREFIX)/lib
mkdir -p $(TARGET_DESTDIR)$(TARGET_PREFIX)/include/libcmt/
cp -f src/*.h $(TARGET_DESTDIR)$(TARGET_PREFIX)/include/libcmt/
cp -f include/libcmt/*.h $(TARGET_DESTDIR)$(TARGET_PREFIX)/include/libcmt/
cp -f build/ffi.h $(TARGET_DESTDIR)$(TARGET_PREFIX)/include/libcmt/
mkdir -p $(TARGET_DESTDIR)$(TARGET_PREFIX)/lib/pkgconfig
sed -e 's|@ARG_PREFIX@|$(TARGET_PREFIX)|g' src/libcmt.pc > $(TARGET_DESTDIR)$(TARGET_PREFIX)/lib/pkgconfig/libcmt.pc
Expand Down Expand Up @@ -126,7 +126,7 @@ install-mock: $(mock_LIB) $(mock_SO) build/ffi.h
mkdir -p $(DESTDIR)$(PREFIX)/lib
cp -f $(mock_LIB) $(mock_SO) $(DESTDIR)$(PREFIX)/lib
mkdir -p $(DESTDIR)$(PREFIX)/include/libcmt/
cp -f src/*.h $(DESTDIR)$(PREFIX)/include/libcmt/
cp -f include/libcmt/*.h $(DESTDIR)$(PREFIX)/include/libcmt/
cp -f build/ffi.h $(DESTDIR)$(PREFIX)/include/libcmt/
mkdir -p $(DESTDIR)$(PREFIX)/lib/pkgconfig
sed -e 's|@ARG_PREFIX@|$(PREFIX)|g' src/libcmt_mock.pc > $(DESTDIR)$(PREFIX)/lib/pkgconfig/libcmt.pc
Expand Down Expand Up @@ -183,7 +183,8 @@ $(tools_OBJDIR)/funsel: tools/funsel.c $(mock_LIB)

tools: $(tools_BINS)

build/ffi.h: src/buf.h src/abi.h src/keccak.h src/merkle.h src/io.h src/rollup.h
HDRS := $(patsubst %,include/libcmt/%, buf.h abi.h keccak.h merkle.h io.h rollup.h)
build/ffi.h: $(HDRS)
cat $^ | sh tools/prepare-ffi.sh > $@
#-------------------------------------------------------------------------------
LINTER_IGNORE_SOURCES=src/io.c
Expand Down
5 changes: 3 additions & 2 deletions sys-utils/libcmt/doc/examples/abi_encode_001.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
int encode_bytes(cmt_buf_t *tx, uint32_t funsel, size_t bytes_length, void *bytes_data) {
cmt_buf_t wr = *tx;
cmt_buf_t of;
void *params_base = wr.begin + 4; // after funsel
cmt_buf_t frame;

// static section
return cmt_abi_put_funsel(&wr, funsel)
|| cmt_abi_mark_frame(&wr, &frame)
|| cmt_abi_put_bytes_s(&wr, &of)
// dynamic section
|| cmt_abi_put_bytes_d(&wr, &of, bytes_length, bytes_data, params_base);
|| cmt_abi_put_bytes_d(&wr, &of, &frame, &(cmt_abi_bytes_t){bytes_length, bytes_data});
}
7 changes: 4 additions & 3 deletions sys-utils/libcmt/doc/examples/abi_encode_002.c
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,16 @@ int encode_bytes(cmt_buf_t *tx, uint32_t funsel,
size_t bytes1_length, void *bytes1_data) {
cmt_buf_t wr = *tx;
cmt_buf_t of[2];
void *params_base = wr.begin + 4; // after funsel
cmt_buf_t frame;

// static section
return cmt_abi_put_funsel(&wr, funsel)
|| cmt_abi_mark_frame(&wr, &frame)
|| cmt_abi_put_bytes_s(&wr, &of[0])
|| cmt_abi_put_bytes_s(&wr, &of[1])
// dynamic section
|| cmt_abi_put_bytes_d(&wr, &of[0], bytes0_length, bytes0_data, params_base)
|| cmt_abi_put_bytes_d(&wr, &of[1], bytes1_length, bytes1_data, params_base)
|| cmt_abi_put_bytes_d(&wr, &frame, &of[0], &(cmt_abi_bytes_t){bytes0_length, bytes0_data})
|| cmt_abi_put_bytes_d(&wr, &frame, &of[1], &(cmt_abi_bytes_t){bytes1_length, bytes1_data})
;
}

Loading
Loading