diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index b42d277f..82f12c8a 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -107,5 +107,7 @@ jobs: - name: Test rollup-http-server and echo-dapp client run: | + mkdir -p /opt/mock + make -C sys-utils/libcmt/ -j$(nproc) install-mock PREFIX=/opt/mock cd rollup-http/rollup-http-server - USE_ROLLUP_BINDINGS_MOCK=1 cargo test -- --show-output --test-threads=1 + CPATH="/opt/mock/include:$CPATH" RUSTFLAGS="-L /opt/mock/lib" cargo test -- --show-output --test-threads=1 diff --git a/Dockerfile b/Dockerfile index eba31a2f..5ea1d628 100644 --- a/Dockerfile +++ b/Dockerfile @@ -38,6 +38,7 @@ apt-get install -y --no-install-recommends \ wget \ pkg-config \ dpkg-cross \ + libclang-dev \ gcc-12-riscv64-linux-gnu \ g++-12-riscv64-linux-gnu @@ -46,6 +47,8 @@ for tool in cpp g++ gcc gcc-ar gcc-nm gcc-ranlib gcov gcov-dump gcov-tool; do update-alternatives --install /usr/bin/$tool $tool /usr/bin/$tool-12 12 done +ln -s gcc /usr/bin/cc + wget -O ${LINUX_HEADERS_FILEPATH} ${LINUX_HEADERS_URLPATH} echo "7d0238324661a3850fe2e07e5c4485a94da5d5162dbb67def0f1541ed1dc3b45 ${LINUX_HEADERS_FILEPATH}" | sha256sum --check apt-get install -y --no-install-recommends ${LINUX_HEADERS_FILEPATH} @@ -76,58 +79,59 @@ RUN make -C ${BUILD_BASE}/tools/sys-utils/libcmt/ -j$(nproc) install install-moc PREFIX=/usr/x86_64-linux-gnu TARGET_PREFIX=/usr/riscv64-linux-gnu USER developer RUN make -C ${BUILD_BASE}/tools/sys-utils/ -j$(nproc) all +ENV CPATH="/usr/riscv64-linux-gnu/include/:${CPATH}" # build rust tools # ------------------------------------------------------------------------------ -FROM tools-env as rust-env +FROM c-builder as rust-env ENV PATH="/home/developer/.cargo/bin:${PATH}" USER developer -#RUN cd && \ -# wget https://github.com/rust-lang/rustup/archive/refs/tags/1.26.0.tar.gz && \ -# echo "6f20ff98f2f1dbde6886f8d133fe0d7aed24bc76c670ea1fca18eb33baadd808 1.26.0.tar.gz" | sha256sum --check && \ -# tar -xzf 1.26.0.tar.gz && \ -# bash rustup-1.26.0/rustup-init.sh \ -# -y \ -# --default-toolchain 1.74.0 \ -# --profile minimal \ -# --target riscv64gc-unknown-linux-gnu && \ -# rm -rf rustup-1.26.0 1.26.0.tar.gz -# -#FROM rust-env as rust-builder -#COPY --chown=developer:developer rollup-http/rollup-init ${BUILD_BASE}/tools/rollup-http/rollup-init -#COPY --chown=developer:developer rollup-http/rollup-http-client ${BUILD_BASE}/tools/rollup-http/rollup-http-client -#COPY --chown=developer:developer rollup-http/.cargo ${BUILD_BASE}/tools/rollup-http/.cargo -# -## build rollup-http-server dependencies -#FROM rust-builder as http-server-dep-builder -#COPY --chown=developer:developer rollup-http/rollup-http-server/Cargo.toml rollup-http/rollup-http-server/Cargo.lock ${BUILD_BASE}/tools/rollup-http/rollup-http-server/ -#RUN cd ${BUILD_BASE}/tools/rollup-http/rollup-http-server && \ -# mkdir src/ && \ -# echo "fn main() {}" > src/main.rs && \ -# echo "pub fn dummy() {}" > src/lib.rs && \ -# cargo build --target riscv64gc-unknown-linux-gnu --release -# -## build rollup-http-server -#FROM http-server-dep-builder as http-server-builder -#COPY --chown=developer:developer rollup-http/rollup-http-server/build.rs ${BUILD_BASE}/tools/rollup-http/rollup-http-server/ -#COPY --chown=developer:developer rollup-http/rollup-http-server/src ${BUILD_BASE}/tools/rollup-http/rollup-http-server/src -#RUN cd ${BUILD_BASE}/tools/rollup-http/rollup-http-server && touch build.rs src/* && \ -# cargo build --target riscv64gc-unknown-linux-gnu --release -# -## build echo-dapp dependencies -#FROM rust-builder as echo-dapp-dep-builder -#COPY --chown=developer:developer rollup-http/echo-dapp/Cargo.toml rollup-http/echo-dapp/Cargo.lock ${BUILD_BASE}/tools/rollup-http/echo-dapp/ -#RUN cd ${BUILD_BASE}/tools/rollup-http/echo-dapp && \ -# mkdir src/ && echo "fn main() {}" > src/main.rs && \ -# cargo build --target riscv64gc-unknown-linux-gnu --release -# -## build echo-dapp -#FROM echo-dapp-dep-builder as echo-dapp-builder -#COPY --chown=developer:developer rollup-http/echo-dapp/src ${BUILD_BASE}/tools/rollup-http/echo-dapp/src -#RUN cd ${BUILD_BASE}/tools/rollup-http/echo-dapp && touch src/* && \ -# cargo build --target riscv64gc-unknown-linux-gnu --release +RUN cd && \ + wget https://github.com/rust-lang/rustup/archive/refs/tags/1.26.0.tar.gz && \ + echo "6f20ff98f2f1dbde6886f8d133fe0d7aed24bc76c670ea1fca18eb33baadd808 1.26.0.tar.gz" | sha256sum --check && \ + tar -xzf 1.26.0.tar.gz && \ + bash rustup-1.26.0/rustup-init.sh \ + -y \ + --default-toolchain 1.74.0 \ + --profile minimal \ + --target riscv64gc-unknown-linux-gnu && \ + rm -rf rustup-1.26.0 1.26.0.tar.gz + +FROM rust-env as rust-builder +COPY --chown=developer:developer rollup-http/rollup-init ${BUILD_BASE}/tools/rollup-http/rollup-init +COPY --chown=developer:developer rollup-http/rollup-http-client ${BUILD_BASE}/tools/rollup-http/rollup-http-client +COPY --chown=developer:developer rollup-http/.cargo ${BUILD_BASE}/tools/rollup-http/.cargo + +# build rollup-http-server dependencies +FROM rust-builder as http-server-dep-builder +COPY --chown=developer:developer rollup-http/rollup-http-server/Cargo.toml rollup-http/rollup-http-server/Cargo.lock ${BUILD_BASE}/tools/rollup-http/rollup-http-server/ +RUN cd ${BUILD_BASE}/tools/rollup-http/rollup-http-server && \ + mkdir src/ && \ + echo "fn main() {}" > src/main.rs && \ + echo "pub fn dummy() {}" > src/lib.rs && \ + cargo build --target riscv64gc-unknown-linux-gnu --release + +# build rollup-http-server +FROM http-server-dep-builder as http-server-builder +COPY --chown=developer:developer rollup-http/rollup-http-server/build.rs ${BUILD_BASE}/tools/rollup-http/rollup-http-server/ +COPY --chown=developer:developer rollup-http/rollup-http-server/src ${BUILD_BASE}/tools/rollup-http/rollup-http-server/src +RUN cd ${BUILD_BASE}/tools/rollup-http/rollup-http-server && touch build.rs src/* && \ + cargo build --target riscv64gc-unknown-linux-gnu --release + +# build echo-dapp dependencies +FROM rust-builder as echo-dapp-dep-builder +COPY --chown=developer:developer rollup-http/echo-dapp/Cargo.toml rollup-http/echo-dapp/Cargo.lock ${BUILD_BASE}/tools/rollup-http/echo-dapp/ +RUN cd ${BUILD_BASE}/tools/rollup-http/echo-dapp && \ + mkdir src/ && echo "fn main() {}" > src/main.rs && \ + cargo build --target riscv64gc-unknown-linux-gnu --release + +# build echo-dapp +FROM echo-dapp-dep-builder as echo-dapp-builder +COPY --chown=developer:developer rollup-http/echo-dapp/src ${BUILD_BASE}/tools/rollup-http/echo-dapp/src +RUN cd ${BUILD_BASE}/tools/rollup-http/echo-dapp && touch src/* && \ + cargo build --target riscv64gc-unknown-linux-gnu --release # pack tools (deb) # ------------------------------------------------------------------------------ @@ -151,8 +155,8 @@ COPY --from=c-builder ${BUILD_BASE}/tools/sys-utils/rollup/rollup ${STAGING_SBIN COPY --from=c-builder ${BUILD_BASE}/tools/sys-utils/ioctl-echo-loop/ioctl-echo-loop ${STAGING_BIN} COPY --from=c-builder ${BUILD_BASE}/tools/sys-utils/yield/yield ${STAGING_SBIN} COPY --from=c-builder ${BUILD_BASE}/tools/sys-utils/misc/* ${STAGING_BIN} -#COPY --from=rust-builder ${BUILD_BASE}/tools/rollup-http/rollup-init/rollup-init ${STAGING_SBIN} -#COPY --from=http-server-builder ${BUILD_BASE}/tools/rollup-http/rollup-http-server/target/riscv64gc-unknown-linux-gnu/release/rollup-http-server ${STAGING_BIN} -#COPY --from=echo-dapp-builder ${BUILD_BASE}/tools/rollup-http/echo-dapp/target/riscv64gc-unknown-linux-gnu/release/echo-dapp ${STAGING_BIN} +COPY --from=rust-builder ${BUILD_BASE}/tools/rollup-http/rollup-init/rollup-init ${STAGING_SBIN} +COPY --from=http-server-builder ${BUILD_BASE}/tools/rollup-http/rollup-http-server/target/riscv64gc-unknown-linux-gnu/release/rollup-http-server ${STAGING_BIN} +COPY --from=echo-dapp-builder ${BUILD_BASE}/tools/rollup-http/echo-dapp/target/riscv64gc-unknown-linux-gnu/release/echo-dapp ${STAGING_BIN} RUN dpkg-deb -Zxz --root-owner-group --build ${STAGING_BASE} ${BUILD_BASE}/${TOOLS_DEB} diff --git a/fs/Dockerfile b/fs/Dockerfile index d8c4c45b..2259ba0d 100644 --- a/fs/Dockerfile +++ b/fs/Dockerfile @@ -40,7 +40,7 @@ RUN apt-get update && \ bash=5.1-6ubuntu1 \ psmisc=23.4-2build3 \ bc=1.07.1-3build1 \ - curl=7.81.0-1ubuntu1.15 \ + curl=7.81.0-1ubuntu1.16 \ device-tree-compiler=1.6.1-1 \ jq=1.6-2.1ubuntu3 \ lua5.4=5.4.4-1 \ diff --git a/rollup-http/echo-dapp/src/main.rs b/rollup-http/echo-dapp/src/main.rs index 038458b5..a9fc0e34 100644 --- a/rollup-http/echo-dapp/src/main.rs +++ b/rollup-http/echo-dapp/src/main.rs @@ -44,6 +44,7 @@ pub async fn process_advance_request( let voucher_payload = request.payload.clone(); let voucher = Voucher { destination: request.metadata.msg_sender.clone(), + value: "0xdeadbeef".to_string(), payload: voucher_payload, }; diff --git a/rollup-http/rollup-http-client/src/rollup.rs b/rollup-http/rollup-http-client/src/rollup.rs index eeef5659..9304b2b4 100644 --- a/rollup-http/rollup-http-client/src/rollup.rs +++ b/rollup-http/rollup-http-client/src/rollup.rs @@ -21,10 +21,9 @@ use std::fmt; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct AdvanceMetadata { pub msg_sender: String, - pub epoch_index: u64, pub input_index: u64, pub block_number: u64, - pub timestamp: u64, + pub block_timestamp: u64, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -51,6 +50,7 @@ pub struct Notice { #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Voucher { pub destination: String, + pub value: String, pub payload: String, } diff --git a/rollup-http/rollup-http-server/Cargo.lock b/rollup-http/rollup-http-server/Cargo.lock index e2923df4..fea9b208 100644 --- a/rollup-http/rollup-http-server/Cargo.lock +++ b/rollup-http/rollup-http-server/Cargo.lock @@ -65,7 +65,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e01ed3140b2f8d422c68afa1ed2e85d996ea619c988ac834d255db32138655cb" dependencies = [ "quote", - "syn 2.0.39", + "syn 2.0.53", ] [[package]] @@ -178,7 +178,29 @@ dependencies = [ "actix-router", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.53", +] + +[[package]] +name = "actix-web-validator" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ee5ed4e266dad8d980f964c5ddd746f1f4f85b7f3b54f7099ab861ec6d746" +dependencies = [ + "actix-http", + "actix-router", + "actix-web", + "bytes", + "futures", + "futures-util", + "log", + "mime", + "serde", + "serde_json", + "serde_qs", + "serde_urlencoded", + "thiserror", + "validator", ] [[package]] @@ -233,21 +255,18 @@ dependencies = [ "alloc-no-stdlib", ] -[[package]] -name = "ansi_term" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" -dependencies = [ - "winapi", -] - [[package]] name = "anyhow" version = "1.0.75" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6" +[[package]] +name = "arrayvec" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" + [[package]] name = "async-mutex" version = "1.4.0" @@ -265,7 +284,7 @@ checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.53", ] [[package]] @@ -308,24 +327,24 @@ checksum = "35636a1494ede3b646cc98f74f8e62c773a38a659ebc777a2cf26b9b74171df9" [[package]] name = "bindgen" -version = "0.59.2" +version = "0.69.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bd2a9a458e8f4304c52c43ebb0cfbd520289f8379a52e329a38afda99bf8eb8" +checksum = "a00dc851838a2120612785d195287475a3ac45514741da670b735818822129a0" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.4.1", "cexpr", "clang-sys", - "clap", - "env_logger", + "itertools", "lazy_static", "lazycell", "log", - "peeking_take_while", + "prettyplease", "proc-macro2", "quote", "regex", "rustc-hash", "shlex", + "syn 2.0.53", "which", ] @@ -341,6 +360,18 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07" +[[package]] +name = "bitvec" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -371,6 +402,18 @@ dependencies = [ "alloc-stdlib", ] +[[package]] +name = "byte-slice-cast" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3ac9f8b63eca6fd385229b3675f6cc0dc5c8a5c8a54a59d4f52ffd670d87b0c" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "bytes" version = "1.5.0" @@ -422,21 +465,6 @@ dependencies = [ "libloading", ] -[[package]] -name = "clap" -version = "2.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" -dependencies = [ - "ansi_term", - "atty", - "bitflags 1.3.2", - "strsim", - "textwrap", - "unicode-width", - "vec_map", -] - [[package]] name = "convert_case" version = "0.4.0" @@ -472,6 +500,12 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crunchy" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" + [[package]] name = "crypto-common" version = "0.1.6" @@ -558,6 +592,50 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "ethabi" +version = "18.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7413c5f74cc903ea37386a8965a936cbeb334bd270862fdece542c1b2dcbc898" +dependencies = [ + "ethereum-types", + "hex", + "once_cell", + "regex", + "serde", + "serde_json", + "sha3", + "thiserror", + "uint", +] + +[[package]] +name = "ethbloom" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c22d4b5885b6aa2fe5e8b9329fb8d232bf739e434e6b87347c63bdd00c120f60" +dependencies = [ + "crunchy", + "fixed-hash", + "impl-rlp", + "impl-serde", + "tiny-keccak", +] + +[[package]] +name = "ethereum-types" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02d215cbf040552efcbe99a38372fe80ab9d00268e20012b79fcd0f073edd8ee" +dependencies = [ + "ethbloom", + "fixed-hash", + "impl-rlp", + "impl-serde", + "primitive-types", + "uint", +] + [[package]] name = "event-listener" version = "2.5.3" @@ -570,6 +648,18 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" +[[package]] +name = "fixed-hash" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835c052cb0c08c1acf6ffd71c022172e18723949c8282f2b9f27efbc51e64534" +dependencies = [ + "byteorder", + "rand", + "rustc-hex", + "static_assertions", +] + [[package]] name = "fixedbitset" version = "0.2.0" @@ -601,6 +691,27 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futures" +version = "0.3.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0290714b38af9b4a7b094b8a37086d1b4e61f2df9122c3cad2577669145335" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.29" @@ -608,6 +719,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff4dd66668b557604244583e3e1e1eada8c5c2e96a6d0d6653ede395b78bbacb" dependencies = [ "futures-core", + "futures-sink", ] [[package]] @@ -616,6 +728,34 @@ version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eb1d22c66e66d9d72e1758f0bd7d4fd0bee04cad842ee34587d68c07e45d088c" +[[package]] +name = "futures-executor" +version = "0.3.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f4fb8693db0cf099eadcca0efe2a5a22e4550f98ed16aba6c48700da29597bc" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" + +[[package]] +name = "futures-macro" +version = "0.3.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53b153fd91e4b0147f4aced87be237c98248656bb01050b96bf3ee89220a8ddb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.53", +] + [[package]] name = "futures-sink" version = "0.3.29" @@ -634,10 +774,16 @@ version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a19526d624e703a3179b3d322efec918b6246ea0fa51d41124525f00f1cc8104" dependencies = [ + "futures-channel", "futures-core", + "futures-io", + "futures-macro", + "futures-sink", "futures-task", + "memchr", "pin-project-lite", "pin-utils", + "slab", ] [[package]] @@ -815,6 +961,16 @@ dependencies = [ "want", ] +[[package]] +name = "idna" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c" +dependencies = [ + "unicode-bidi", + "unicode-normalization", +] + [[package]] name = "idna" version = "0.5.0" @@ -825,6 +981,50 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "if_chain" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb56e1aa765b4b4f3aadfab769793b7087bb03a4ea4920644a6d238e2df5b9ed" + +[[package]] +name = "impl-codec" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba6a270039626615617f3f36d15fc827041df3b78c439da2cadfa47455a77f2f" +dependencies = [ + "parity-scale-codec", +] + +[[package]] +name = "impl-rlp" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28220f89297a075ddc7245cd538076ee98b01f2a9c23a53a4f1105d5a322808" +dependencies = [ + "rlp", +] + +[[package]] +name = "impl-serde" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc88fc67028ae3db0c853baa36269d398d5f45b6982f95549ff5def78c935cd" +dependencies = [ + "serde", +] + +[[package]] +name = "impl-trait-for-tuples" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d7a9f6330b71fea57921c9b61c47ee6e84f72d394754eff6163ae67e7395eb" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "indexmap" version = "1.9.3" @@ -869,6 +1069,15 @@ dependencies = [ "libc", ] +[[package]] +name = "keccak" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc2af9a1119c51f12a14607e783cb977bde58bc069ff0c3da1095e635d70654" +dependencies = [ + "cpufeatures", +] + [[package]] name = "language-tags" version = "0.3.2" @@ -889,9 +1098,9 @@ checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" [[package]] name = "libc" -version = "0.2.150" +version = "0.2.153" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c" +checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" [[package]] name = "libloading" @@ -905,9 +1114,9 @@ dependencies = [ [[package]] name = "linux-raw-sys" -version = "0.4.11" +version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "969488b55f8ac402214f3f5fd243ebb7206cf82de60d3172994707a4bcc2b829" +checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" [[package]] name = "local-channel" @@ -1018,9 +1227,35 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.18.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" +checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" + +[[package]] +name = "parity-scale-codec" +version = "3.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "881331e34fa842a2fb61cc2db9643a8fedc615e47cfcc52597d1af0db9a7e8fe" +dependencies = [ + "arrayvec", + "bitvec", + "byte-slice-cast", + "impl-trait-for-tuples", + "parity-scale-codec-derive", + "serde", +] + +[[package]] +name = "parity-scale-codec-derive" +version = "3.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be30eaf4b0a9fba5336683b38de57bb86d179a35862ba6bfcf57625d006bde5b" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 1.0.109", +] [[package]] name = "parking_lot" @@ -1051,12 +1286,6 @@ version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c" -[[package]] -name = "peeking_take_while" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" - [[package]] name = "percent-encoding" version = "2.3.1" @@ -1103,11 +1332,68 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" +[[package]] +name = "prettyplease" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a41cf62165e97c7f814d2221421dbb9afcbcdb0a88068e5ea206e19951c2cbb5" +dependencies = [ + "proc-macro2", + "syn 2.0.53", +] + +[[package]] +name = "primitive-types" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b34d9fd68ae0b74a41b21c03c2f62847aa0ffea044eee893b4c140b37e244e2" +dependencies = [ + "fixed-hash", + "impl-codec", + "impl-rlp", + "impl-serde", + "uint", +] + +[[package]] +name = "proc-macro-crate" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24" +dependencies = [ + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + [[package]] name = "proc-macro2" -version = "1.0.70" +version = "1.0.79" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39278fbbf5fb4f646ce651690877f89d1c5811a3d4acb27700c1cb3cdb78fd3b" +checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e" dependencies = [ "unicode-ident", ] @@ -1165,13 +1451,19 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.33" +version = "1.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" +checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" dependencies = [ "proc-macro2", ] +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + [[package]] name = "rand" version = "0.8.5" @@ -1240,6 +1532,16 @@ version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" +[[package]] +name = "rlp" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb919243f34364b6bd2fc10ef797edbfa75f33c252e7998527479c6d6b47e1ec" +dependencies = [ + "bytes", + "rustc-hex", +] + [[package]] name = "rollup-http-client" version = "0.1.0" @@ -1256,19 +1558,23 @@ dependencies = [ [[package]] name = "rollup-http-server" -version = "0.1.0" +version = "0.2.0" dependencies = [ "actix-server", "actix-web", + "actix-web-validator", "async-mutex", "bindgen", "cc", "env_logger", + "ethabi", "getopts", "hex", "hyper", + "lazy_static", "libc", "log", + "rand", "regex", "rollup-http-client", "rstest", @@ -1276,6 +1582,7 @@ dependencies = [ "serde_json", "tokio", "tonic-build", + "validator", ] [[package]] @@ -1303,6 +1610,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" +[[package]] +name = "rustc-hex" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e75f6a532d0fd9f7f13144f392b6ad56a32696bfcd9c78f797f16bbb6f072d6" + [[package]] name = "rustc_version" version = "0.4.0" @@ -1314,15 +1627,15 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.25" +version = "0.38.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc99bc2d4f1fed22595588a013687477aedf3cdcfb26558c559edb67b4d9b22e" +checksum = "65e04861e65f21776e67888bfbea442b3642beaa0138fdb1dd7a84a52dffdb89" dependencies = [ "bitflags 2.4.1", "errno", "libc", "linux-raw-sys", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] @@ -1360,7 +1673,7 @@ checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.53", ] [[package]] @@ -1374,6 +1687,19 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_qs" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cac3f1e2ca2fe333923a1ae72caca910b98ed0630bb35ef6f8c8517d6e81afa" +dependencies = [ + "actix-web", + "futures", + "percent-encoding", + "serde", + "thiserror", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -1397,6 +1723,16 @@ dependencies = [ "digest", ] +[[package]] +name = "sha3" +version = "0.10.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75872d278a8f37ef87fa0ddbda7802605cb18344497949862c0d4dcb291eba60" +dependencies = [ + "digest", + "keccak", +] + [[package]] name = "shlex" version = "1.2.0" @@ -1448,10 +1784,10 @@ dependencies = [ ] [[package]] -name = "strsim" -version = "0.8.0" +name = "static_assertions" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "syn" @@ -1466,26 +1802,31 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.39" +version = "2.0.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23e78b90f2fcf45d3e842032ce32e3f2d1545ba6636271dcbf24fa306d87be7a" +checksum = "7383cd0e49fff4b6b90ca5670bfd3e9d6a733b3f90c686605aa7eec8c4996032" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + [[package]] name = "tempfile" -version = "3.8.1" +version = "3.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef1adac450ad7f4b3c28589471ade84f25f731a7a0fe30d71dfa9f60fd808e5" +checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", "fastrand", - "redox_syscall", "rustix", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] @@ -1498,12 +1839,23 @@ dependencies = [ ] [[package]] -name = "textwrap" -version = "0.11.0" +name = "thiserror" +version = "1.0.58" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" +checksum = "03468839009160513471e86a034bb2c5c0e4baae3b43f79ffc55c4a5427b3297" dependencies = [ - "unicode-width", + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.53", ] [[package]] @@ -1535,6 +1887,15 @@ dependencies = [ "time-core", ] +[[package]] +name = "tiny-keccak" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", +] + [[package]] name = "tinyvec" version = "1.6.0" @@ -1577,7 +1938,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.53", ] [[package]] @@ -1594,6 +1955,23 @@ dependencies = [ "tracing", ] +[[package]] +name = "toml_datetime" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" + +[[package]] +name = "toml_edit" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" +dependencies = [ + "indexmap 2.1.0", + "toml_datetime", + "winnow", +] + [[package]] name = "tonic-build" version = "0.5.2" @@ -1644,6 +2022,18 @@ version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" +[[package]] +name = "uint" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76f64bba2c53b04fcab63c01a7d7427eadc821e3bc48c34dc9ba29c501164b52" +dependencies = [ + "byteorder", + "crunchy", + "hex", + "static_assertions", +] + [[package]] name = "unicode-bidi" version = "0.3.13" @@ -1684,15 +2074,51 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633" dependencies = [ "form_urlencoded", - "idna", + "idna 0.5.0", "percent-encoding", ] [[package]] -name = "vec_map" -version = "0.8.2" +name = "validator" +version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" +checksum = "b92f40481c04ff1f4f61f304d61793c7b56ff76ac1469f1beb199b1445b253bd" +dependencies = [ + "idna 0.4.0", + "lazy_static", + "regex", + "serde", + "serde_derive", + "serde_json", + "url", + "validator_derive", +] + +[[package]] +name = "validator_derive" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc44ca3088bb3ba384d9aecf40c6a23a676ce23e09bdaca2073d99c207f864af" +dependencies = [ + "if_chain", + "lazy_static", + "proc-macro-error", + "proc-macro2", + "quote", + "regex", + "syn 1.0.109", + "validator_types", +] + +[[package]] +name = "validator_types" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "111abfe30072511849c5910134e8baf8dc05de4c0e5903d681cbd5c9c4d611e3" +dependencies = [ + "proc-macro2", + "syn 1.0.109", +] [[package]] name = "version_check" @@ -1890,6 +2316,24 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" +[[package]] +name = "winnow" +version = "0.5.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" +dependencies = [ + "memchr", +] + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + [[package]] name = "zerocopy" version = "0.7.26" @@ -1907,7 +2351,7 @@ checksum = "dd7e48ccf166952882ca8bd778a43502c64f33bf94c12ebe2a7f08e5a0f6689f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.53", ] [[package]] diff --git a/rollup-http/rollup-http-server/Cargo.toml b/rollup-http/rollup-http-server/Cargo.toml index f0c53827..1ba18f4c 100644 --- a/rollup-http/rollup-http-server/Cargo.toml +++ b/rollup-http/rollup-http-server/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "rollup-http-server" -version = "0.1.0" +version = "0.2.0" edition = "2021" -authors = ["Marko Atanasievski "] +authors = ["Marko Atanasievski , Sofia Rodrigues , Alex Mikhalevich "] [lib] name = "rollup_http_server" @@ -17,7 +17,10 @@ getopts = "0.2" libc = "0.2" regex = "1.5.5" actix-web = "4.0.0-rc.2" +validator = { version = "0.16", features = ["derive"] } actix-server = "2.0" +actix-web-validator = "5.0.1" +lazy_static = "1.4.0" serde = { version = "1.0", features = ["derive"]} serde_json = "1.0" log = "0.4" @@ -28,20 +31,18 @@ hyper = { version = "0.14", features = ["http1", "runtime", "client"] } hex = "0.4" rstest = "0.12" - [build-dependencies] -bindgen = "0.59" +bindgen = "0.69.4" cc = "1.0" tonic-build = "0.5" [dev-dependencies] rollup-http-client = {path = "../rollup-http-client"} - - +rand = "0.8.5" +ethabi = "18.0.0" [profile.release] strip = true lto = true # Enable Link Time Optimization opt-level = "z" # Optimize for size. codegen-units = 1 # Reduce number of codegen units to increase optimizations, but slower build -# panic = "abort" # Abort on panic diff --git a/rollup-http/rollup-http-server/README.md b/rollup-http/rollup-http-server/README.md index d1f8461c..ed5b2236 100644 --- a/rollup-http/rollup-http-server/README.md +++ b/rollup-http/rollup-http-server/README.md @@ -2,25 +2,25 @@ For Cartesi decentralized application to communicate with the client outside of emulator, `/dev/rollup` linux device is used. Rollup HTTP server translates requests read from Linux device to http `advance/inspect` requests and conveys them to the DApp using its HTTP api interface. DApp communicates results of its execution to the outside world by using `voucher/notice/report/finish` API of the Rollup HTTP Server. -Rollup HTTP Server application implements interface defined [here](https://github.com/cartesi/rollups/blob/develop/openapi/rollup.yaml) and DApp application as http client pools Rollup HTTP Server for new requests, and pushes to it results of request processing voucher/notices/reports. +Rollup HTTP Server application implements interface defined [here](https://github.com/cartesi/rollups/blob/develop/openapi/rollup.yaml) and DApp application as http client pools Rollup HTTP Server for new requests, and pushes to it results of request processing voucher/notices/reports. ## Getting Started This project requires Rust. To install Rust follow the instructions [here](https://www.rust-lang.org/tools/install). -###Build using toolchain docker +### Build using toolchain docker ```shell -$ ./build.sh +$ ./build-with-toolchain.sh ``` ### Run tests ```shell -$ USE_ROLLUP_BINDINGS_MOCK=1 cargo test -- --show-output --test-threads=1 +$ CPATH=":$CPATH" RUSTFLAGS="-L /path/to/libcmt/lib" cargo test -- --show-output --test-threads=1 ``` ## License The http-dispatcher project and all contributions are licensed under -[APACHE 2.0](https://www.apache.org/licenses/LICENSE-2.0). Please review our [LICENSE](LICENSE) file. \ No newline at end of file +[APACHE 2.0](https://www.apache.org/licenses/LICENSE-2.0). Please review our [LICENSE](LICENSE) file. diff --git a/rollup-http/rollup-http-server/build-with-toolchain.sh b/rollup-http/rollup-http-server/build-with-toolchain.sh index 4308d8f9..386ffac2 100755 --- a/rollup-http/rollup-http-server/build-with-toolchain.sh +++ b/rollup-http/rollup-http-server/build-with-toolchain.sh @@ -6,8 +6,17 @@ RISCV_ARCH="${RISCV_ARCH:-rv64gc}" RISCV_ABI="${RISCV_ABI:-lp64d}" CONTAINER_BASE="${CONTAINER_BASE:-/opt/cartesi/tools}" -docker run --rm -e USER=`id -u -n` -e GROUP=`id -g -n` -e UID=`id -u` -e GID=`id -g` -v `pwd`/../:$CONTAINER_BASE \ ---env CC=riscv64-cartesi-linux-gnu-gcc --env CXX=riscv64-cartesi-linux-gnu-g++ --env CFLAGS="-march=$RISCV_ARCH -mabi=$RISCV_ABI" \ +CMD="make -C sys-utils/libcmt install; cd $CONTAINER_BASE/rollup-http/rollup-http-server; cargo build --target riscv64gc-unknown-linux-gnu --release" + +cargo clean + +docker run --rm -e USER=`id -u -n` -e GROUP=`id -g -n` -e UID=`id -u` -e GID=`id -g` -v `pwd`/../../:$CONTAINER_BASE \ +--env CC=riscv64-cartesi-linux-gnu-gcc \ +--env CXX=riscv64-cartesi-linux-gnu-g++ \ +--env TOOLCHAIN_PREFIX=riscv64-cartesi-linux-gnu- \ +--env CFLAGS="-march=$RISCV_ARCH -mabi=$RISCV_ABI" \ --env CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER=riscv64-cartesi-linux-gnu-gcc \ --w $CONTAINER_BASE/rollup-http-server $TOOLCHAIN_IMAGE:$TOOLCHAIN_TAG \ -cargo build --target riscv64gc-unknown-linux-gnu --release +--env TARGET_PREFIX=$CONTAINER_BASE/libcmt \ +--env CPATH=$CONTAINER_BASE/libcmt/include \ +--env RUSTFLAGS="-L $CONTAINER_BASE/libcmt/lib" \ +-w $CONTAINER_BASE $TOOLCHAIN_IMAGE:$TOOLCHAIN_TAG /bin/sh -c "$CMD" diff --git a/rollup-http/rollup-http-server/build.rs b/rollup-http/rollup-http-server/build.rs index 37a540fb..45e22558 100644 --- a/rollup-http/rollup-http-server/build.rs +++ b/rollup-http/rollup-http-server/build.rs @@ -14,20 +14,25 @@ // limitations under the License. // +use std::env; +use std::path::PathBuf; + extern crate cc; fn main() { - println!("cargo:rerun-if-changed=src/rollup/bindings.c,src/rollup/bindings.h,tests/rollup_test_bindings.c,tests/rollup_test.h"); - let test = std::env::var("USE_ROLLUP_BINDINGS_MOCK").unwrap_or("0".to_string()); - if test == "1" { - cc::Build::new() - .file("tests/rollup_test_bindings.c") - .compile("libtest_bindings.a"); - println!("cargo:rustc-link-lib=test_bindings"); - } else { - cc::Build::new() - .file("src/rollup/bindings.c") - .compile("libbindings.a"); - println!("cargo:rustc-link-lib=bindings"); - } + // link the libcmt shared library + println!("cargo:rustc-link-lib=cmt"); + + let bindings = bindgen::Builder::default() + // the input header we would like to generate bindings for + .header("src/rollup/wrapper.h") + // invalidate the built crate whenever any of the included header files changed + .parse_callbacks(Box::new(bindgen::CargoCallbacks::new())) + .generate() + .expect("Unable to generate bindings"); + + let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); + bindings + .write_to_file(out_path.join("bindings.rs")) + .expect("Couldn't write bindings!"); } diff --git a/rollup-http/rollup-http-server/src/dapp_process.rs b/rollup-http/rollup-http-server/src/dapp_process.rs index 931fce51..021c0af2 100644 --- a/rollup-http/rollup-http-server/src/dapp_process.rs +++ b/rollup-http/rollup-http-server/src/dapp_process.rs @@ -14,16 +14,15 @@ // limitations under the License. // -use std::os::unix::io::RawFd; use std::sync::Arc; use async_mutex::Mutex; use tokio::process::Command; -use crate::rollup::{self, Exception}; +use crate::rollup::{self, Exception, RollupFd}; /// Execute the dapp command and throw a rollup exception if it fails or exits -pub async fn run(args: Vec, rollup_fd: Arc>) { +pub async fn run(args: Vec, rollup_fd: Arc>) { log::info!("starting dapp: {}", args.join(" ")); let task = tokio::task::spawn_blocking(move || Command::new(&args[0]).args(&args[1..]).spawn()); let message = match task.await { @@ -40,7 +39,7 @@ pub async fn run(args: Vec, rollup_fd: Arc>) { let exception = Exception { payload: String::from("0x") + &hex::encode(message), }; - match rollup::rollup_throw_exception(*rollup_fd.lock().await, &exception) { + match rollup::rollup_throw_exception(&*rollup_fd.lock().await, &exception) { Ok(_) => { log::debug!("exception successfully thrown {:#?}", exception); } diff --git a/rollup-http/rollup-http-server/src/http_service.rs b/rollup-http/rollup-http-server/src/http_service.rs index c650d68a..67fc14c6 100644 --- a/rollup-http/rollup-http-server/src/http_service.rs +++ b/rollup-http/rollup-http-server/src/http_service.rs @@ -14,18 +14,18 @@ // limitations under the License. // -use std::os::unix::io::RawFd; use std::sync::Arc; -use actix_web::{middleware::Logger, web::Data, web::Json, App, HttpResponse, HttpServer}; +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 crate::config::Config; -use crate::rollup; +use crate::rollup::{self, RollupFd}; use crate::rollup::{ - AdvanceRequest, Exception, InspectRequest, Notice, Report, RollupRequest, Voucher, + AdvanceRequest, Exception, InspectRequest, Notice, Report, RollupRequest, FinishRequest, Voucher, }; #[derive(Debug, Serialize, Deserialize)] @@ -40,7 +40,7 @@ enum RollupHttpRequest { /// Create new instance of http server pub fn create_server( config: &Config, - rollup_fd: Arc>, + rollup_fd: Arc>, ) -> std::io::Result { let server = HttpServer::new(move || { let data = Data::new(Mutex::new(Context { @@ -64,7 +64,7 @@ pub fn create_server( /// Create and run new instance of http server pub async fn run( config: &Config, - rollup_fd: Arc>, + rollup_fd: Arc>, server_ready: Arc, ) -> std::io::Result<()> { log::info!("starting http dispatcher http service!"); @@ -90,7 +90,7 @@ async fn voucher(mut voucher: Json, data: Data>) -> Http } let context = data.lock().await; // Write voucher to linux rollup device - return match rollup::rollup_write_voucher(*context.rollup_fd.lock().await, &mut voucher.0) { + return match rollup::rollup_write_voucher(&*context.rollup_fd.lock().await, &mut voucher.0) { Ok(voucher_index) => { log::debug!("voucher successfully inserted {:#?}", voucher); HttpResponse::Created().json(IndexResponse { @@ -114,7 +114,7 @@ async fn notice(mut notice: Json, data: Data>) -> HttpRes log::debug!("received notice request"); let context = data.lock().await; // Write notice to linux rollup device - return match rollup::rollup_write_notice(*context.rollup_fd.lock().await, &mut notice.0) { + return match rollup::rollup_write_notice(&*context.rollup_fd.lock().await, &mut notice.0) { Ok(notice_index) => { log::debug!("notice successfully inserted {:#?}", notice); HttpResponse::Created().json(IndexResponse { @@ -135,7 +135,7 @@ async fn report(report: Json, data: Data>) -> HttpRespons log::debug!("received report request"); let context = data.lock().await; // Write report to linux rollup device - return match rollup::rollup_write_report(*context.rollup_fd.lock().await, &report.0) { + return match rollup::rollup_write_report(&*context.rollup_fd.lock().await, &report.0) { Ok(_) => { log::debug!("report successfully inserted {:#?}", report); HttpResponse::Accepted().body("") @@ -157,7 +157,7 @@ async fn exception(exception: Json, data: Data>) -> Ht let context = data.lock().await; // Throw an exception - return match rollup::rollup_throw_exception(*context.rollup_fd.lock().await, &exception.0) { + return match rollup::rollup_throw_exception(&*context.rollup_fd.lock().await, &exception.0) { Ok(_) => { log::debug!("exception successfully thrown {:#?}", exception); HttpResponse::Accepted().body("") @@ -190,7 +190,7 @@ async fn finish(finish: Json, data: Data>) -> Http let context = data.lock().await; let rollup_fd = context.rollup_fd.lock().await; // Write finish request, read indicator for next request - let new_rollup_request = match rollup::perform_rollup_finish_request(*rollup_fd, accept).await { + let new_rollup_request = match rollup::perform_rollup_finish_request(&*rollup_fd).await { Ok(finish_request) => { // Received new request, process it log::info!( @@ -201,7 +201,7 @@ async fn finish(finish: Json, data: Data>) -> Http _ => "UNKNOWN", } ); - match rollup::handle_rollup_requests(*rollup_fd, finish_request).await { + match rollup::handle_rollup_requests(&*rollup_fd, finish_request).await { Ok(rollup_request) => rollup_request, Err(e) => { let error_message = format!( @@ -237,11 +237,6 @@ async fn finish(finish: Json, data: Data>) -> Http .json(http_rollup_request) } -#[derive(Debug, Clone, Deserialize)] -struct FinishRequest { - status: String, -} - #[derive(Debug, Clone, Serialize)] struct IndexResponse { index: u64, @@ -260,5 +255,5 @@ struct Error { } struct Context { - pub rollup_fd: Arc>, + pub rollup_fd: Arc>, } diff --git a/rollup-http/rollup-http-server/src/main.rs b/rollup-http/rollup-http-server/src/main.rs index c38bacea..cca29199 100644 --- a/rollup-http/rollup-http-server/src/main.rs +++ b/rollup-http/rollup-http-server/src/main.rs @@ -14,15 +14,12 @@ // limitations under the License. // -use std::fs::File; use std::io::ErrorKind; -#[cfg(unix)] -use std::os::unix::io::{IntoRawFd, RawFd}; use std::sync::Arc; use async_mutex::Mutex; use getopts::{Options, ParsingStyle}; -use rollup_http_server::{config::Config, dapp_process, http_service, rollup}; +use rollup_http_server::{config::Config, dapp_process, http_service, rollup::RollupFd}; use tokio::sync::Notify; fn print_usage(program: &str, opts: Options) { @@ -100,16 +97,7 @@ async fn main() -> std::io::Result<()> { .unwrap(); } - // Open rollup device - let rollup_file = match File::open(rollup::ROLLUP_DEVICE_NAME) { - Ok(file) => file, - Err(e) => { - log::error!("error opening rollup device {}", e.to_string()); - return Err(e); - } - }; - - let rollup_fd: Arc> = Arc::new(Mutex::new(rollup_file.into_raw_fd())); + let rollup_fd: Arc> = Arc::new(Mutex::new(RollupFd::create().unwrap())); let server_ready = Arc::new(Notify::new()); // In another thread, wait until the server is ready and then start the dapp diff --git a/rollup-http/rollup-http-server/src/rollup/bindings.c b/rollup-http/rollup-http-server/src/rollup/bindings.c deleted file mode 100644 index 86628c41..00000000 --- a/rollup-http/rollup-http-server/src/rollup/bindings.c +++ /dev/null @@ -1,143 +0,0 @@ -/* Copyright Cartesi and individual authors (see AUTHORS) - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "bindings.h" -#include - -static int resize_bytes(struct rollup_bytes *bytes, uint64_t size) { - if (bytes->length < size) { - uint8_t *new_data = (uint8_t *) realloc(bytes->data, size); - if (!new_data) { - return -1; - } - bytes->length = size; - bytes->data = new_data; - } - return 0; -} - -/* Finishes processing of current advance or inspect. - * Returns 0 on success, -1 on error */ -int rollup_finish_request(int fd, struct rollup_finish *finish, bool accept) { - int res = 0; - memset(finish, 0, sizeof(*finish)); - finish->accept_previous_request = accept; - res = ioctl(fd, IOCTL_ROLLUP_FINISH, (unsigned long) finish); - return res; -} - -/* Obtains arguments to advance state - * Outputs metadata and payload in structs - * Returns 0 on success, -1 on error */ -int rollup_read_advance_state_request(int fd, struct rollup_finish *finish, struct rollup_bytes *bytes, - struct rollup_input_metadata *metadata) { - struct rollup_advance_state req; - int res = 0; - if (resize_bytes(bytes, finish->next_request_payload_length) != 0) { - fprintf(stderr, "Failed growing payload buffer\n"); - return -1; - } - memset(&req, 0, sizeof(req)); - req.payload = *bytes; - res = ioctl(fd, IOCTL_ROLLUP_READ_ADVANCE_STATE, (unsigned long) &req); - if (res != 0) { - fprintf(stderr, "IOCTL_ROLLUP_READ_ADVANCE_STATE returned error (%d), err message: %s\n", res, strerror(errno)); - } - *metadata = req.metadata; - return res; -} - -/* Obtains query of inspect state request - * Returns 0 on success, -1 on error */ -int rollup_read_inspect_state_request(int fd, struct rollup_finish *finish, struct rollup_bytes *query) { - struct rollup_inspect_state req; - int res = 0; - if (resize_bytes(query, finish->next_request_payload_length) != 0) { - fprintf(stderr, "Failed growing payload buffer\n"); - return -1; - } - memset(&req, 0, sizeof(req)); - req.payload = *query; - res = ioctl(fd, IOCTL_ROLLUP_READ_INSPECT_STATE, (unsigned long) &req); - if (res != 0) { - fprintf(stderr, "IOCTL_ROLLUP_READ_INSPECT_STATE returned error (%d), err message: %s\n", res, strerror(errno)); - return res; - } - return 0; -} - -/* Outputs a new voucher. - * voucher_index is filled with new index from the driver - * Returns 0 on success, -1 on error */ -int rollup_write_voucher(int fd, uint8_t destination[CARTESI_ROLLUP_ADDRESS_SIZE], struct rollup_bytes *bytes, - uint64_t *voucher_index) { - struct rollup_voucher v; - memset(&v, 0, sizeof(v)); - memcpy(v.destination, destination, CARTESI_ROLLUP_ADDRESS_SIZE); - v.payload = *bytes; - int res = ioctl(fd, IOCTL_ROLLUP_WRITE_VOUCHER, (unsigned long) &v); - if (res != 0) { - fprintf(stderr, "IOCTL_ROLLUP_WRITE_VOUCHER returned error %d, err message: %s\n", res, strerror(errno)); - return res; - } - *voucher_index = v.index; - return 0; -} - -/* Outputs a new notice. - * notice_index is filled with new index from the driver - * Returns 0 on success, -1 on error */ -int rollup_write_notice(int fd, struct rollup_bytes *bytes, uint64_t *notice_index) { - struct rollup_notice n; - memset(&n, 0, sizeof(n)); - n.payload = *bytes; - int res = ioctl(fd, IOCTL_ROLLUP_WRITE_NOTICE, (unsigned long) &n); - if (res != 0) { - fprintf(stderr, "IOCTL_ROLLUP_WRITE_NOTICE returned error %d, err message: %s\n", res, strerror(errno)); - return res; - } - *notice_index = n.index; - return 0; -} - -/* Outputs a new report. - * Returns 0 on success, -1 on error */ -int rollup_write_report(int fd, struct rollup_bytes *bytes) { - struct rollup_report r; - memset(&r, 0, sizeof(r)); - r.payload = *bytes; - int res = ioctl(fd, IOCTL_ROLLUP_WRITE_REPORT, (unsigned long) &r); - if (res != 0) { - fprintf(stderr, "IOCTL_ROLLUP_WRITE_REPORT returned error %d, err message: %s\n", res, strerror(errno)); - return res; - } - - return 0; -} - -/* Outputs a dapp exception. - * Returns 0 on success, -1 on error */ -int rollup_throw_exception(int fd, struct rollup_bytes *bytes) { - struct rollup_exception e; - memset(&e, 0, sizeof(e)); - e.payload = *bytes; - int res = ioctl(fd, IOCTL_ROLLUP_THROW_EXCEPTION, (unsigned long) &e); - if (res != 0) { - fprintf(stderr, "IOCTL_ROLLUP_THROW_EXCEPTION returned error %d, err message: %s\n", res, strerror(errno)); - return res; - } - return 0; -} diff --git a/rollup-http/rollup-http-server/src/rollup/bindings.h b/rollup-http/rollup-http-server/src/rollup/bindings.h deleted file mode 100644 index 766a14b0..00000000 --- a/rollup-http/rollup-http-server/src/rollup/bindings.h +++ /dev/null @@ -1,46 +0,0 @@ -/* Copyright Cartesi and individual authors (see AUTHORS) - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* C interfaces that are converted to rust using bindgen (https://github.com/rust-lang/rust-bindgen) - * command to generate Rust file from rollup C interface. In case that C rollup bindings are updated, - * `bindings.rs` file needs to be regenerated using following procedure: - * Add toolchain `riscv64-cartesi-linux-gnu` to the shell execution path - * $ cd linux/rollup/http/http-dispatcher/src/rollup - * $ bindgen ./bindings.h -o ./bindings.rs --whitelist-var '^IOCTL.*' --whitelist-var '^CARTESI.*' --whitelist-type - "^rollup_.*" --whitelist-function '^rollup.*'\ - -- --sysroot=/opt/riscv/riscv64-cartesi-linux-gnu/riscv64-cartesi-linux-gnu/sysroot - --target=riscv64-cartesi-linux-gnu -march=rv64gc -mabi=lp64d -*/ - -#include -#include -#include -#include -#include -#include - -#include -#include - -int rollup_finish_request(int fd, struct rollup_finish *finish, bool accept); -int rollup_read_advance_state_request(int fd, struct rollup_finish *finish, struct rollup_bytes *bytes, - struct rollup_input_metadata *metadata); -int rollup_read_inspect_state_request(int fd, struct rollup_finish *finish, struct rollup_bytes *query); -int rollup_write_voucher(int fd, uint8_t destination[CARTESI_ROLLUP_ADDRESS_SIZE], struct rollup_bytes *bytes, - uint64_t *voucher_index); -int rollup_write_notice(int fd, struct rollup_bytes *bytes, uint64_t *notice_index); -int rollup_write_report(int fd, struct rollup_bytes *bytes); -int rollup_throw_exception(int fd, struct rollup_bytes *bytes); diff --git a/rollup-http/rollup-http-server/src/rollup/bindings.rs b/rollup-http/rollup-http-server/src/rollup/bindings.rs deleted file mode 100644 index ff4cf8d4..00000000 --- a/rollup-http/rollup-http-server/src/rollup/bindings.rs +++ /dev/null @@ -1,414 +0,0 @@ -/* automatically generated by rust-bindgen 0.58.1 */ -#![allow(dead_code)] -#![allow(unused_variables)] -#![allow(non_upper_case_globals)] -#![allow(non_camel_case_types)] -#![allow(non_snake_case)] - -pub const CARTESI_ROLLUP_ADVANCE_STATE: u32 = 0; -pub const CARTESI_ROLLUP_INSPECT_STATE: u32 = 1; -pub const CARTESI_ROLLUP_ADDRESS_SIZE: u32 = 20; -pub type __uint8_t = ::std::os::raw::c_uchar; -pub type __uint64_t = ::std::os::raw::c_ulong; -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct rollup_bytes { - pub data: *mut ::std::os::raw::c_uchar, - pub length: u64, -} -#[test] -fn bindgen_test_layout_rollup_bytes() { - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(rollup_bytes)) - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rollup_bytes)) - ); - assert_eq!( - unsafe { &(*(::std::ptr::null::())).data as *const _ as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rollup_bytes), - "::", - stringify!(data) - ) - ); - assert_eq!( - unsafe { &(*(::std::ptr::null::())).length as *const _ as usize }, - 8usize, - concat!( - "Offset of field: ", - stringify!(rollup_bytes), - "::", - stringify!(length) - ) - ); -} -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct rollup_input_metadata { - pub msg_sender: [u8; 20usize], - pub block_number: u64, - pub timestamp: u64, - pub epoch_index: u64, - pub input_index: u64, -} -#[test] -fn bindgen_test_layout_rollup_input_metadata() { - assert_eq!( - ::std::mem::size_of::(), - 56usize, - concat!("Size of: ", stringify!(rollup_input_metadata)) - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rollup_input_metadata)) - ); - assert_eq!( - unsafe { - &(*(::std::ptr::null::())).msg_sender as *const _ as usize - }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rollup_input_metadata), - "::", - stringify!(msg_sender) - ) - ); - assert_eq!( - unsafe { - &(*(::std::ptr::null::())).block_number as *const _ as usize - }, - 24usize, - concat!( - "Offset of field: ", - stringify!(rollup_input_metadata), - "::", - stringify!(block_number) - ) - ); - assert_eq!( - unsafe { &(*(::std::ptr::null::())).timestamp as *const _ as usize }, - 32usize, - concat!( - "Offset of field: ", - stringify!(rollup_input_metadata), - "::", - stringify!(timestamp) - ) - ); - assert_eq!( - unsafe { - &(*(::std::ptr::null::())).epoch_index as *const _ as usize - }, - 40usize, - concat!( - "Offset of field: ", - stringify!(rollup_input_metadata), - "::", - stringify!(epoch_index) - ) - ); - assert_eq!( - unsafe { - &(*(::std::ptr::null::())).input_index as *const _ as usize - }, - 48usize, - concat!( - "Offset of field: ", - stringify!(rollup_input_metadata), - "::", - stringify!(input_index) - ) - ); -} -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct rollup_advance_state { - pub metadata: rollup_input_metadata, - pub payload: rollup_bytes, -} -#[test] -fn bindgen_test_layout_rollup_advance_state() { - assert_eq!( - ::std::mem::size_of::(), - 72usize, - concat!("Size of: ", stringify!(rollup_advance_state)) - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rollup_advance_state)) - ); - assert_eq!( - unsafe { &(*(::std::ptr::null::())).metadata as *const _ as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rollup_advance_state), - "::", - stringify!(metadata) - ) - ); - assert_eq!( - unsafe { &(*(::std::ptr::null::())).payload as *const _ as usize }, - 56usize, - concat!( - "Offset of field: ", - stringify!(rollup_advance_state), - "::", - stringify!(payload) - ) - ); -} -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct rollup_inspect_state { - pub payload: rollup_bytes, -} -#[test] -fn bindgen_test_layout_rollup_inspect_state() { - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(rollup_inspect_state)) - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rollup_inspect_state)) - ); - assert_eq!( - unsafe { &(*(::std::ptr::null::())).payload as *const _ as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rollup_inspect_state), - "::", - stringify!(payload) - ) - ); -} -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct rollup_finish { - pub accept_previous_request: bool, - pub next_request_type: ::std::os::raw::c_int, - pub next_request_payload_length: ::std::os::raw::c_int, -} -#[test] -fn bindgen_test_layout_rollup_finish() { - assert_eq!( - ::std::mem::size_of::(), - 12usize, - concat!("Size of: ", stringify!(rollup_finish)) - ); - assert_eq!( - ::std::mem::align_of::(), - 4usize, - concat!("Alignment of ", stringify!(rollup_finish)) - ); - assert_eq!( - unsafe { - &(*(::std::ptr::null::())).accept_previous_request as *const _ as usize - }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rollup_finish), - "::", - stringify!(accept_previous_request) - ) - ); - assert_eq!( - unsafe { &(*(::std::ptr::null::())).next_request_type as *const _ as usize }, - 4usize, - concat!( - "Offset of field: ", - stringify!(rollup_finish), - "::", - stringify!(next_request_type) - ) - ); - assert_eq!( - unsafe { - &(*(::std::ptr::null::())).next_request_payload_length as *const _ - as usize - }, - 8usize, - concat!( - "Offset of field: ", - stringify!(rollup_finish), - "::", - stringify!(next_request_payload_length) - ) - ); -} -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct rollup_voucher { - pub destination: [u8; 20usize], - pub payload: rollup_bytes, - pub index: u64, -} -#[test] -fn bindgen_test_layout_rollup_voucher() { - assert_eq!( - ::std::mem::size_of::(), - 48usize, - concat!("Size of: ", stringify!(rollup_voucher)) - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rollup_voucher)) - ); - assert_eq!( - unsafe { &(*(::std::ptr::null::())).destination as *const _ as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rollup_voucher), - "::", - stringify!(destination) - ) - ); - assert_eq!( - unsafe { &(*(::std::ptr::null::())).payload as *const _ as usize }, - 24usize, - concat!( - "Offset of field: ", - stringify!(rollup_voucher), - "::", - stringify!(payload) - ) - ); - assert_eq!( - unsafe { &(*(::std::ptr::null::())).index as *const _ as usize }, - 40usize, - concat!( - "Offset of field: ", - stringify!(rollup_voucher), - "::", - stringify!(index) - ) - ); -} -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct rollup_notice { - pub payload: rollup_bytes, - pub index: u64, -} -#[test] -fn bindgen_test_layout_rollup_notice() { - assert_eq!( - ::std::mem::size_of::(), - 24usize, - concat!("Size of: ", stringify!(rollup_notice)) - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rollup_notice)) - ); - assert_eq!( - unsafe { &(*(::std::ptr::null::())).payload as *const _ as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rollup_notice), - "::", - stringify!(payload) - ) - ); - assert_eq!( - unsafe { &(*(::std::ptr::null::())).index as *const _ as usize }, - 16usize, - concat!( - "Offset of field: ", - stringify!(rollup_notice), - "::", - stringify!(index) - ) - ); -} -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct rollup_report { - pub payload: rollup_bytes, -} -#[test] -fn bindgen_test_layout_rollup_report() { - assert_eq!( - ::std::mem::size_of::(), - 16usize, - concat!("Size of: ", stringify!(rollup_report)) - ); - assert_eq!( - ::std::mem::align_of::(), - 8usize, - concat!("Alignment of ", stringify!(rollup_report)) - ); - assert_eq!( - unsafe { &(*(::std::ptr::null::())).payload as *const _ as usize }, - 0usize, - concat!( - "Offset of field: ", - stringify!(rollup_report), - "::", - stringify!(payload) - ) - ); -} - -extern "C" { - pub fn rollup_finish_request( - fd: ::std::os::raw::c_int, - finish: *mut rollup_finish, - accept: bool, - ) -> ::std::os::raw::c_int; - - pub fn rollup_read_advance_state_request( - fd: ::std::os::raw::c_int, - finish: *mut rollup_finish, - bytes: *mut rollup_bytes, - metadata: *mut rollup_input_metadata, - ) -> ::std::os::raw::c_int; - - pub fn rollup_read_inspect_state_request( - fd: ::std::os::raw::c_int, - finish: *mut rollup_finish, - query: *mut rollup_bytes, - ) -> ::std::os::raw::c_int; - - pub fn rollup_write_voucher( - fd: ::std::os::raw::c_int, - destination: *mut u8, - bytes: *mut rollup_bytes, - voucher_index: *mut u64, - ) -> ::std::os::raw::c_int; - - pub fn rollup_write_notice( - fd: ::std::os::raw::c_int, - bytes: *mut rollup_bytes, - notice_index: *mut u64, - ) -> ::std::os::raw::c_int; - - pub fn rollup_write_report( - fd: ::std::os::raw::c_int, - bytes: *mut rollup_bytes, - ) -> ::std::os::raw::c_int; - - pub fn rollup_throw_exception( - fd: ::std::os::raw::c_int, - bytes: *mut rollup_bytes, - ) -> ::std::os::raw::c_int; -} diff --git a/rollup-http/rollup-http-server/src/rollup/mod.rs b/rollup-http/rollup-http-server/src/rollup/mod.rs index 3104f8af..eb2f5860 100644 --- a/rollup-http/rollup-http-server/src/rollup/mod.rs +++ b/rollup-http/rollup-http-server/src/rollup/mod.rs @@ -14,19 +14,57 @@ // limitations under the License. // -pub const ROLLUP_DEVICE_NAME: &str = "/dev/rollup"; +#![allow(non_upper_case_globals)] +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] -use serde::{Deserialize, Serialize}; use std::io::ErrorKind; -use std::os::unix::prelude::RawFd; -mod bindings; -pub use bindings::CARTESI_ROLLUP_ADDRESS_SIZE; -pub use bindings::CARTESI_ROLLUP_ADVANCE_STATE; -pub use bindings::CARTESI_ROLLUP_INSPECT_STATE; +use libc::c_void; +use serde::{Deserialize, Serialize}; +use validator::Validate; +use regex::Regex; +use lazy_static::lazy_static; + +include!(concat!(env!("OUT_DIR"), "/bindings.rs")); + +#[derive(Clone)] +pub struct RollupFd(*mut cmt_rollup_t); + +impl RollupFd { + pub fn create() -> Result { + unsafe { + let zeroed = Box::leak(Box::new(std::mem::zeroed::())); + let result = cmt_rollup_init(zeroed); + if result != 0 { + Err(result) + } else { + Ok(RollupFd(zeroed)) + } + } + } +} + +impl Drop for RollupFd { + fn drop(&mut self) { + unsafe { + cmt_rollup_fini(self.0); + drop(Box::from_raw(self.0)); + } + } +} + +unsafe impl Sync for RollupFd {} +unsafe impl Send for RollupFd {} + +pub const REQUEST_TYPE_ADVANCE_STATE: u32 = 0; +pub const REQUEST_TYPE_INSPECT_STATE: u32 = 1; +pub const CARTESI_ROLLUP_ADDRESS_SIZE: u32 = 20; -pub const REQUEST_TYPE_ADVANCE_STATE: &str = "advance_state"; -pub const REQUEST_TYPE_INSPECT_STATE: &str = "inspect_state"; +lazy_static! { + static ref ETH_ADDR_REGEXP: Regex = Regex::new(r"0x[0-9a-fA-F]{1,42}$").unwrap(); + static ref ETH_U256_REGEXP: Regex = Regex::new(r"0x[0-9a-fA-F]{1,64}$").unwrap(); +} #[derive(Debug, Default)] pub struct RollupError { @@ -53,35 +91,25 @@ impl std::error::Error for RollupError {} pub struct RollupFinish { pub accept_previous_request: bool, pub next_request_type: i32, - pub next_request_payload_length: i32, + pub next_request_payload_length: usize, } -impl From for bindings::rollup_finish { +impl From for cmt_rollup_finish_t { fn from(other: RollupFinish) -> Self { - bindings::rollup_finish { + cmt_rollup_finish_t { next_request_type: other.next_request_type, accept_previous_request: other.accept_previous_request, - next_request_payload_length: other.next_request_payload_length, + next_request_payload_length: other.next_request_payload_length as u32, } } } -impl From<&mut RollupFinish> for bindings::rollup_finish { +impl From<&mut RollupFinish> for cmt_rollup_finish_t { fn from(other: &mut RollupFinish) -> Self { - bindings::rollup_finish { - next_request_type: other.next_request_type, - accept_previous_request: other.accept_previous_request, - next_request_payload_length: other.next_request_payload_length, - } - } -} - -impl From for RollupFinish { - fn from(other: bindings::rollup_finish) -> Self { - RollupFinish { + cmt_rollup_finish_t { next_request_type: other.next_request_type, accept_previous_request: other.accept_previous_request, - next_request_payload_length: other.next_request_payload_length, + next_request_payload_length: other.next_request_payload_length as u32, } } } @@ -89,26 +117,34 @@ impl From for RollupFinish { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AdvanceMetadata { pub msg_sender: String, - pub epoch_index: u64, pub input_index: u64, pub block_number: u64, - pub timestamp: u64, + pub block_timestamp: u64, } -impl From for AdvanceMetadata { - fn from(other: bindings::rollup_input_metadata) -> Self { +impl From for AdvanceMetadata { + fn from(other: cmt_rollup_advance_t) -> Self { let mut address = "0x".to_string(); address.push_str(&hex::encode(&other.msg_sender)); AdvanceMetadata { - input_index: other.input_index, - epoch_index: other.epoch_index, - timestamp: other.timestamp, + input_index: other.index, + block_timestamp: other.block_timestamp, block_number: other.block_number, msg_sender: address, } } } +impl From for RollupFinish { + fn from(other: cmt_rollup_finish_t) -> Self { + RollupFinish { + next_request_type: other.next_request_type, + accept_previous_request: other.accept_previous_request, + next_request_payload_length: other.next_request_payload_length as usize, + } + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AdvanceRequest { pub metadata: AdvanceMetadata, @@ -125,28 +161,36 @@ pub enum RollupRequest { Advance(AdvanceRequest), } +#[derive(Debug, Clone, Deserialize, Validate)] +pub struct FinishRequest { + pub status: String, +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct InspectReport { - pub reports: Vec, + pub reports: Vec } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize, Validate)] pub struct Notice { pub payload: String, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize, Validate)] pub struct Voucher { + #[validate(regex = "ETH_ADDR_REGEXP")] pub destination: String, + #[validate(regex = "ETH_U256_REGEXP")] + pub value: String, pub payload: String, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize, Validate)] pub struct Report { pub payload: String, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize, Validate)] pub struct Exception { pub payload: String, } @@ -156,49 +200,46 @@ pub enum RollupResponse { } pub fn rollup_finish_request( - fd: RawFd, + fd: &RollupFd, finish: &mut RollupFinish, - accept: bool, ) -> Result<(), Box> { - let mut finish_c = Box::new(bindings::rollup_finish::from(&mut *finish)); + let mut finish_c = Box::new(cmt_rollup_finish_t::from(&mut *finish)); log::debug!("writing rollup finish request, yielding"); - let res = unsafe { bindings::rollup_finish_request(fd as i32, finish_c.as_mut(), accept) }; - if res != 0 { + + let res = unsafe { cmt_rollup_finish(fd.0, finish_c.as_mut()) }; + + if res < 0 { log::error!("failed to write finish request, IOCTL error {}", res); return Err(Box::new(RollupError::new(&format!( "IOCTL_ROLLUP_FINISH returned error {}", res )))); } + *finish = RollupFinish::from(*finish_c); + log::debug!("finish request written to rollup device: {:#?}", &finish); Ok(()) } pub fn rollup_read_advance_state_request( - fd: RawFd, - finish: &mut RollupFinish, + fd: &RollupFd, ) -> Result> { - let mut finish_c = Box::new(bindings::rollup_finish::from(&mut *finish)); - let mut bytes_c = Box::new(bindings::rollup_bytes { - data: std::ptr::null::<::std::os::raw::c_uchar>() as *mut ::std::os::raw::c_uchar, - length: 0, - }); - let mut input_metadata_c = Box::new(bindings::rollup_input_metadata { + + let mut advance_request = Box::new(cmt_rollup_advance_t { + chain_id: 0, msg_sender: Default::default(), + app_contract: Default::default(), block_number: 0, - timestamp: 0, - epoch_index: 0, - input_index: 0, + block_timestamp: 0, + index: 0, + payload_length: 0, + payload: std::ptr::null::<::std::os::raw::c_uchar>() as *mut c_void, }); + let res = unsafe { - bindings::rollup_read_advance_state_request( - fd as i32, - finish_c.as_mut(), - bytes_c.as_mut(), - input_metadata_c.as_mut(), - ) + cmt_rollup_read_advance_state(fd.0, advance_request.as_mut()) }; if res != 0 { @@ -208,68 +249,73 @@ pub fn rollup_read_advance_state_request( )))); } - if bytes_c.length == 0 { + if advance_request.payload_length == 0 { log::info!("read zero size payload from advance state request"); } - let mut payload: Vec = Vec::with_capacity(bytes_c.length as usize); - if bytes_c.length > 0 { + let mut payload: Vec = Vec::with_capacity(advance_request.payload_length as usize); + if advance_request.payload_length > 0 { unsafe { - std::ptr::copy(bytes_c.data, payload.as_mut_ptr(), bytes_c.length as usize); - payload.set_len(bytes_c.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); } } let result = AdvanceRequest { - metadata: AdvanceMetadata::from(*input_metadata_c), + metadata: AdvanceMetadata::from(*advance_request), payload: "0x".to_string() + &hex::encode(&payload), }; - *finish = RollupFinish::from(*finish_c); + Ok(result) } + pub fn rollup_read_inspect_state_request( - fd: RawFd, - finish: &mut RollupFinish, + fd: &RollupFd, ) -> Result> { - let mut finish_c = Box::new(bindings::rollup_finish::from(&mut *finish)); - let mut bytes_c = Box::new(bindings::rollup_bytes { - data: std::ptr::null::<::std::os::raw::c_uchar>() as *mut ::std::os::raw::c_uchar, - length: 0, + + 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 { - bindings::rollup_read_inspect_state_request(fd as i32, finish_c.as_mut(), bytes_c.as_mut()) + cmt_rollup_read_inspect_state(fd.0, inspect_request.as_mut()) }; + if res != 0 { return Err(Box::new(RollupError::new(&format!( "IOCTL_ROLLUP_READ_INSPECT_STATE returned error {}", res )))); } - if bytes_c.length == 0 { + + if inspect_request.payload_length == 0 { log::info!("read zero size payload from inspect state request"); } - let mut payload: Vec = Vec::with_capacity(bytes_c.length as usize); - if bytes_c.length > 0 { + println!("inspect_request.payload_length: {}", inspect_request.payload_length); + let mut payload: Vec = Vec::with_capacity(inspect_request.payload_length as usize); + if inspect_request.payload_length > 0 { unsafe { - std::ptr::copy(bytes_c.data, payload.as_mut_ptr(), bytes_c.length as usize); - payload.set_len(bytes_c.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); } } let result = InspectRequest { payload: "0x".to_string() + &hex::encode(&payload), }; - *finish = RollupFinish::from(*finish_c); + Ok(result) } pub fn rollup_write_notice( - fd: RawFd, + fd: &RollupFd, notice: &mut Notice, ) -> Result> { print_notice(notice); + let binary_payload = match hex::decode(¬ice.payload[2..]) { Ok(payload) => payload, Err(_err) => { @@ -278,20 +324,21 @@ pub fn rollup_write_notice( )))); } }; + let mut buffer: Vec = Vec::with_capacity(binary_payload.len()); - let mut bytes_c = Box::new(bindings::rollup_bytes { - data: buffer.as_mut_ptr() as *mut ::std::os::raw::c_uchar, - length: binary_payload.len() as u64, - }); + let length = binary_payload.len() as u64; let mut notice_index: std::os::raw::c_ulong = 0; + let res = unsafe { std::ptr::copy( binary_payload.as_ptr(), buffer.as_mut_ptr(), binary_payload.len(), ); - bindings::rollup_write_notice(fd as i32, bytes_c.as_mut(), &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 { return Err(Box::new(RollupError::new(&format!( "IOCTL_ROLLUP_WRITE_NOTICE returned error {}", @@ -300,29 +347,42 @@ pub fn rollup_write_notice( } else { log::debug!("notice with id {} successfully written!", notice_index); } + Ok(notice_index as u64) } + pub fn rollup_write_voucher( - fd: RawFd, + fd: &RollupFd, voucher: &mut Voucher, ) -> Result> { print_voucher(voucher); + let binary_payload = match hex::decode(&voucher.payload[2..]) { Ok(payload) => payload, Err(_err) => { return Err(Box::new(RollupError::new(&format!( - "Error decoding voucher payload, payload must be in Ethereum hex binary format" + "Error decoding voucher payload, it must be in Ethereum hex binary format" )))); } }; - let mut buffer: Vec = Vec::with_capacity(binary_payload.len()); - let mut bytes_c = Box::new(bindings::rollup_bytes { - data: buffer.as_mut_ptr() as *mut ::std::os::raw::c_uchar, - length: binary_payload.len() as u64, - }); + let mut payload_buffer: Vec = Vec::with_capacity(binary_payload.len()); + let payload_data = payload_buffer.as_mut_ptr(); + let payload_length = binary_payload.len(); - let mut address_c = match hex::decode(&voucher.destination[2..]) { + 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 = 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!( @@ -336,16 +396,27 @@ pub fn rollup_write_voucher( let res = unsafe { std::ptr::copy( binary_payload.as_ptr(), - buffer.as_mut_ptr(), + payload_buffer.as_mut_ptr(), binary_payload.len(), ); - bindings::rollup_write_voucher( - fd as i32, - address_c.as_mut_ptr(), - bytes_c.as_mut(), + 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, &mut voucher_index, ) }; + if res != 0 { return Err(Box::new(RollupError::new(&format!( "IOCTL_ROLLUP_WRITE_VOUCHER returned error {}", @@ -358,8 +429,9 @@ pub fn rollup_write_voucher( Ok(voucher_index as u64) } -pub fn rollup_write_report(fd: RawFd, report: &Report) -> Result<(), Box> { +pub fn rollup_write_report(fd: &RollupFd, report: &Report) -> Result<(), Box> { print_report(report); + let binary_payload = match hex::decode(&report.payload[2..]) { Ok(payload) => payload, Err(_err) => { @@ -368,19 +440,21 @@ pub fn rollup_write_report(fd: RawFd, report: &Report) -> Result<(), Box = Vec::with_capacity(binary_payload.len()); - let mut bytes_c = Box::new(bindings::rollup_bytes { - data: buffer.as_mut_ptr() as *mut ::std::os::raw::c_uchar, - length: binary_payload.len() as u64, - }); + + let data = buffer.as_mut_ptr() as *mut c_void; + let length = binary_payload.len(); + let res = unsafe { std::ptr::copy( binary_payload.as_ptr(), buffer.as_mut_ptr(), binary_payload.len(), ); - bindings::rollup_write_report(fd as i32, bytes_c.as_mut()) + cmt_rollup_emit_report(fd.0, length as u32, data) }; + if res != 0 { return Err(Box::new(RollupError::new(&format!( "IOCTL_ROLLUP_WRITE_REPORT returned error {}", @@ -389,14 +463,16 @@ pub fn rollup_write_report(fd: RawFd, report: &Report) -> Result<(), Box Result<(), Box> { print_exception(exception); + let binary_payload = match hex::decode(&exception.payload[2..]) { Ok(payload) => payload, Err(_err) => { @@ -405,18 +481,18 @@ pub fn rollup_throw_exception( )))); } }; + let mut buffer: Vec = Vec::with_capacity(binary_payload.len()); - let mut bytes_c = Box::new(bindings::rollup_bytes { - data: buffer.as_mut_ptr() as *mut ::std::os::raw::c_uchar, - length: binary_payload.len() as u64, - }); + let length = binary_payload.len(); + let data = buffer.as_mut_ptr() as *mut c_void; + let res = unsafe { std::ptr::copy( binary_payload.as_ptr(), buffer.as_mut_ptr(), binary_payload.len(), ); - bindings::rollup_throw_exception(fd as i32, bytes_c.as_mut()) + cmt_rollup_emit_exception(fd.0, length as u32, data) }; if res != 0 { return Err(Box::new(RollupError::new(&format!( @@ -430,12 +506,16 @@ pub fn rollup_throw_exception( } pub async fn perform_rollup_finish_request( - fd: RawFd, - accept: bool, + fd: &RollupFd, ) -> std::io::Result { let mut finish_request = RollupFinish::default(); - match rollup_finish_request(fd, &mut finish_request, accept) { - Ok(_) => Ok(finish_request), + finish_request.accept_previous_request = true; + + match rollup_finish_request(fd, &mut finish_request) { + Ok(_) => { + dbg!(&finish_request); + Ok(finish_request) + } Err(e) => { log::error!("error inserting finish request, details: {}", e.to_string()); Err(std::io::Error::new(ErrorKind::Other, e.to_string())) @@ -445,16 +525,17 @@ pub async fn perform_rollup_finish_request( /// Read advance/inspect request from rollup device pub async fn handle_rollup_requests( - fd: RawFd, - mut finish_request: RollupFinish, + fd: &RollupFd, + finish_request: RollupFinish, ) -> Result { let next_request_type = finish_request.next_request_type as u32; + match next_request_type { - CARTESI_ROLLUP_ADVANCE_STATE => { + REQUEST_TYPE_ADVANCE_STATE => { log::debug!("handle advance state request..."); let advance_request = { // Read advance request from rollup device - match rollup_read_advance_state_request(fd, &mut finish_request) { + match rollup_read_advance_state_request(fd) { Ok(r) => r, Err(e) => { return Err(std::io::Error::new(ErrorKind::Other, e.to_string())); @@ -467,11 +548,11 @@ pub async fn handle_rollup_requests( // Send newly read advance request to http service Ok(RollupRequest::Advance(advance_request)) } - CARTESI_ROLLUP_INSPECT_STATE => { + REQUEST_TYPE_INSPECT_STATE => { log::debug!("handle inspect state request..."); // Read inspect request from rollup device let inspect_request = { - match rollup_read_inspect_state_request(fd, &mut finish_request) { + match rollup_read_inspect_state_request(fd) { Ok(r) => r, Err(e) => { return Err(std::io::Error::new(ErrorKind::Other, e.to_string())); @@ -506,10 +587,9 @@ pub fn print_advance(advance: &AdvanceRequest) { advance_request_printout.push_str("advance: {{msg_sender: "); format_address_printout(&advance.metadata.msg_sender, &mut advance_request_printout); advance_request_printout.push_str(&format!( - " block_number: {} timestamp: {} epoch_index: {} input_index: {} }}", + " block_number: {} block_timestamp: {} input_index: {} }}", advance.metadata.block_number, - advance.metadata.timestamp, - advance.metadata.epoch_index, + advance.metadata.block_timestamp, advance.metadata.input_index )); log::debug!("{}", &advance_request_printout); @@ -531,6 +611,7 @@ 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: "); diff --git a/rollup-http/rollup-http-server/src/rollup/wrapper.h b/rollup-http/rollup-http-server/src/rollup/wrapper.h new file mode 100644 index 00000000..e04f87c6 --- /dev/null +++ b/rollup-http/rollup-http-server/src/rollup/wrapper.h @@ -0,0 +1 @@ +#include diff --git a/rollup-http/rollup-http-server/tests/rollup-http-server-tests.rs b/rollup-http/rollup-http-server/tests/rollup-http-server-tests.rs index b421ceb3..e83368ab 100644 --- a/rollup-http/rollup-http-server/tests/rollup-http-server-tests.rs +++ b/rollup-http/rollup-http-server/tests/rollup-http-server-tests.rs @@ -23,16 +23,17 @@ use rollup_http_client::rollup::{ Exception, 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::fs::File; use std::future::Future; -use std::os::unix::io::{IntoRawFd, RawFd}; use std::sync::Arc; +use rand::Rng; +use std::env; +use std::fs::File; +use std::io::Write; -const PORT: u16 = 10010; const HOST: &str = "127.0.0.1"; -const TEST_ROLLUP_DEVICE: &str = "rollup_driver.bin"; #[allow(dead_code)] struct Context { @@ -51,17 +52,7 @@ fn run_test_http_service( host: &str, port: u16, ) -> std::io::Result> { - println!("Opening rollup device"); - // Open test rollup device - let rollup_file = match File::create(TEST_ROLLUP_DEVICE) { - Ok(file) => file, - Err(e) => { - log::error!("error opening rollup device {}", e.to_string()); - return Err(e); - } - }; - - let rollup_fd: Arc> = Arc::new(Mutex::new(rollup_file.into_raw_fd())); + let rollup_fd: Arc> = Arc::new(Mutex::new(RollupFd::create().unwrap())); let rollup_fd = rollup_fd.clone(); let http_config = Config { http_address: host.to_string(), @@ -80,8 +71,11 @@ fn run_test_http_service( async fn context_future() -> Context { let mut server_handle: Option = None; let mut count = 5; + let mut port; loop { - match run_test_http_service(HOST, PORT) { + port = rand::thread_rng().gen_range(49152..65535); + + match run_test_http_service(HOST, port) { Ok(handle) => { server_handle = handle; break; @@ -100,7 +94,7 @@ async fn context_future() -> Context { } Context { - address: format!("http://{}:{}", HOST, PORT), + address: format!("http://{}:{}", HOST, port), server_handle: server_handle.unwrap(), } } @@ -125,9 +119,42 @@ async fn test_server_instance_creation( async fn test_finish_request( context_future: impl Future, ) -> Result<(), Box> { + /* + * cast calldata 'EvmAdvance(uint256,address,address,uint256,uint256,uint256,bytes)' \ + * 0 $(cast address-zero) $(printf 0x%040x 1) 0 0 0 0xdeadbeef | xxd -r -p + */ + let advance_payload_data = "cc7dee1f00000000000000000000000000000000000000000000000000000000000\ + 0000000000000000000000000000000000000000000000000000000000000000000\ + 0000000000000000000000000000000000000000000000000000000000000000010\ + 0000000000000000000000000000000000000000000000000000000000000000000\ + 0000000000000000000000000000000000000000000000000000000000000000000\ + 0000000000000000000000000000000000000000000000000000000000000000000\ + 0000000000000000000000000000000000000000000000000000e00000000000000\ + 000000000000000000000000000000000000000000000000004deadbeef00000000\ + 000000000000000000000000000000000000000000000000"; + + /* + * inspect requests are not evm encoded + */ + let inspect_payload_data = "deadbeef"; + + let advance_binary_data = hex::decode(advance_payload_data).unwrap(); + let advance_path = "advance_payload.bin"; + let mut advance_file = File::create(advance_path)?; + advance_file.write_all(&advance_binary_data)?; + + let inspect_binary_data = hex::decode(inspect_payload_data).unwrap(); + let inspect_path = "inspect_payload.bin"; + 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_DEBUG", "yes"); + let context = context_future.await; println!("Sending finish request"); let request_response = RollupResponse::Finish(true); + match rollup_http_client::client::send_finish_request(&context.address, &request_response).await { Ok(request) => match request { @@ -137,15 +164,14 @@ async fn test_finish_request( } RollupRequest::Advance(advance_request) => { println!("Got new advance request: {:?}", advance_request); - assert_eq!(advance_request.payload.len(), 42); + assert_eq!(advance_request.payload.len(), 10); assert_eq!( advance_request.metadata.msg_sender, - "0x1111111111111111111111111111111111111111" + "0x0000000000000000000000000000000000000001" ); assert_eq!( - std::str::from_utf8(&hex::decode(&advance_request.payload[2..]).unwrap()) - .unwrap(), - "test advance request" + &advance_request.payload[2..], + "deadbeef" ); } }, @@ -160,11 +186,10 @@ async fn test_finish_request( RollupRequest::Inspect(inspect_request) => { println!("Got new inspect request: {:?}", inspect_request); context.server_handle.stop(true).await; - assert_eq!(inspect_request.payload.len(), 42); + assert_eq!(inspect_request.payload.len(), 10); assert_eq!( - std::str::from_utf8(&hex::decode(&inspect_request.payload[2..]).unwrap()) - .unwrap(), - "test inspect request" + &inspect_request.payload[2..], + "deadbeef" ); } RollupRequest::Advance(_advance_request) => { @@ -178,9 +203,40 @@ async fn test_finish_request( } } context.server_handle.stop(true).await; + + std::fs::remove_file(advance_path)?; + std::fs::remove_file(inspect_path)?; + Ok(()) } +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 decoded_voucher = ethabi::decode( + &[ethabi::ParamType::Address, ethabi::ParamType::Uint(256), ethabi::ParamType::Bytes], + &data[4..], // skip the first 4 bytes that are the function signature + ).ok().unwrap(); + + assert_eq!( + "0x".to_string() + &decoded_voucher[0].to_string(), + original_voucher.destination, + ); + assert_eq!( + "0x".to_string() + &decoded_voucher[1].to_string(), + original_voucher.value, + ); + assert_eq!( + "0x".to_string() + &decoded_voucher[2].to_string(), + original_voucher.payload, + ); +} + #[rstest] #[tokio::test] async fn test_write_voucher( @@ -190,33 +246,27 @@ async fn test_write_voucher( println!("Writing voucher"); let test_voucher_01 = Voucher { destination: "0x1111111111111111111111111111111111111111".to_string(), + value: "0xdeadbeef".to_string(), payload: "0x".to_string() + &hex::encode("voucher test payload 01"), }; let test_voucher_02 = Voucher { destination: "0x2222222222222222222222222222222222222222".to_string(), + value: "0xdeadbeef".to_string(), payload: "0x".to_string() + &hex::encode("voucher test payload 02"), }; - rollup_http_client::client::send_voucher(&context.address, test_voucher_01).await; + rollup_http_client::client::send_voucher(&context.address, test_voucher_01.clone()).await; + + check_voucher_or_fail(test_voucher_01, "none.output-0.bin"); + std::fs::remove_file("none.output-0.bin")?; + println!("Writing second voucher!"); - rollup_http_client::client::send_voucher(&context.address, test_voucher_02).await; + + rollup_http_client::client::send_voucher(&context.address, test_voucher_02.clone()).await; context.server_handle.stop(true).await; - //Read text file with results - let voucher1 = - std::fs::read_to_string("test_voucher_1.txt").expect("error reading voucher 1 file"); - assert_eq!( - voucher1, - "index: 1, payload_size: 23, payload: voucher test payload 01" - ); - std::fs::remove_file("test_voucher_1.txt")?; + check_voucher_or_fail(test_voucher_02, "none.output-0.bin"); + std::fs::remove_file("none.output-0.bin")?; - let voucher2 = - std::fs::read_to_string("test_voucher_2.txt").expect("error reading voucher 2 file"); - assert_eq!( - voucher2, - "index: 2, payload_size: 23, payload: voucher test payload 02" - ); - std::fs::remove_file("test_voucher_2.txt")?; Ok(()) } @@ -231,16 +281,24 @@ async fn test_write_notice( let test_notice = Notice { payload: "0x".to_string() + &hex::encode("notice test payload 01"), }; - rollup_http_client::client::send_notice(&context.address, test_notice).await; + rollup_http_client::client::send_notice(&context.address, test_notice.clone()).await; context.server_handle.stop(true).await; - //Read text file with results - let notice1 = - std::fs::read_to_string("test_notice_1.txt").expect("error reading test notice file"); + + // 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 decoded_notice = ethabi::decode( + &[ethabi::ParamType::Bytes], + &data[4..], // skip the first 4 bytes that are the function signature + ).ok().unwrap(); + assert_eq!( - notice1, - "index: 1, payload_size: 22, payload: notice test payload 01" + "0x".to_string() + &decoded_notice[0].to_string(), + test_notice.payload, ); - std::fs::remove_file("test_notice_1.txt")?; + std::fs::remove_file("none.output-0.bin")?; + Ok(()) } @@ -259,12 +317,12 @@ async fn test_write_report( context.server_handle.stop(true).await; //Read text file with results let report1 = - std::fs::read_to_string("test_report_1.txt").expect("error reading test report file"); + std::fs::read_to_string("none.report-0.bin").expect("error reading test report file"); assert_eq!( report1, - "index: 1, payload_size: 22, payload: report test payload 01" + "report test payload 01" ); - std::fs::remove_file("test_report_1.txt")?; + std::fs::remove_file("none.report-0.bin")?; Ok(()) } @@ -286,12 +344,12 @@ async fn test_exception_throw( println!("Server closed"); //Read text file with results let exception = - std::fs::read_to_string("test_exception_1.txt").expect("error reading test exception file"); + std::fs::read("none.exception-0.bin").expect("error reading test exception file"); assert_eq!( exception, - "index: 1, payload_size: 25, payload: exception test payload 01" + vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ); println!("Removing exception text file"); - std::fs::remove_file("test_exception_1.txt")?; + std::fs::remove_file("none.exception-0.bin")?; Ok(()) } diff --git a/rollup-http/rollup-http-server/tests/rollup_test_bindings.c b/rollup-http/rollup-http-server/tests/rollup_test_bindings.c deleted file mode 100644 index 07e93eaa..00000000 --- a/rollup-http/rollup-http-server/tests/rollup_test_bindings.c +++ /dev/null @@ -1,197 +0,0 @@ -/* Copyright Cartesi and individual authors (see AUTHORS) - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -#include "rollup_test_bindings.h" - -// Every uneven request is advance request, -// every even request is inspect request -static int request_test_counter = 0; -static int voucher_index_counter = 0; -static int notice_index_counter = 0; -static int report_index_counter = 0; -static int exception_index_counter = 0; - -static const char test_advance_request_str[] = "test advance request"; -static const size_t test_advance_request_str_size = sizeof(test_advance_request_str)-1; -static const char test_inspect_request_str[] = "test inspect request"; -static const size_t test_inspect_request_str_size = sizeof(test_inspect_request_str)-1; - -static const struct rollup_advance_state test_advance_request = { - .metadata = { - .msg_sender = {0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, - 0x11, 0x11, 0x11, 0x11}, - .block_number = 0, - .timestamp = 0, - .epoch_index = 0, - .input_index = 0 - }, - .payload = { - .data = test_advance_request_str, - .length = test_advance_request_str_size - } -}; - -static const struct rollup_inspect_state test_inspect_request = { - .payload = { - .data = test_inspect_request_str, - .length = test_inspect_request_str_size - } -}; - -static int resize_bytes(struct rollup_bytes *bytes, uint64_t size) { - if (bytes->length < size) { - uint8_t *new_data = (uint8_t *) realloc(bytes->data, size); - if (!new_data) { - return -1; - } - bytes->length = size; - bytes->data = new_data; - } - return 0; -} - -/* Finishes processing of current advance or inspect. - * Returns 0 on success, -1 on error */ -int rollup_finish_request(int fd, struct rollup_finish *finish, bool accept) { - int res = 0; - memset(finish, 0, sizeof(*finish)); - finish->accept_previous_request = accept; - request_test_counter += 1; - if (request_test_counter % 2 == 0) { - //test inspect request - finish->next_request_type = CARTESI_ROLLUP_INSPECT_STATE; - finish->next_request_payload_length = test_inspect_request.payload.length; - } else { - // test advance request - finish->next_request_type = CARTESI_ROLLUP_ADVANCE_STATE; - finish->next_request_payload_length = test_advance_request.payload.length; - } - - return res; -} - -/* Returns test advance state rollup request - * Returns 0 on success, -1 on error */ -int rollup_read_advance_state_request(int fd, struct rollup_finish *finish, - struct rollup_bytes *bytes, struct rollup_input_metadata *metadata) { - struct rollup_advance_state req; - int res = 0; - if (resize_bytes(bytes, finish->next_request_payload_length) != 0) { - fprintf(stderr, "Failed growing payload buffer\n"); - return -1; - } - memset(&req, 0, sizeof(req)); - // test advance request - *metadata = test_advance_request.metadata; - *bytes = test_advance_request.payload; - return res; -} - -/* Returns test inspect state rollup request - * Returns 0 on success, -1 on error */ -int rollup_read_inspect_state_request(int fd, struct rollup_finish *finish, struct rollup_bytes *query) { - struct rollup_inspect_state req; - int res = 0; - if (resize_bytes(query, finish->next_request_payload_length) != 0) { - fprintf(stderr, "Failed growing payload buffer\n"); - return -1; - } - memset(&req, 0, sizeof(req)); - *query = test_inspect_request.payload; - return 0; -} - -/* Outputs a new voucher to a file test_voucher_xx.txt in a text file - * voucher_index is filled with new index from the driver - * Returns 0 on success, -1 on error */ -int rollup_write_voucher(int fd, uint8_t destination[CARTESI_ROLLUP_ADDRESS_SIZE], struct rollup_bytes *bytes, - uint64_t *voucher_index) { - char filename[32] = {0}; - char destination_c[CARTESI_ROLLUP_ADDRESS_SIZE + 1] = {0}; - voucher_index_counter = voucher_index_counter + 1; - sprintf(filename, "test_voucher_%d.txt", voucher_index_counter); - FILE *f = fopen(filename, "w"); - if (f == NULL) { - return -1; - } - memcpy(destination_c, destination, CARTESI_ROLLUP_ADDRESS_SIZE); - fprintf(f, "index: %d, payload_size: %d, payload: ", voucher_index_counter, bytes->length); - for (int i = 0; i < bytes->length; i++) { - fputc(bytes->data[i], f); - } - fclose(f); - *voucher_index = voucher_index_counter; - return 0; -} - -/* Outputs a new notice to a file test_notice_xx.txt - * notice_index is filled with new index from the driver - * Returns 0 on success, -1 on error */ -int rollup_write_notice(int fd, struct rollup_bytes *bytes, uint64_t *notice_index) { - char filename[32] = {0}; - notice_index_counter = notice_index_counter + 1; - sprintf(filename, "test_notice_%d.txt", notice_index_counter); - FILE *f = fopen(filename, "w"); - if (f == NULL) { - return -1; - } - fprintf(f, "index: %d, payload_size: %d, payload: ", notice_index_counter, bytes->length); - for (int i = 0; i < bytes->length; i++) { - fputc(bytes->data[i], f); - } - fclose(f); - *notice_index = notice_index_counter; - return 0; -} - - -/* Outputs a new report to a file test_report_xx.txt - * Returns 0 on success, -1 on error */ -int rollup_write_report(int fd, struct rollup_bytes *bytes) { - char filename[32] = {0}; - report_index_counter = report_index_counter + 1; - sprintf(filename, "test_report_%d.txt", report_index_counter); - FILE *f = fopen(filename, "w"); - if (f == NULL) { - return -1; - } - fprintf(f, "index: %d, payload_size: %d, payload: ", report_index_counter, bytes->length); - for (int i = 0; i < bytes->length; i++) { - fputc(bytes->data[i], f); - } - fclose(f); - return 0; -} - -/* Outputs a dapp exception to a file test_exception_xx.txt - * Returns 0 on success, -1 on error */ -int rollup_throw_exception(int fd, struct rollup_bytes *bytes) { - char filename[32] = {0}; - exception_index_counter = exception_index_counter + 1; - sprintf(filename, "test_exception_%d.txt", exception_index_counter); - FILE *f = fopen(filename, "w"); - if (f == NULL) { - return -1; - } - fprintf(f, "index: %d, payload_size: %d, payload: ", exception_index_counter, bytes->length); - for (int i = 0; i < bytes->length; i++) { - fputc(bytes->data[i], f); - } - fclose(f); - return 0; -} - diff --git a/rollup-http/rollup-http-server/tests/rollup_test_bindings.h b/rollup-http/rollup-http-server/tests/rollup_test_bindings.h deleted file mode 100644 index 50a3e86a..00000000 --- a/rollup-http/rollup-http-server/tests/rollup_test_bindings.h +++ /dev/null @@ -1,145 +0,0 @@ -/* Copyright Cartesi and individual authors (see AUTHORS) - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -#ifndef _UAPI_LINUX_CARTESI_ROLLUP_H -#define _UAPI_LINUX_CARTESI_ROLLUP_H - -#include -#include -#include -#include -#include -#include -#include - - -#define CARTESI_ROLLUP_ADVANCE_STATE 0 -#define CARTESI_ROLLUP_INSPECT_STATE 1 - -#define CARTESI_ROLLUP_ADDRESS_SIZE 20 - -struct rollup_bytes { - unsigned char *data; - uint64_t length; -}; - -struct rollup_input_metadata { - uint8_t msg_sender[CARTESI_ROLLUP_ADDRESS_SIZE]; - uint64_t block_number; - uint64_t timestamp; - uint64_t epoch_index; - uint64_t input_index; -}; - -struct rollup_advance_state { - struct rollup_input_metadata metadata; - struct rollup_bytes payload; -}; - -struct rollup_inspect_state { - struct rollup_bytes payload; -}; - -struct rollup_finish { - /* True if previous request should be accepted */ - /* False if previous request should be rejected */ - bool accept_previous_request; - - int next_request_type; /* either CARTESI_ROLLUP_ADVANCE or CARTESI_ROLLUP_INSPECT */ - int next_request_payload_length; -}; - -struct rollup_voucher { - uint8_t destination[CARTESI_ROLLUP_ADDRESS_SIZE]; - struct rollup_bytes payload; - uint64_t index; -}; - -struct rollup_notice { - struct rollup_bytes payload; - uint64_t index; -}; - -struct rollup_report { - struct rollup_bytes payload; -}; - -struct rollup_exception { - struct rollup_bytes payload; -}; - -/* Finishes processing of current advance or inspect. - * Returns only when next advance input or inspect query is ready. - * How: - * Yields manual with rx-accepted if accept is true and yields manual with rx-rejected if accept is false. - * Once yield returns, checks the data field in fromhost to decide if next request is advance or inspect. - * Returns type and payload length of next request in struct - * Returns 0 */ -#define IOCTL_ROLLUP_FINISH _IOWR(0xd3, 0, struct rollup_finish) - -/* Obtains arguments to advance state - * How: - * Reads from input metadat memory range and convert data. - * Reads from rx buffer and copy to payload - * Returns 0 */ -#define IOCTL_ROLLUP_READ_ADVANCE_STATE _IOWR(0xd3, 0, struct rollup_advance_state) - -/* Obtains arguments to inspect state - * How: - * Reads from rx buffer and copy to payload - * Returns 0 */ -#define IOCTL_ROLLUP_READ_INSPECT_STATE _IOWR(0xd3, 0, struct rollup_inspect_state) - -/* Outputs a new voucher. - * How: Computes the Keccak-256 hash of address+payload and then, atomically: - * - Copies the (address+be32(0x40)+be32(payload_length)+payload) to the tx buffer - * - Copies the hash to the next available slot in the voucher-hashes memory range - * - Yields automatic with tx-voucher - * - Fills in the index field with the corresponding slot from voucher-hashes - * Returns 0 */ -#define IOCTL_ROLLUP_WRITE_VOUCHER _IOWR(0xd3, 1, struct rollup_voucher) - -/* Outputs a new notice. - * How: Computes the Keccak-256 hash of payload and then, atomically: - * - Copies the (be32(0x20)+be32(payload_length)+payload) to the tx buffer - * - Copies the hash to the next available slot in the notice-hashes memory range - * - Yields automatic with tx-notice - * - Fills in the index field with the corresponding slot from notice-hashes - * Returns 0 */ -#define IOCTL_ROLLUP_WRITE_NOTICE _IOWR(0xd3, 2, struct rollup_notice) - -/* Outputs a new report. - * - Copies the (be32(0x20)+be32(payload_length)+payload) to the tx buffer - * - Yields automatic with tx-report - * Returns 0 */ -#define IOCTL_ROLLUP_WRITE_REPORT _IOWR(0xd3, 3, struct rollup_report) - -/* Throws an exeption. - * - Copies the (be32(0x20)+be32(payload_length)+payload) to the tx buffer - * - Yields manual with tx-exception - * Returns 0 */ -#define IOCTL_ROLLUP_THROW_EXCEPTION _IOWR(0xd3, 4, struct rollup_exception) -#endif - - -int rollup_finish_request(int fd, struct rollup_finish *finish, bool accept); -int rollup_read_advance_state_request(int fd, struct rollup_finish *finish, struct rollup_bytes *bytes, struct rollup_input_metadata *metadata); -int rollup_read_inspect_state_request(int fd, struct rollup_finish *finish, struct rollup_bytes *query); -int rollup_write_voucher(int fd, uint8_t address[CARTESI_ROLLUP_ADDRESS_SIZE], struct rollup_bytes *bytes, uint64_t* voucher_index); -int rollup_write_notice(int fd, struct rollup_bytes *bytes, uint64_t* notice_index); -int rollup_write_report(int fd, struct rollup_bytes *bytes); -int rollup_throw_exception(int fd, struct rollup_bytes *bytes); diff --git a/sys-utils/libcmt/doc/examples/io.c b/sys-utils/libcmt/doc/examples/io.c index 154dc1a6..7d30316f 100644 --- a/sys-utils/libcmt/doc/examples/io.c +++ b/sys-utils/libcmt/doc/examples/io.c @@ -20,8 +20,8 @@ int exception(union cmt_io_driver *io) { /* exception -------------------------------------------------------- */ struct cmt_io_yield req[1] = {{ - .dev = HTIF_DEVICE_YIELD, - .cmd = HTIF_YIELD_MANUAL, + .dev = HTIF_YIELD_DEV, + .cmd = HTIF_YIELD_CMD_MANUAL, .reason = HTIF_YIELD_MANUAL_REASON_TX_EXCEPTION, .data = n, }}; diff --git a/sys-utils/libcmt/src/io-mock.c b/sys-utils/libcmt/src/io-mock.c index 9ca6371d..fdf6b753 100644 --- a/sys-utils/libcmt/src/io-mock.c +++ b/sys-utils/libcmt/src/io-mock.c @@ -21,6 +21,9 @@ #include #include +#define CMT_TX_BUF_MAX_LENGTH (2UL * 1024 * 1024) // 2MB +#define CMT_RX_BUF_MAX_LENGTH (2UL * 1024 * 1024) // 2MB + static int read_whole_file(const char *name, size_t max, void *data, size_t *length); static int write_whole_file(const char *name, size_t length, const void *data); @@ -30,10 +33,8 @@ int cmt_io_init(cmt_io_driver_t *_me) { } cmt_io_driver_mock_t *me = &_me->mock; - size_t tx_length = 2UL * 1024 * 1024; // 2MB - size_t rx_length = 2UL * 1024 * 1024; // 2MB - cmt_buf_init(me->tx, tx_length, malloc(tx_length)); - cmt_buf_init(me->rx, rx_length, malloc(rx_length)); + cmt_buf_init(me->tx, CMT_TX_BUF_MAX_LENGTH, malloc(CMT_TX_BUF_MAX_LENGTH)); + cmt_buf_init(me->rx, CMT_RX_BUF_MAX_LENGTH, malloc(CMT_RX_BUF_MAX_LENGTH)); if (!me->tx->begin || !me->rx->begin) { free(me->tx->begin); @@ -75,7 +76,7 @@ cmt_buf_t cmt_io_get_tx(cmt_io_driver_t *me) { if (!me) { return empty; } - return *me->ioctl.tx; + return *me->mock.tx; } cmt_buf_t cmt_io_get_rx(cmt_io_driver_t *me) { @@ -83,7 +84,7 @@ cmt_buf_t cmt_io_get_rx(cmt_io_driver_t *me) { if (!me) { return empty; } - return *me->ioctl.rx; + return *me->mock.rx; } static int load_next_input(cmt_io_driver_mock_t *me, struct cmt_io_yield *rr) { @@ -98,7 +99,7 @@ static int load_next_input(cmt_io_driver_mock_t *me, struct cmt_io_yield *rr) { } size_t file_length = 0; - int rc = read_whole_file(filepath, cmt_buf_length(me->rx), me->rx->begin, &file_length); + int rc = read_whole_file(filepath, CMT_RX_BUF_MAX_LENGTH, me->rx->begin, &file_length); if (rc) { (void) fprintf(stderr, "failed to load \"%s\". %s\n", filepath, strerror(-rc)); return rc; @@ -116,6 +117,7 @@ static int load_next_input(cmt_io_driver_mock_t *me, struct cmt_io_yield *rr) { me->output_seq = 0; me->report_seq = 0; me->exception_seq = 0; + me->rx->end = me->rx->begin + file_length; if (getenv("CMT_DEBUG")) { (void) fprintf(stderr, "processing filename: \"%s\" (%lu), type: %d\n", filepath, file_length, me->input_type); @@ -124,7 +126,7 @@ static int load_next_input(cmt_io_driver_mock_t *me, struct cmt_io_yield *rr) { } static int store_output(cmt_io_driver_mock_t *me, const char *filepath, struct cmt_io_yield *rr) { - if (rr->data > cmt_buf_length(me->tx)) { + if (rr->data > CMT_TX_BUF_MAX_LENGTH) { return -ENOBUFS; }