diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 000000000..224af64df --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,16 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "lldb", + "request": "launch", + "name": "Debug", + "program": "${workspaceFolder}/", + "args": [], + "cwd": "${workspaceFolder}" + } + ] +} \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index ab3be4dbf..25a00404d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -175,7 +175,7 @@ dependencies = [ "lazy_static", "log 0.4.11", "num_cpus", - "parking_lot 0.11.0", + "parking_lot 0.11.1", "threadpool", ] @@ -936,7 +936,7 @@ dependencies = [ "encode_unicode", "lazy_static", "libc", - "parking_lot 0.11.0", + "parking_lot 0.10.2", "regex", "termios", "unicode-width", @@ -1571,7 +1571,9 @@ dependencies = [ "base64 0.11.0", "ed25519-dalek", "lazy_static", + "once_cell 1.5.2", "parity-scale-codec", + "parking_lot 0.11.1", "rand 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", "rand_core 0.3.1", "rand_os", @@ -1800,7 +1802,7 @@ version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96d502af37186c4fef99453df03e374683f8a1eec9dcc1e66b3b82dc8278ce3c" dependencies = [ - "once_cell 1.4.1", + "once_cell 1.5.2", ] [[package]] @@ -2844,9 +2846,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.4.1" +version = "1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "260e51e7efe62b592207e9e13a68e43692a7a279171d6ba57abd208bf23645ad" +checksum = "13bd41f508810a131401606d54ac32a467c97172d74ba7662562ebba5ad07fa0" [[package]] name = "opaque-debug" @@ -2973,9 +2975,9 @@ dependencies = [ [[package]] name = "parking_lot" -version = "0.11.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4893845fa2ca272e647da5d0e46660a314ead9c2fdd9a883aabc32e481a8733" +checksum = "6d7744ac029df22dca6284efe4e898991d28e3085c706c972bcd7da4a27a15eb" dependencies = [ "instant", "lock_api 0.4.1", @@ -3588,7 +3590,7 @@ checksum = "952cd6b98c85bbc30efa1ba5783b8abf12fec8b3287ffa52605b9432313e34e4" dependencies = [ "cc", "libc", - "once_cell 1.4.1", + "once_cell 1.5.2", "spin", "untrusted", "web-sys", @@ -5144,7 +5146,7 @@ dependencies = [ "jsonrpc-core", "log 0.4.11", "native-tls", - "parking_lot 0.11.0", + "parking_lot 0.11.1", "rlp", "rustc-hex", "secp256k1", diff --git a/docker-compose.yml b/docker-compose.yml index a346db81d..e018bac05 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,6 +1,6 @@ version: "3.7" services: - sgx_machine: + sgx_machine_kim: image: osuketh/anonify:1804-1.1.3 volumes: - .:/root/anonify @@ -13,22 +13,22 @@ services: stdin_open: true tty: true networks: - testing_net: - ipv4_address: 172.28.1.1 + testing_net_kim: + ipv4_address: 172.48.1.1 - ganache: + ganache_kim: image: trufflesuite/ganache-cli:latest ports: - - "8545:8545" + - "28545:8545" volumes: - ./ganache_data:/ganache_data networks: - testing_net: - ipv4_address: 172.28.0.2 + testing_net_kim: + ipv4_address: 172.48.0.2 networks: - testing_net: + testing_net_kim: ipam: driver: default config: - - subnet: 172.28.0.0/16 \ No newline at end of file + - subnet: 172.48.0.0/16 \ No newline at end of file diff --git a/example/erc20/server/src/tests.rs b/example/erc20/server/src/tests.rs index 2bbb977e7..fc9c640a7 100644 --- a/example/erc20/server/src/tests.rs +++ b/example/erc20/server/src/tests.rs @@ -622,7 +622,7 @@ async fn test_join_group_then_handshake() { } fn set_server_env_vars() { - env::set_var("ETH_URL", "http://172.28.0.2:8545"); + env::set_var("ETH_URL", "http://172.48.0.2:8545"); env::set_var("ABI_PATH", "../../../contract-build/Anonify.abi"); env::set_var("BIN_PATH", "../../../contract-build/Anonify.bin"); env::set_var("CONFIRMATIONS", "0"); diff --git a/frame/common/Cargo.toml b/frame/common/Cargo.toml index fba47606e..c9ac947e0 100644 --- a/frame/common/Cargo.toml +++ b/frame/common/Cargo.toml @@ -21,6 +21,8 @@ rand_core = { version = "0.3", optional = true } rand_os = { version = "0.1", optional = true } base64 = { version = "0.11", optional = true } lazy_static = { version = "1.4", features = ["spin_no_std"] } +once_cell = "1.5.2" +parking_lot = "0.11.1" [features] default = ["std"] diff --git a/frame/common/src/benchmark.rs b/frame/common/src/benchmark.rs new file mode 100644 index 000000000..fb3c5432a --- /dev/null +++ b/frame/common/src/benchmark.rs @@ -0,0 +1,9 @@ +// use crate::localstd::{collections::HashMap, time::SystemTime}; +// use once_cell::sync::Lazy; +// use parking_lot::Mutex; + +// static PENDING_TX: Lazy>> = Lazy::new(|| { +// let mut m = HashMap::new(); +// m.insert(0, SystemTime::now()); +// Mutex::new(m) +// }); \ No newline at end of file diff --git a/frame/common/src/lib.rs b/frame/common/src/lib.rs index 5f726634e..0121d88e9 100644 --- a/frame/common/src/lib.rs +++ b/frame/common/src/lib.rs @@ -17,6 +17,7 @@ use sgx_anyhow as local_anyhow; #[macro_use] extern crate lazy_static; +// pub mod benchmark; pub mod crypto; pub mod state_types; pub mod traits; diff --git a/frame/enclave/src/register.rs b/frame/enclave/src/register.rs index d0b905a77..fac3febc7 100644 --- a/frame/enclave/src/register.rs +++ b/frame/enclave/src/register.rs @@ -24,7 +24,14 @@ macro_rules! register_ecall { let input = EE::EI::decode(&mut &input_payload[..]) .map_err(|e| anyhow!("{:?}", e))?; EE::eval_policy(&input)?; + + let t4 = std::time::SystemTime::now(); + println!("########## t4: {:?}", t4); + // txを送る側の場合、MsgSenderのhandleを、 + // eventを取得する側の場合、MsgReceiverのhandleを実行 let res = EE::handle::<$runtime_exec, $ctx_ops>(input, $ctx, $max_mem)?; + let t5 = std::time::SystemTime::now(); + println!("########## t5: {:?}", t5); Ok(res.encode()) } diff --git a/frame/host/src/ecalls.rs b/frame/host/src/ecalls.rs index 6abf7643f..ba7a59ea2 100644 --- a/frame/host/src/ecalls.rs +++ b/frame/host/src/ecalls.rs @@ -51,7 +51,8 @@ impl EnclaveConnector { let output_ptr = output_buf.as_mut_ptr(); let mut ret = EnclaveStatus::default(); - + let t3 = std::time::SystemTime::now(); + println!("########## t3: {:?}", t3); let status = unsafe { ecall_entry_point( self.eid, @@ -64,6 +65,8 @@ impl EnclaveConnector { &mut output_len, ) }; + let t6 = std::time::SystemTime::now(); + println!("########## t6: {:?}", t6); if status != sgx_status_t::SGX_SUCCESS { return Err(FrameHostError::SgxStatus { diff --git a/frame/host/src/engine.rs b/frame/host/src/engine.rs index c7f930a9b..eb464fba0 100644 --- a/frame/host/src/engine.rs +++ b/frame/host/src/engine.rs @@ -16,7 +16,7 @@ pub trait HostEngine { let (ecall_input, host_output) = input.apply()?; let ecall_output = EnclaveConnector::new(eid, Self::OUTPUT_MAX_LEN) .invoke_ecall::(Self::CMD, ecall_input)?; - + host_output.set_ecall_output(ecall_output) } } diff --git a/modules/anonify-enclave/src/commands.rs b/modules/anonify-enclave/src/commands.rs index 4a977085e..01593f4de 100644 --- a/modules/anonify-enclave/src/commands.rs +++ b/modules/anonify-enclave/src/commands.rs @@ -35,21 +35,23 @@ impl EnclaveEngine for MsgSender { R: RuntimeExecutor, C: ContextOps + Clone, { + // グループキー取得 let group_key = &mut *enclave_context.write_group_key(); let roster_idx = group_key.my_roster_idx() as usize; + // 送信側のグループ鍵交換 // ratchet sender's app keychain per tx. group_key.sender_ratchet(roster_idx)?; - let account_id = ecall_input.access_policy().into_account_id(); + // 暗号化された状態遷移コマンドを復号 let mut command = enclave_context.decrypt(ecall_input.encrypted_command)?; - + // 暗号文作成(TX送信用?) let ciphertext = Commands::::new(ecall_input.call_id, &mut command, account_id)? .encrypt(group_key, max_mem_size)?; - + // 署名 let msg = Sha256::hash(&ciphertext.encode()); let enclave_sig = enclave_context.sign(msg.as_bytes())?; + // コマンド(TXに入れるやつ)生成 let command_output = output::Command::new(ciphertext, enclave_sig.0, enclave_sig.1); - enclave_context.set_notification(account_id); Ok(command_output) @@ -64,6 +66,7 @@ impl EnclaveEngine for MsgReceiver { type EI = input::InsertCiphertext; type EO = output::ReturnUpdatedState; + // BCからeventを取得して、その中に暗号文が入っている場合、Enclaveの中ではこの処理が実行される fn handle( ecall_input: Self::EI, enclave_context: &C, @@ -86,10 +89,12 @@ impl EnclaveEngine for MsgReceiver { // In addition to these, `sync_ratchet` fails even if the receiver generation is larger than that of the sender // So if you run `sync_ratchet` first, // it will either succeed or both fail for the mutable `app_keychain`, so it will be atomic. + // グループキー同期 group_key.sync_ratchet(roster_idx, msg_gen)?; group_key.receiver_ratchet(roster_idx)?; - // Even if an error occurs in the state transition logic here, there is no problem because the state of `app_keychain` is consistent. + // 状態遷移ロジック実行 + // 暗号文を平文に変換し、runtime上で状態遷移を実行 let iter_op = Commands::::state_transition( enclave_context.clone(), ecall_input.ciphertext(), @@ -98,6 +103,7 @@ impl EnclaveEngine for MsgReceiver { let mut output = output::ReturnUpdatedState::default(); if let Some(updated_state_iter) = iter_op { + // 状態遷移処理が成功したらupdate_state -> insert_by_updated_state if let Some(updated_state) = enclave_context.update_state(updated_state_iter) { output.update(updated_state); } diff --git a/modules/anonify-eth-driver/src/dispatcher.rs b/modules/anonify-eth-driver/src/dispatcher.rs index 1feaac0dd..585d2004a 100644 --- a/modules/anonify-eth-driver/src/dispatcher.rs +++ b/modules/anonify-eth-driver/src/dispatcher.rs @@ -187,8 +187,11 @@ where gas, ); let eid = inner.deployer.get_enclave_id(); + let t2 = std::time::SystemTime::now(); + println!("########## t2: {:?}", t2); let host_output = CommandWorkflow::exec(input, eid)?; - + let t7 = std::time::SystemTime::now(); + println!("########## t7: {:?}", t7); match &inner.sender { Some(s) => s.send_command(host_output).await, None => Err(HostError::AddressNotSet), diff --git a/modules/anonify-eth-driver/src/eth/connection.rs b/modules/anonify-eth-driver/src/eth/connection.rs index 544097760..a5fb08a65 100644 --- a/modules/anonify-eth-driver/src/eth/connection.rs +++ b/modules/anonify-eth-driver/src/eth/connection.rs @@ -111,6 +111,8 @@ impl Web3Contract { enclave_sig.push(recovery_id); let gas = output.gas; + let t8 = std::time::SystemTime::now(); + println!("############### t8 {:?}", t8); self.contract .call( "storeCommand", diff --git a/modules/anonify-eth-driver/src/eth/event_watcher.rs b/modules/anonify-eth-driver/src/eth/event_watcher.rs index d2f7067e3..d42a63bde 100644 --- a/modules/anonify-eth-driver/src/eth/event_watcher.rs +++ b/modules/anonify-eth-driver/src/eth/event_watcher.rs @@ -49,13 +49,19 @@ impl Watcher for EventWatcher { &self, eid: sgx_enclave_id_t, ) -> Result>>> { - let enclave_updated_state = self + let event_logs = self .contract .get_event(self.cache.clone(), self.contract.address()) - .await? - .into_enclave_log() - .insert_enclave(eid) - .save_cache(self.contract.address()); + .await?; + + let t10 = std::time::SystemTime::now(); + println!("########## t10: {:?}", t10); + let enclave_updated_state = event_logs.into_enclave_log() + .insert_enclave(eid); + let t11 = std::time::SystemTime::now(); + println!("########## t11: {:?}", t11); + + let enclave_updated_state = enclave_updated_state.save_cache(self.contract.address()); Ok(enclave_updated_state.updated_states()) } @@ -194,6 +200,7 @@ impl EnclaveLog { match self.inner { Some(log) => { let next_blc_num = log.latest_blc_num + 1; + // ここね! let updated_states = log.invoke_ecall(eid); EnclaveUpdatedState { @@ -230,6 +237,7 @@ impl InnerEnclaveLog { for e in self.payloads { match e.payload { + // 暗号文が存在してたらそれをTEE上で処理する Payload::Ciphertext(ciphertext) => { info!( "Fetch a ciphertext: roster_idx: {}, epoch: {}, generation: {}", @@ -239,6 +247,7 @@ impl InnerEnclaveLog { ); let inp = host_input::InsertCiphertext::new(ciphertext.clone()); + // InsertCiphertextWorkflowのCMDは2 match InsertCiphertextWorkflow::exec(inp, eid) .map_err(Into::into) .and_then(|e| { diff --git a/modules/anonify-eth-driver/src/eth/sender.rs b/modules/anonify-eth-driver/src/eth/sender.rs index 06c2a386c..69e408013 100644 --- a/modules/anonify-eth-driver/src/eth/sender.rs +++ b/modules/anonify-eth-driver/src/eth/sender.rs @@ -60,6 +60,7 @@ impl Sender for EthSender { async fn send_command(&self, host_output: host_output::Command) -> Result { info!("Sending a command to blockchain: {:?}", host_output); + // コントラクト実行 self.contract.send_command(host_output).await } diff --git a/scripts/test.sh b/scripts/test.sh index cec4bb3f5..311ab063f 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -25,15 +25,15 @@ cd ../tests/integration RUST_BACKTRACE=1 RUST_LOG=debug cargo test -- --nocapture cd ../../example/erc20/server -RUST_BACKTRACE=1 RUST_LOG=debug cargo test test_deploy_post -- --nocapture -sleep 1 -RUST_BACKTRACE=1 RUST_LOG=debug cargo test test_multiple_messages -- --nocapture -sleep 1 -RUST_BACKTRACE=1 RUST_LOG=debug cargo test test_skip_invalid_event -- --nocapture -sleep 1 -RUST_BACKTRACE=1 RUST_LOG=debug cargo test test_node_recovery -- --nocapture -sleep 1 -RUST_BACKTRACE=1 RUST_LOG=debug cargo test test_join_group_then_handshake -- --nocapture +# RUST_BACKTRACE=1 RUST_LOG=debug cargo test test_deploy_post -- --nocapture +# sleep 1 +# RUST_BACKTRACE=1 RUST_LOG=debug cargo test test_multiple_messages -- --nocapture +# sleep 1 +# RUST_BACKTRACE=1 RUST_LOG=debug cargo test test_skip_invalid_event -- --nocapture +# sleep 1 +# RUST_BACKTRACE=1 RUST_LOG=debug cargo test test_node_recovery -- --nocapture +# sleep 1 +# RUST_BACKTRACE=1 RUST_LOG=debug cargo test test_join_group_then_handshake -- --nocapture echo "Unit testing..." cd ../../../scripts diff --git a/tests/integration/src/lib.rs b/tests/integration/src/lib.rs index 72059ec89..f3fe96af7 100644 --- a/tests/integration/src/lib.rs +++ b/tests/integration/src/lib.rs @@ -22,7 +22,7 @@ use web3::{ Web3, }; -const ETH_URL: &str = "http://172.28.0.2:8545"; +const ETH_URL: &str = "http://172.48.0.2:8545"; const ABI_PATH: &str = "../../contract-build/Anonify.abi"; const BIN_PATH: &str = "../../contract-build/Anonify.bin"; const CONFIRMATIONS: usize = 0; @@ -45,7 +45,6 @@ pub async fn get_encrypting_key( let address = Address::from_str(contract_addr).unwrap(); let f = File::open(ABI_PATH).unwrap(); let abi = ContractABI::load(BufReader::new(f)).unwrap(); - let query_encrypting_key: Vec = Contract::new(web3_conn, address, abi) .query( "getEncryptingKey", @@ -310,7 +309,13 @@ async fn test_integration_eth_transfer() { let amount = U64::from_raw(30); let recipient = other_access_policy.into_account_id(); let transfer_cmd = transfer { amount, recipient }; + + // TEEで実行する状態遷移コマンド(transfer)を暗号化(ECIES暗号文取得) let encrypted_command = EciesCiphertext::encrypt(&pubkey, transfer_cmd.encode()).unwrap(); + // TXを生成し、BCに送信する処理 + // 中でグループキーのローテーションや各種暗号処理を行い、最後にBCへTXを送信 + let t1 = std::time::SystemTime::now(); + println!("########## t1: {:?}", t1); let receipt = dispatcher .send_command::( my_access_policy.clone(), @@ -321,11 +326,16 @@ async fn test_integration_eth_transfer() { ) .await .unwrap(); - println!("receipt: {:?}", receipt); + let t9 = std::time::SystemTime::now(); + println!("########## t9: {:?}", t9); + // println!("receipt: {:?}", receipt); + + // BCからイベントを取得 // Update state inside enclave dispatcher.fetch_events::().await.unwrap(); - + let t12 = std::time::SystemTime::now(); + println!("########## t12: {:?}", t12); // Check the updated states let my_updated_state = dispatcher .get_state::(my_access_policy, "balance_of")