From 33c0ba3fe66a6b5fb54747cc2a640e62b932fd45 Mon Sep 17 00:00:00 2001 From: Jun Kimura Date: Thu, 6 Jul 2023 11:13:58 +0900 Subject: [PATCH] tools: remove cgen from repo Signed-off-by: Jun Kimura --- .github/workflows/test.yml | 1 - Cargo.lock | 27 --- Cargo.toml | 1 - Makefile | 4 - tools/cgen/.gitignore | 1 - tools/cgen/Cargo.toml | 36 ---- tools/cgen/README.md | 4 - tools/cgen/build.rs | 27 --- tools/cgen/src/cli.rs | 68 ------ tools/cgen/src/gen.rs | 424 ------------------------------------- tools/cgen/src/main.rs | 12 -- tools/cgen/src/types.rs | 202 ------------------ 12 files changed, 807 deletions(-) delete mode 100644 tools/cgen/.gitignore delete mode 100644 tools/cgen/Cargo.toml delete mode 100644 tools/cgen/README.md delete mode 100644 tools/cgen/build.rs delete mode 100644 tools/cgen/src/cli.rs delete mode 100644 tools/cgen/src/gen.rs delete mode 100644 tools/cgen/src/main.rs delete mode 100644 tools/cgen/src/types.rs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 241bd419..1f2814a1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -55,4 +55,3 @@ jobs: - run: source /opt/sgxsdk/environment && make -B - run: source /opt/sgxsdk/environment && make test - run: source /opt/sgxsdk/environment && make integration-test - - run: source /opt/sgxsdk/environment && make cgen diff --git a/Cargo.lock b/Cargo.lock index 38be82f2..69f7d385 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -618,33 +618,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" -[[package]] -name = "cgen" -version = "0.1.0" -dependencies = [ - "anyhow", - "attestation-report", - "base64 0.20.0-alpha.1", - "clap", - "commitments", - "ecall-commands", - "enclave-api", - "host", - "host-environment", - "ibc", - "ibc-proto 0.26.0", - "ibc-test-framework", - "lcp-types", - "log 0.4.17", - "relay-tendermint", - "rlp", - "serde", - "serde_json", - "store", - "tempfile", - "tokio", -] - [[package]] name = "chrono" version = "0.4.22" diff --git a/Cargo.toml b/Cargo.toml index 91eb9b26..3de6568e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,6 @@ members = [ "proto", "tests/integration", "tools/nodes-runner", - "tools/cgen" ] exclude = [ "enclave", diff --git a/Makefile b/Makefile index 611d77a7..8af55380 100644 --- a/Makefile +++ b/Makefile @@ -215,10 +215,6 @@ udeps: yrly: go build -o ./bin/yrly -tags customcert ./go/relay/bin -.PHONY: cgen -cgen: - @cargo build $(CARGO_TARGET) --package cgen - .PHONY: nodes-runner nodes-runner: @cargo build $(CARGO_TARGET) --package nodes-runner diff --git a/tools/cgen/.gitignore b/tools/cgen/.gitignore deleted file mode 100644 index 8fce6030..00000000 --- a/tools/cgen/.gitignore +++ /dev/null @@ -1 +0,0 @@ -data/ diff --git a/tools/cgen/Cargo.toml b/tools/cgen/Cargo.toml deleted file mode 100644 index 92aab9f3..00000000 --- a/tools/cgen/Cargo.toml +++ /dev/null @@ -1,36 +0,0 @@ -[package] -name = "cgen" -version = "0.1.0" -edition = "2021" -build = "build.rs" - -[dependencies] -ibc = { version = "0.29.0", default-features = false, features = ["serde", "std"] } -ibc-proto = { version = "0.26.0", default-features = false, features = ["parity-scale-codec", "borsh"] } -ibc-test-framework = { version = "0.22.0", default-features = false } -clap = { version = "3.2", features = ["derive"] } -tempfile = "3" -anyhow = { version = "1.0.56" } -tokio = { version = "1.0" } -log = "0.4.8" -serde = { version = "1.0", default-features = false, features = ["alloc"] } -serde_json = { version = "1.0", default-features = false, features = ["alloc"] } -base64 = { git = "https://github.com/marshallpierce/rust-base64", default-features = false, features = ["alloc"] } -rlp = { version = "0.5.1", default-features = false } - -lcp-types = { path = "../../modules/types" } -host = { path = "../../modules/host" } -host-environment = { path = "../../modules/host-environment" } -store = { path = "../../modules/store" } -commitments = { path = "../../modules/commitments" } -enclave-api = { path = "../../modules/enclave-api" } -ecall-commands = { path = "../../modules/ecall-commands" } -attestation-report = { path = "../../modules/attestation-report" } -relay-tendermint = { path = "../../modules/relay/tendermint" } - -[features] -default = [] -sgx-sw = [ - "enclave-api/sgx-sw", - "ecall-commands/sgx-sw" -] diff --git a/tools/cgen/README.md b/tools/cgen/README.md deleted file mode 100644 index 7b5d45e9..00000000 --- a/tools/cgen/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# cgen - -cgen is an LCP commitment generator. - diff --git a/tools/cgen/build.rs b/tools/cgen/build.rs deleted file mode 100644 index 3f4a65bd..00000000 --- a/tools/cgen/build.rs +++ /dev/null @@ -1,27 +0,0 @@ -use std::env; - -fn main() { - let sdk_dir = env::var("SGX_SDK").unwrap_or_else(|_| "/opt/sgxsdk".to_string()); - let sgx_mode = env::var("SGX_MODE").unwrap_or_else(|_| "HW".to_string()); - - println!("cargo:rustc-link-search=native=./lib"); - println!("cargo:rustc-link-lib=static=Enclave_u"); - println!("cargo:rustc-link-search=native={}/lib64", sdk_dir); - println!("cargo:rustc-link-lib=static=sgx_uprotected_fs"); - println!("cargo:rustc-link-lib=static=sgx_ukey_exchange"); - - match sgx_mode.as_ref() { - "SW" => { - println!("cargo:rustc-link-lib=dylib=sgx_urts_sim"); - println!("cargo:rustc-link-lib=dylib=sgx_uae_service_sim"); - } - "HW" => { - println!("cargo:rustc-link-lib=dylib=sgx_urts"); - println!("cargo:rustc-link-lib=dylib=sgx_uae_service"); - } - _ => { - println!("cargo:rustc-link-lib=dylib=sgx_urts"); - println!("cargo:rustc-link-lib=dylib=sgx_uae_service"); - } - } -} diff --git a/tools/cgen/src/cli.rs b/tools/cgen/src/cli.rs deleted file mode 100644 index ec38b287..00000000 --- a/tools/cgen/src/cli.rs +++ /dev/null @@ -1,68 +0,0 @@ -use crate::gen::{CGenConfig, CGenSuite, Command}; -use anyhow::Result; -use clap::Parser; -use enclave_api::Enclave; -use host_environment::Environment; -use ibc_test_framework::prelude::run_binary_channel_test; -use std::{ - path::PathBuf, - str::FromStr, - sync::{Arc, RwLock}, -}; -use store::{host::HostStore, memory::MemStore}; -use tempfile::TempDir; - -/// Entry point for LCP CLI. -#[derive(Debug, Parser)] -#[clap( - name = env!("CARGO_PKG_NAME"), - version = env!("CARGO_PKG_VERSION"), - author = env!("CARGO_PKG_AUTHORS"), - about = env!("CARGO_PKG_DESCRIPTION"), - arg_required_else_help = true, -)] -pub struct Cli { - /// Path to the enclave binary - #[clap(long = "enclave", help = "Path to enclave binary")] - pub enclave: PathBuf, - /// Output path to LCP commitments - #[clap(long = "out", help = "Output path to LCP commitments")] - pub out_dir: PathBuf, - /// Commands to process - #[clap(long = "commands", help = "Commands to process", multiple = true)] - pub commands: Vec, -} - -impl Cli { - pub fn run(self) -> Result<()> { - let tmp_dir = TempDir::new()?; - let home = tmp_dir.path().to_str().unwrap().to_string(); - - let spid = std::env::var("SPID")?.as_bytes().to_vec(); - let ias_key = std::env::var("IAS_KEY")?.as_bytes().to_vec(); - - host::set_environment(Environment::new( - home.into(), - Arc::new(RwLock::new(HostStore::Memory(MemStore::default()))), - )) - .unwrap(); - - let env = host::get_environment().unwrap(); - let enclave = Enclave::create(self.enclave, &env.home, env.store.clone())?; - - let mut commands = vec![]; - for c in self.commands { - commands.push(Command::from_str(&c)?); - } - run_binary_channel_test(&CGenSuite::new( - CGenConfig { - spid, - ias_key, - out_dir: self.out_dir, - }, - enclave, - commands, - ))?; - Ok(()) - } -} diff --git a/tools/cgen/src/gen.rs b/tools/cgen/src/gen.rs deleted file mode 100644 index ad631322..00000000 --- a/tools/cgen/src/gen.rs +++ /dev/null @@ -1,424 +0,0 @@ -use crate::types::JSONSerializer; -use anyhow::{anyhow, bail}; -use ecall_commands::{ - CommitmentProofPair, IASRemoteAttestationInput, InitClientInput, InitEnclaveInput, - UpdateClientInput, VerifyMembershipInput, -}; -use enclave_api::{Enclave, EnclaveCommandAPI}; -use ibc::core::ics04_channel::packet::Sequence; -use ibc::core::ics23_commitment::commitment::CommitmentProofBytes; -use ibc::core::ics23_commitment::merkle::MerkleProof; -use ibc::core::ics24_host::path::{ChannelEndPath, CommitmentPath, ConnectionPath}; -use ibc::core::ics24_host::Path; -use ibc::Height; -use ibc_proto::protobuf::Protobuf; -use ibc_test_framework::prelude::*; -use ibc_test_framework::util::random::random_u64_range; -use lcp_types::{ClientId, Time}; -use relay_tendermint::types::{to_ibc_channel_id, to_ibc_connection_id, to_ibc_port_id}; -use relay_tendermint::Relayer; -use std::str::FromStr; -use std::sync::Arc; -use std::{fs::File, io::Write, path::PathBuf}; -use tokio::runtime::Runtime as TokioRuntime; - -pub struct CGenSuite { - config: CGenConfig, - enclave: Enclave, - commands: Vec, -} - -impl CGenSuite { - pub fn new( - config: CGenConfig, - enclave: Enclave, - commands: Vec, - ) -> Self { - Self { - config, - enclave, - commands, - } - } -} - -#[derive(Clone)] -pub struct CGenConfig { - pub(crate) spid: Vec, - pub(crate) ias_key: Vec, - pub(crate) out_dir: PathBuf, -} - -pub enum Command { - UpdateClient, - VerifyConnection, - VerifyChannel, - VerifyPacket, - WaitBlocks(u64), -} - -impl FromStr for Command { - type Err = anyhow::Error; - fn from_str(s: &str) -> Result { - let parts: Vec<&str> = s.split(':').collect(); - match parts[0] { - "update_client" => Ok(Command::UpdateClient), - "verify_connection" => Ok(Command::VerifyConnection), - "verify_channel" => Ok(Command::VerifyChannel), - "verify_packet" => Ok(Command::VerifyPacket), - "wait_blocks" => { - if parts.len() != 2 { - bail!("`wait` requires one argument"); - } - Ok(Command::WaitBlocks(u64::from_str(parts[1])?)) - } - _ => bail!("unknown command: '{}'", s), - } - } -} - -pub struct CommandFileGenerator<'e, ChainA: ChainHandle, ChainB: ChainHandle> { - config: CGenConfig, - enclave: &'e Enclave, - rly: Relayer, - - channel: ConnectedChannel, - command_sequence: u64, - - client_latest_height: Option, // latest height of client state - chain_latest_provable_height: Height, // latest provable height of chainA -} - -impl<'e, ChainA: ChainHandle, ChainB: ChainHandle> CommandFileGenerator<'e, ChainA, ChainB> { - pub fn new( - config: CGenConfig, - enclave: &'e Enclave, - rly: Relayer, - channel: ConnectedChannel, - ) -> Self { - let chain_latest_provable_height = rly.query_latest_height().unwrap().decrement().unwrap(); - Self { - config, - enclave, - rly, - channel, - command_sequence: 1, - client_latest_height: None, - chain_latest_provable_height, - } - } - - pub fn gen(&mut self, commands: &[Command], wait_blocks: u64) -> Result<(), anyhow::Error> { - if wait_blocks > 0 { - self.wait_blocks(wait_blocks)?; - } - self.init_enclave_key()?; - self.command_sequence += 1; - let client_id = self.create_client()?; - self.command_sequence += 1; - - for cmd in commands.iter() { - assert!(self.command_sequence < 1000); - match cmd { - Command::UpdateClient => self.update_client(client_id.clone())?, - Command::VerifyConnection => self.verify_connection(client_id.clone())?, - Command::VerifyChannel => self.verify_channel(client_id.clone())?, - // TODO get sequence from command - Command::VerifyPacket => self.verify_packet(client_id.clone(), 1u64.into())?, - Command::WaitBlocks(n) => self.wait_blocks(*n)?, - }; - self.command_sequence += 1; - } - Ok(()) - } - - fn init_enclave_key(&mut self) -> Result<(), anyhow::Error> { - let _ = match self.enclave.init_enclave_key(InitEnclaveInput::default()) { - Ok(res) => res, - Err(e) => { - bail!("Init Enclave Failed {:?}!", e); - } - }; - - let res = match self - .enclave - .ias_remote_attestation(IASRemoteAttestationInput { - spid: self.config.spid.clone(), - ias_key: self.config.ias_key.clone(), - }) { - Ok(res) => res.report, - Err(e) => { - bail!("IAS Remote Attestation Failed {:?}!", e); - } - }; - - self.write_to_file("avr", &res)?; - Ok(()) - } - - fn create_client(&mut self) -> Result { - let (client_state, consensus_state) = self - .rly - .fetch_state_as_any(self.chain_latest_provable_height)?; - log::info!( - "initial_height: {:?} client_state: {:?}, consensus_state: {:?}", - self.chain_latest_provable_height, - client_state, - consensus_state - ); - - let input = InitClientInput { - any_client_state: client_state, - any_consensus_state: consensus_state, - current_timestamp: Time::now(), - }; - - self.write_to_file("init_client_input", &input)?; - - let res = self.enclave.init_client(input).unwrap(); - assert!(!res.proof.is_proven()); - - log::info!( - "generated client id is {}", - res.client_id.as_str().to_string() - ); - - self.write_to_file("init_client_result", &res)?; - - self.client_latest_height = Some(self.chain_latest_provable_height); - - Ok(res.client_id) - } - - fn update_client(&mut self, client_id: ClientId) -> Result<(), anyhow::Error> { - assert!( - self.chain_latest_provable_height > self.client_latest_height.unwrap(), - "To update the client, you need to advance block's height with `wait_blocks`" - ); - let target_header = self.rly.create_header( - self.client_latest_height.unwrap(), - self.chain_latest_provable_height, - )?; - let input = UpdateClientInput { - client_id, - any_header: target_header, - current_timestamp: Time::now(), - include_state: true, - }; - - self.write_to_file("update_client_input", &input)?; - - let res = self.enclave.update_client(input)?; - log::info!("update_client's result is {:?}", res); - assert!(res.0.is_proven()); - - self.write_to_file("update_client_result", &res.0)?; - - assert!(self.chain_latest_provable_height == res.0.commitment().new_height.try_into()?); - self.client_latest_height = Some(self.chain_latest_provable_height); - Ok(()) - } - - fn verify_connection(&mut self, client_id: ClientId) -> Result<(), anyhow::Error> { - let res = self.rly.query_connection_proof( - to_ibc_connection_id( - self.channel - .connection - .connection - .a_connection_id() - .unwrap() - .clone(), - ), - self.client_latest_height, - )?; - - let input = VerifyMembershipInput { - client_id, - prefix: "ibc".into(), - path: Path::Connection(ConnectionPath(to_ibc_connection_id( - self.channel - .connection - .connection - .a_connection_id() - .unwrap() - .clone(), - ))) - .to_string(), - value: res.0.encode_vec().unwrap(), - proof: CommitmentProofPair( - res.2.try_into().map_err(|e| anyhow!("{:?}", e))?, - merkle_proof_to_bytes(res.1)?, - ), - }; - self.write_to_file("verify_connection_input", &input)?; - let res = self.enclave.verify_membership(input)?; - self.write_to_file("verify_connection_result", &res.0)?; - - Ok(()) - } - - fn verify_channel(&mut self, client_id: ClientId) -> Result<(), anyhow::Error> { - let res = self.rly.query_channel_proof( - to_ibc_port_id(self.channel.channel.a_side.port_id().clone()), - to_ibc_channel_id(self.channel.channel.a_side.channel_id().unwrap().clone()), - self.client_latest_height, - )?; - - let input = VerifyMembershipInput { - client_id, - prefix: "ibc".into(), - path: Path::ChannelEnd(ChannelEndPath( - to_ibc_port_id(self.channel.channel.a_side.port_id().clone()), - to_ibc_channel_id(self.channel.channel.a_side.channel_id().unwrap().clone()), - )) - .to_string(), - value: res.0.encode_vec().unwrap(), - proof: CommitmentProofPair( - res.2.try_into().map_err(|e| anyhow!("{:?}", e))?, - merkle_proof_to_bytes(res.1)?, - ), - }; - self.write_to_file("verify_channel_input", &input)?; - let res = self.enclave.verify_membership(input)?; - self.write_to_file("verify_channel_result", &res.0)?; - - Ok(()) - } - - fn verify_packet( - &mut self, - client_id: ClientId, - sequence: Sequence, - ) -> Result<(), anyhow::Error> { - let res = self.rly.query_packet_proof( - to_ibc_port_id(self.channel.channel.a_side.port_id().clone()), - to_ibc_channel_id(self.channel.channel.a_side.channel_id().unwrap().clone()), - sequence, - self.client_latest_height, - )?; - - let input = VerifyMembershipInput { - client_id, - prefix: "ibc".into(), - path: Path::Commitment(CommitmentPath { - port_id: to_ibc_port_id(self.channel.channel.a_side.port_id().clone()), - channel_id: to_ibc_channel_id( - self.channel.channel.a_side.channel_id().unwrap().clone(), - ), - sequence, - }) - .to_string(), - value: res.0.into_vec(), - proof: CommitmentProofPair( - res.2.try_into().map_err(|e| anyhow!("{:?}", e))?, - merkle_proof_to_bytes(res.1)?, - ), - }; - - self.write_to_file("verify_packet_input", &input)?; - let res = self.enclave.verify_membership(input)?; - self.write_to_file("verify_packet_result", &res.0)?; - - Ok(()) - } - - fn wait_blocks(&mut self, n: u64) -> Result<(), anyhow::Error> { - let target = self.chain_latest_provable_height.add(n); - loop { - let h = self.rly.query_latest_height()?.decrement()?; - info!( - "wait_blocks: found new height: height={} target={}", - h, target - ); - if h > target { - self.chain_latest_provable_height = target; - return Ok(()); - } - } - } - - fn write_to_file( - &self, - name: &str, - content: &S, - ) -> Result<(), anyhow::Error> { - let s = content.to_json_string()?; - - let out_path = self - .config - .out_dir - .join(format!("{:03}-{}", self.command_sequence, name)); - if out_path.exists() { - bail!(format!("dir '{:?}' already exists", out_path)); - } - - File::create(out_path)?.write_all(s.as_bytes())?; - Ok(()) - } -} - -impl TestOverrides for CGenSuite { - fn modify_relayer_config(&self, config: &mut Config) { - // disable packet relay - config.mode.packets.enabled = false; - } -} - -impl BinaryChannelTest for CGenSuite { - fn run( - &self, - _config: &TestConfig, - _relayer: RelayerDriver, - chains: ConnectedChains, - channel: ConnectedChannel, - ) -> Result<(), Error> { - // Begin: IBC transfer - - let denom_a = chains.node_a.denom(); - let wallet_a = chains.node_a.wallets().user1().cloned(); - let wallet_b = chains.node_b.wallets().user1().cloned(); - let balance_a = chains - .node_a - .chain_driver() - .query_balance(&wallet_a.address(), &denom_a)?; - - let a_to_b_amount = random_u64_range(1000, 5000); - - chains.node_a.chain_driver().ibc_transfer_token( - &channel.port_a.as_ref(), - &channel.channel_id_a.as_ref(), - &wallet_a.as_ref(), - &wallet_b.address(), - &denom_a.with_amount(a_to_b_amount).as_ref(), - )?; - - chains.node_a.chain_driver().assert_eventual_wallet_amount( - &wallet_a.address(), - &denom_a - .with_amount(balance_a.amount().checked_sub(a_to_b_amount).unwrap()) - .as_ref(), - )?; - - log::info!( - "Sending IBC transfer from chain {} to chain {} with amount of {} {}", - chains.chain_id_a(), - chains.chain_id_b(), - a_to_b_amount, - denom_a - ); - - // End: IBC transfer - - let rt = Arc::new(TokioRuntime::new()?); - let config_a = chains.handle_a().config()?; - let rly = Relayer::new(config_a, rt).unwrap(); - CommandFileGenerator::new(self.config.clone(), &self.enclave, rly, channel) - .gen(&self.commands, 1) - .map_err(|e| Error::assertion(e.to_string())) - } -} - -fn merkle_proof_to_bytes(proof: MerkleProof) -> Result, anyhow::Error> { - let proof = CommitmentProofBytes::try_from(proof)?; - Ok(proof.into()) -} diff --git a/tools/cgen/src/main.rs b/tools/cgen/src/main.rs deleted file mode 100644 index 229f0079..00000000 --- a/tools/cgen/src/main.rs +++ /dev/null @@ -1,12 +0,0 @@ -use anyhow::Result; -use clap::Parser; -use cli::Cli; - -mod cli; -mod gen; -mod types; - -fn main() -> Result<()> { - let cli = Cli::parse(); - cli.run() -} diff --git a/tools/cgen/src/types.rs b/tools/cgen/src/types.rs deleted file mode 100644 index 6ff1f47a..00000000 --- a/tools/cgen/src/types.rs +++ /dev/null @@ -1,202 +0,0 @@ -use attestation_report::EndorsedAttestationVerificationReport; -use commitments::{StateCommitmentProof, UpdateClientCommitmentProof}; -use ecall_commands::{InitClientInput, InitClientResult, UpdateClientInput, VerifyMembershipInput}; -use lcp_types::ClientId; -use serde::{Deserialize, Serialize}; - -pub trait JSONSerializer { - fn to_json_string(&self) -> Result; -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct JSONEndorsedAttestationVerificationReport { - /// Attestation report generated by the hardware - pub avr: String, - /// Singature of the report - #[serde(with = "serde_base64")] - pub signature: Vec, - /// Certificate matching the signing key of the signature - #[serde(with = "serde_base64")] - pub signing_cert: Vec, - /// mrenclave of the target enclave - #[serde(with = "serde_base64")] - pub mrenclave: Vec, - /// address of enclave key - #[serde(with = "serde_base64")] - pub enclave_key: Vec, -} - -impl JSONSerializer for EndorsedAttestationVerificationReport { - fn to_json_string(&self) -> Result { - let this = self.clone(); - let avr = this.get_avr()?; - let quote = avr.parse_quote()?; - Ok(serde_json::to_string( - &JSONEndorsedAttestationVerificationReport { - avr: this.avr, - signature: this.signature, - signing_cert: this.signing_cert, - mrenclave: quote.get_mrenclave().m.to_vec(), - enclave_key: quote.get_enclave_key_address()?.0.to_vec(), - }, - )?) - } -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct JSONAny { - type_url: String, - #[serde(with = "serde_base64")] - value: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct JSONInitClientInput { - any_client_state: JSONAny, - any_consensus_state: JSONAny, - current_timestamp: u64, // second -} - -impl JSONSerializer for InitClientInput { - fn to_json_string(&self) -> Result { - let s = serde_json::to_string(&JSONInitClientInput { - any_client_state: JSONAny { - type_url: self.any_client_state.type_url.clone(), - value: self.any_client_state.value.clone(), - }, - any_consensus_state: JSONAny { - type_url: self.any_consensus_state.type_url.clone(), - value: self.any_consensus_state.value.clone(), - }, - current_timestamp: self.current_timestamp.as_unix_timestamp_secs(), - })?; - Ok(s) - } -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct JSONInitClientResult { - pub client_id: ClientId, - pub proof: JSONUpdateClientCommitmentProof, -} - -impl JSONSerializer for InitClientResult { - fn to_json_string(&self) -> Result { - let proof = self.proof.clone(); - Ok(serde_json::to_string(&JSONInitClientResult { - client_id: self.client_id.clone(), - proof: JSONUpdateClientCommitmentProof { - commitment_bytes: proof.commitment_bytes, - signer: proof.signer, - signature: proof.signature, - }, - })?) - } -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct JSONUpdateClientInput { - pub client_id: ClientId, - pub any_header: JSONAny, - pub include_state: bool, - pub current_timestamp: u64, // second -} - -impl JSONSerializer for UpdateClientInput { - fn to_json_string(&self) -> Result { - let s = serde_json::to_string(&JSONUpdateClientInput { - client_id: self.client_id.clone(), - any_header: JSONAny { - type_url: self.any_header.type_url.clone(), - value: self.any_header.value.clone(), - }, - include_state: self.include_state, - current_timestamp: self.current_timestamp.as_unix_timestamp_secs(), - })?; - Ok(s) - } -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct JSONUpdateClientCommitmentProof { - #[serde(with = "serde_base64")] - pub commitment_bytes: Vec, - #[serde(with = "serde_base64")] - pub signer: Vec, - #[serde(with = "serde_base64")] - pub signature: Vec, -} - -impl JSONSerializer for UpdateClientCommitmentProof { - fn to_json_string(&self) -> Result { - Ok(serde_json::to_string(&JSONUpdateClientCommitmentProof { - commitment_bytes: self.commitment_bytes.clone(), - signer: self.signer.clone(), - signature: self.signature.clone(), - })?) - } -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct JSONStateCommitmentProof { - #[serde(with = "serde_base64")] - pub commitment_bytes: Vec, - #[serde(with = "serde_base64")] - pub signer: Vec, - #[serde(with = "serde_base64")] - pub signature: Vec, - #[serde(with = "serde_base64")] - pub proof: Vec, -} - -impl JSONSerializer for StateCommitmentProof { - fn to_json_string(&self) -> Result { - let mut st = rlp::RlpStream::new_list(3); - st.append(&self.commitment_bytes) - .append(&self.signer) - .append(&self.signature); - let proof = st.out().to_vec(); - - Ok(serde_json::to_string(&JSONStateCommitmentProof { - commitment_bytes: self.commitment_bytes.clone(), - signer: self.signer.clone(), - signature: self.signature.clone(), - proof, - })?) - } -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct JSONVerifyMembershipInput { - pub client_id: ClientId, - #[serde(with = "serde_base64")] - pub prefix: Vec, - pub path: String, - #[serde(with = "serde_base64")] - pub value: Vec, -} - -impl JSONSerializer for VerifyMembershipInput { - fn to_json_string(&self) -> Result { - Ok(serde_json::to_string(&JSONVerifyMembershipInput { - client_id: self.client_id.clone(), - prefix: self.prefix.clone(), - path: self.path.clone(), - value: self.value.clone(), - })?) - } -} - -mod serde_base64 { - use serde::{Deserialize, Deserializer, Serialize, Serializer}; - - pub fn serialize(v: &Vec, s: S) -> Result { - let base64 = base64::encode(v); - String::serialize(&base64, s) - } - - pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { - let base64 = String::deserialize(d)?; - base64::decode(base64.as_bytes()).map_err(serde::de::Error::custom) - } -}