diff --git a/tinygo-example/.gitignore b/tinygo-example/.gitignore new file mode 100644 index 0000000..7bc4a1e --- /dev/null +++ b/tinygo-example/.gitignore @@ -0,0 +1,3 @@ +.DS_Store +methods/guest/Cargo.lock +target/ diff --git a/tinygo-example/.gitmodules b/tinygo-example/.gitmodules new file mode 100644 index 0000000..eb7a26b --- /dev/null +++ b/tinygo-example/.gitmodules @@ -0,0 +1,4 @@ +[submodule "tinygo"] + path = tinygo + url = https://github.com/risc0/tinygo.git + branch = go21 diff --git a/tinygo-example/.vscode/settings.json b/tinygo-example/.vscode/settings.json new file mode 100644 index 0000000..48d60f9 --- /dev/null +++ b/tinygo-example/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "rust-analyzer.linkedProjects": [ + "./host/Cargo.toml", + "./platform/Cargo.toml" + ] +} \ No newline at end of file diff --git a/tinygo-example/Cargo.toml b/tinygo-example/Cargo.toml new file mode 100644 index 0000000..d01cebe --- /dev/null +++ b/tinygo-example/Cargo.toml @@ -0,0 +1,11 @@ +[workspace] +resolver = "2" +members = ["host", "platform"] + +# Always optimize; building and running the guest takes much longer without optimization. +[profile.dev] +opt-level = 3 + +[profile.release] +debug = 1 +lto = true diff --git a/tinygo-example/LICENSE b/tinygo-example/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/tinygo-example/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/tinygo-example/Makefile b/tinygo-example/Makefile new file mode 100644 index 0000000..007e682 --- /dev/null +++ b/tinygo-example/Makefile @@ -0,0 +1,31 @@ +ROOT_DIR:=$(strip $(dir $(realpath $(lastword $(MAKEFILE_LIST))))) + +default: execute + +.PHONY: platform +platform: + cargo +risc0 rustc -p zkvm-platform --target riscv32im-risc0-zkvm-elf --lib --crate-type staticlib --release --target-dir ./guest/out/platform + +.PHONY: tinygo-llvm +tinygo-llvm: + cd tinygo; make llvm-source && make llvm-build + +.PHONY: tinygo-rebuild +tinygo-rebuild: + cd tinygo; make -j10 + +.PHONY: tinygo +tinygo: tinygo-llvm tinygo-rebuild + +.PHONY: guest +guest: platform + # Note: this will link against the risc0 platform static lib + ./tinygo/build/tinygo build -target=zkvm -o ./guest/out/main ./guest/main.go + +.PHONY: execute +execute: guest + RISC0_DEV_MODE=true cargo run + +.PHONY: prove +prove: guest + cargo run diff --git a/tinygo-example/README.md b/tinygo-example/README.md new file mode 100644 index 0000000..cf92e3e --- /dev/null +++ b/tinygo-example/README.md @@ -0,0 +1,61 @@ +# Tinygo template example + +This is a minimal example of a program compiled with tinygo running in the zkvm. + +## Quick Start + +First, make sure [rustup] is installed. The +[`rust-toolchain.toml`][rust-toolchain] file will be used by `cargo` to +automatically install the correct version. + +To build all methods and execute the method within the zkVM, run the following +command: + +```console +git submodule update --init +make tinygo +make execute + +# And to run outside of dev mode +make prove +``` + +### Executing the project locally in development mode + +During development, faster iteration upon code changes can be achieved by leveraging [dev-mode], we strongly suggest activating it during your early development phase. Furthermore, you might want to get insights into the execution statistics of your project, and this can be achieved by specifying the environment variable `RUST_LOG="[executor]=info"` before running your project. + +Put together, the command to run your project in development mode while getting execution statistics is: + +```bash +RUST_LOG="[executor]=info" RISC0_DEV_MODE=1 cargo run +``` + +### Running proofs remotely on Bonsai + +_Note: The Bonsai proving service is still in early Alpha; an API key is +required for access. [Click here to request access][bonsai access]._ + +If you have access to the URL and API key to Bonsai you can run your proofs +remotely. To prove in Bonsai mode, invoke `cargo run` with two additional +environment variables: + +```bash +BONSAI_API_KEY="YOUR_API_KEY" BONSAI_API_URL="BONSAI_URL" cargo run +``` + +[bonsai access]: https://bonsai.xyz/apply +[cargo-risczero]: https://docs.rs/cargo-risczero +[crates]: https://github.com/risc0/risc0/blob/main/README.md#rust-binaries +[dev-docs]: https://dev.risczero.com +[dev-mode]: https://dev.risczero.com/api/zkvm/dev-mode +[discord]: https://discord.gg/risczero +[docs.rs]: https://docs.rs/releases/search?query=risc0 +[examples]: https://github.com/risc0/risc0/tree/main/examples +[risc0-build]: https://docs.rs/risc0-build +[risc0-repo]: https://www.github.com/risc0/risc0 +[risc0-zkvm]: https://docs.rs/risc0-zkvm +[rustup]: https://rustup.rs +[rust-toolchain]: rust-toolchain.toml +[twitter]: https://twitter.com/risczero +[zkvm-overview]: https://dev.risczero.com/zkvm +[zkhack-iii]: https://www.youtube.com/watch?v=Yg_BGqj_6lg&list=PLcPzhUaCxlCgig7ofeARMPwQ8vbuD6hC5&index=5 diff --git a/tinygo-example/guest/.gitignore b/tinygo-example/guest/.gitignore new file mode 100644 index 0000000..981aeb8 --- /dev/null +++ b/tinygo-example/guest/.gitignore @@ -0,0 +1 @@ +/out \ No newline at end of file diff --git a/tinygo-example/guest/go.mod b/tinygo-example/guest/go.mod new file mode 100644 index 0000000..6f66969 --- /dev/null +++ b/tinygo-example/guest/go.mod @@ -0,0 +1,3 @@ +module github.com/risc0/cosmos-sdk-proving + +go 1.19 diff --git a/tinygo-example/guest/main.go b/tinygo-example/guest/main.go new file mode 100644 index 0000000..91ae945 --- /dev/null +++ b/tinygo-example/guest/main.go @@ -0,0 +1,29 @@ +package main + +/* +#include +#cgo LDFLAGS: -L./out/platform/riscv32im-risc0-zkvm-elf/release -lzkvm_platform +#define DIGEST_WORDS 8 +typedef struct Sha256_Impl Sha256_Impl; +typedef struct sha256_state { + Sha256_Impl *inner; +} sha256_state; +typedef uint32_t Digest[DIGEST_WORDS]; +struct sha256_state *init_sha256(void); +void sha256_update(struct sha256_state *hasher, const uint8_t *data, uint32_t len); +Digest *sha256_finalize(struct sha256_state *hasher); +void sha256_free(struct sha256_state *hasher); +void env_commit(struct sha256_state *hasher, const uint8_t *bytes_ptr, uint32_t len); +void env_exit(struct sha256_state *hasher, uint8_t exit_code); +*/ +import "C" + +func main() { + hasher := C.init_sha256() + + // TODO replace this output with program specific output + outputBytes := [4]byte{0, 1, 2, 3} + + C.env_commit(hasher, &outputBytes[0], uint32(len(outputBytes))) + C.env_exit(hasher, 0) +} diff --git a/tinygo-example/host/Cargo.toml b/tinygo-example/host/Cargo.toml new file mode 100644 index 0000000..83a02dc --- /dev/null +++ b/tinygo-example/host/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "host" +version = "0.1.0" +edition = "2021" + +[dependencies] +risc0-zkvm = { version = "=1.0.0-rc.7" } +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +serde = "1.0" +anyhow = "1.0" diff --git a/tinygo-example/host/src/main.rs b/tinygo-example/host/src/main.rs new file mode 100644 index 0000000..f8dba6a --- /dev/null +++ b/tinygo-example/host/src/main.rs @@ -0,0 +1,26 @@ +use risc0_zkvm::{compute_image_id, default_prover, ExecutorEnv}; +use std::fs; + +fn main() -> anyhow::Result<()> { + // Load built tinygo program and compute it's image ID. + let consensus_elf = fs::read("./guest/out/main")?; + let consensus_id = compute_image_id(&consensus_elf)?; + // Initialize tracing. In order to view logs, run `RUST_LOG=info cargo run` + tracing_subscriber::fmt() + .with_env_filter(tracing_subscriber::filter::EnvFilter::from_default_env()) + .init(); + + let env = ExecutorEnv::builder().build()?; + let prover = default_prover(); + + // Produce a receipt by proving the specified ELF binary. + let receipt = prover.prove(env, &consensus_elf)?.receipt; + + assert_eq!(&receipt.journal.bytes, &[0, 1, 2, 3]); + + // The receipt was verified at the end of proving, but the below code is an + // example of how someone else could verify this receipt. + receipt.verify(consensus_id)?; + + Ok(()) +} diff --git a/tinygo-example/platform/Cargo.toml b/tinygo-example/platform/Cargo.toml new file mode 100644 index 0000000..2c3fc7a --- /dev/null +++ b/tinygo-example/platform/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "zkvm-platform" +version = "0.1.0" +edition = "2021" + +[dependencies] +risc0-zkvm-platform = { version = "=1.0.0-rc.7", features = ["rust-runtime", "export-syscalls"] } +risc0-binfmt = { version = "=1.0.0-rc.7", default-features = false } +risc0-zkp = { version = "=1.0.0-rc.7", default-features = false } diff --git a/tinygo-example/platform/src/lib.rs b/tinygo-example/platform/src/lib.rs new file mode 100644 index 0000000..554844a --- /dev/null +++ b/tinygo-example/platform/src/lib.rs @@ -0,0 +1,114 @@ +use core::{ptr, slice}; +use risc0_binfmt::tagged_struct; +use risc0_zkp::core::digest::Digest; +use risc0_zkp::core::hash::sha::guest::Impl; +use risc0_zkp::core::hash::sha::rust_crypto::{Digest as _, Sha256}; +use risc0_zkvm_platform::fileno; +use risc0_zkvm_platform::syscall::{sys_halt, sys_panic, sys_read, sys_write}; + +const ERR_FREED: &[u8] = b"error: sha256_state has not been initialized or has already been freed"; + +/// C wrapper for guest sha256 implementation. +/// +/// This is used in the guest to generate any sha256 +/// hash, but also to accumulate the Sha256 state of all data written to journal through +/// [commit]. +/// +/// Initialize with [init_sha256], and can retrieve the final hash through [sha256_finalize], +/// or pass it into [zkvm_exit] to exit the program. +#[repr(C)] +#[allow(non_camel_case_types)] +pub struct sha256_state { + inner: *mut Sha256, +} + +#[no_mangle] +pub extern "C" fn init_sha256() -> *mut sha256_state { + Box::into_raw(Box::new(sha256_state { + inner: Box::into_raw(Box::new(Sha256::new())), + })) +} + +/// Update the sha256 state with the bytes passed in. +/// +/// # Safety +/// This is safe assuming that pointers have not been manually modified, and len does not go past +/// the buffer of the data in memory. +#[no_mangle] +pub unsafe extern "C" fn sha256_update(hasher: *mut sha256_state, data: *const u8, len: u32) { + if hasher.is_null() || data.is_null() || (*hasher).inner.is_null() { + sys_panic(ERR_FREED.as_ptr(), ERR_FREED.len()) + } + let data_slice = slice::from_raw_parts(data, len as usize); + (*(*hasher).inner).update(data_slice); +} + +/// Finalize the hasher, returning an allocated digest of the output hash. +/// +/// Note: This digest is leaked, as the zkvm currently uses a bump allocator so it does not need to +/// be freed. If switching allocator, should implement a free method for [Digest]. +/// +/// # Safety +/// Assumes [sha256_state] has not been freed previously. +#[no_mangle] +pub unsafe extern "C" fn sha256_finalize(hasher: *mut sha256_state) -> *mut Digest { + if hasher.is_null() || (*hasher).inner.is_null() { + sys_panic(ERR_FREED.as_ptr(), ERR_FREED.len()) + } + let inner = unsafe { Box::from_raw((*hasher).inner) }; + let result = inner.finalize(); + // Free hasher to assert it is unused after finalize. + sha256_free(hasher); + let arr: [u8; 32] = result.into(); + Box::into_raw(Box::new(arr.into())) +} + +/// Free allocations from [sha256_state]. +/// +/// # Safety +/// This assumes the state has not already been freed or manually modified. +#[no_mangle] +pub unsafe extern "C" fn sha256_free(hasher: *mut sha256_state) { + if !hasher.is_null() { + let mut boxed_hasher = Box::from_raw(hasher); + + let inner = Box::from_raw(boxed_hasher.inner); + // Set pointer to null to avoid double free. `black_box` to avoid compiler optimizing away. + boxed_hasher.inner = ptr::null_mut(); + drop(inner); + + drop(boxed_hasher); + } +} + +/// Exit the zkvm, using the [sha256_state]. +/// +/// # Safety +/// Assumes hasher has not been freed. +#[no_mangle] +pub unsafe extern "C" fn env_exit(hasher: *mut sha256_state, exit_code: u8) -> ! { + let journal_digest = sha256_finalize(hasher); + let output_words: [u32; 8] = + tagged_struct::("risc0.Output", &[&*journal_digest, &Digest::ZERO], &[]).into(); + sys_halt(exit_code, &output_words) +} + +/// Write data to the journal, updating the sha256 state accumulation with that data. +/// +/// # Safety +/// This is safe assuming that pointers have not been manually modified, and len does not go past +/// the buffer of the data in memory. +#[no_mangle] +pub unsafe extern "C" fn env_commit(hasher: *mut sha256_state, bytes_ptr: *const u8, len: u32) { + sha256_update(hasher, bytes_ptr, len); + sys_write(fileno::JOURNAL, bytes_ptr, len as usize); +} + +/// Reads `len` bytes into buffer from the host. +/// +/// # Safety +/// Assumes that the buffer has at least `len` bytes allocated. +#[no_mangle] +pub unsafe extern "C" fn env_read(bytes_ptr: *mut u8, len: u32) { + sys_read(fileno::STDIN, bytes_ptr, len as usize); +}