From 99780d3eb0b4a2bf56587168c2486669572bccda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Stuczy=C5=84ski?= Date: Thu, 27 May 2021 11:27:09 +0100 Subject: [PATCH 1/7] Updated smart contract to work with future cosmwasm 0.14.0 update --- Cargo.lock | 193 ++++++++++++-- common/mixnet-contract/Cargo.toml | 4 +- common/mixnet-contract/src/gateway.rs | 18 +- common/mixnet-contract/src/lib.rs | 2 +- common/mixnet-contract/src/mixnode.rs | 18 +- contracts/mixnet/Cargo.lock | 354 ++++++++++++++++++++++++-- contracts/mixnet/Cargo.toml | 8 +- contracts/mixnet/examples/schema.rs | 6 +- contracts/mixnet/src/contract.rs | 55 ++-- contracts/mixnet/src/error.rs | 8 +- contracts/mixnet/src/helpers.rs | 2 +- contracts/mixnet/src/lib.rs | 3 - contracts/mixnet/src/msg.rs | 17 +- contracts/mixnet/src/queries.rs | 94 ++++--- contracts/mixnet/src/state.rs | 6 +- contracts/mixnet/src/storage.rs | 18 +- contracts/mixnet/src/support/tests.rs | 16 +- contracts/mixnet/src/transactions.rs | 331 ++++++++++++------------ 18 files changed, 834 insertions(+), 319 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a3e1814e16..d07581e2d3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -223,6 +223,17 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +[[package]] +name = "bitvec" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98fcd36dda4e17b7d7abc64cb549bf0201f4ab71e00700c798ca7e62ed3761fa" +dependencies = [ + "funty", + "radium", + "wyz", +] + [[package]] name = "blake2" version = "0.8.1" @@ -458,6 +469,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "const-oid" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f6b64db6932c7e49332728e3a6bd82c6b7e16016607d20923b537c3bc4c0d5f" + [[package]] name = "const_fn" version = "0.4.7" @@ -504,21 +521,35 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea221b5284a47e40033bf9b66f35f984ec0ea2931eb03505246cd27a963f981b" [[package]] -name = "cosmwasm-derive" -version = "0.13.2" +name = "cosmwasm-crypto" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de70197a0fe4e402aa260da00ec62d9bf091afe87866e9f3347691d591b60f89" +checksum = "3ddbf475b0e8a9bd813607d59144ad3f71d90dd66c5e975a46ac2b72ce754121" +dependencies = [ + "digest 0.9.0", + "ed25519-zebra", + "k256", + "rand_core 0.5.1", + "thiserror", +] + +[[package]] +name = "cosmwasm-derive" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4e62de21147741486c6d4adc28850b102dcad1888d9fc2d0a200ca423284563" dependencies = [ "syn", ] [[package]] name = "cosmwasm-std" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02173c4eb78ef76863f5190f60a45278d11e7c8b142327c149e18128b2b97f85" +checksum = "db14129579ddb1dbd8a28376673d61090f35c9069978eb875d489c275bb76315" dependencies = [ "base64 0.13.0", + "cosmwasm-crypto", "cosmwasm-derive", "schemars", "serde", @@ -604,7 +635,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b584a330336237c1eecd3e94266efb216c56ed91225d634cb2991c5f3fd1aeab" dependencies = [ "generic-array 0.14.4", - "subtle 2.2.3", + "subtle 2.4.0", ] [[package]] @@ -614,7 +645,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4857fd85a0c34b3c3297875b747c1e02e06b6a0ea32dd892d8192b9ce0813ea6" dependencies = [ "generic-array 0.14.4", - "subtle 2.2.3", + "subtle 2.4.0", ] [[package]] @@ -645,7 +676,7 @@ dependencies = [ "byteorder", "digest 0.9.0", "rand_core 0.5.1", - "subtle 2.2.3", + "subtle 2.4.0", "zeroize", ] @@ -659,6 +690,15 @@ dependencies = [ "num_cpus", ] +[[package]] +name = "der" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51f59c66c30bb7445c8320a5f9233e437e3572368099f25532a59054328899b4" +dependencies = [ + "const-oid", +] + [[package]] name = "derive_more" version = "0.99.13" @@ -763,6 +803,23 @@ version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f" +[[package]] +name = "dyn-clone" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee2626afccd7561a06cf1367e2950c4718ea04565e20fb5029b6c7d8ad09abcf" + +[[package]] +name = "ecdsa" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fbdb4ff710acb4db8ca29f93b897529ea6d6a45626d5183b47e012aa6ae7e4" +dependencies = [ + "elliptic-curve", + "hmac 0.10.1", + "signature", +] + [[package]] name = "ed25519" version = "1.0.1" @@ -786,12 +843,44 @@ dependencies = [ "zeroize", ] +[[package]] +name = "ed25519-zebra" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a128b76af6dd4b427e34a6fd43dc78dbfe73672ec41ff615a2414c1a0ad0409" +dependencies = [ + "curve25519-dalek", + "hex", + "rand_core 0.5.1", + "serde", + "sha2 0.9.1", + "thiserror", +] + [[package]] name = "either" version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" +[[package]] +name = "elliptic-curve" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2db227e61a43a34915680bdda462ec0e212095518020a88a1f91acd16092c39" +dependencies = [ + "bitvec", + "digest 0.9.0", + "ff", + "funty", + "generic-array 0.14.4", + "group", + "pkcs8", + "rand_core 0.5.1", + "subtle 2.4.0", + "zeroize", +] + [[package]] name = "encoding_rs" version = "0.8.24" @@ -820,6 +909,17 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" +[[package]] +name = "ff" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01646e077d4ebda82b73f1bca002ea1e91561a77df2431a9e79729bcc31950ef" +dependencies = [ + "bitvec", + "rand_core 0.5.1", + "subtle 2.4.0", +] + [[package]] name = "figment" version = "0.10.5" @@ -875,6 +975,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "funty" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fed34cd105917e91daa4da6b3728c47b068749d6a62c59811f06ed2ac71d9da7" + [[package]] name = "futures" version = "0.3.9" @@ -1078,6 +1184,17 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" +[[package]] +name = "group" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc11f9f5fbf1943b48ae7c2bf6846e7d827a512d1be4f23af708f5ca5d01dde1" +dependencies = [ + "ff", + "rand_core 0.5.1", + "subtle 2.4.0", +] + [[package]] name = "h2" version = "0.3.1" @@ -1126,6 +1243,12 @@ dependencies = [ "libc", ] +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "hkdf" version = "0.8.0" @@ -1344,6 +1467,18 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "k256" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4476a0808212a9e81ce802eb1a0cfc60e73aea296553bacc0fac7e1268bc572a" +dependencies = [ + "cfg-if 1.0.0", + "ecdsa", + "elliptic-curve", + "sha2 0.9.1", +] + [[package]] name = "keystream" version = "1.0.0" @@ -2140,6 +2275,15 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[package]] +name = "pkcs8" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4839a901843f3942576e65857f0ebf2e190ef7024d3c62a94099ba3f819ad1d" +dependencies = [ + "der", +] + [[package]] name = "pkg-config" version = "0.3.18" @@ -2242,6 +2386,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "radium" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "def50a86306165861203e7f84ecffbbdfdea79f0e51039b33de1e952358c47ac" + [[package]] name = "rand" version = "0.7.3" @@ -2574,10 +2724,11 @@ dependencies = [ [[package]] name = "schemars" -version = "0.7.6" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be77ed66abed6954aabf6a3e31a84706bedbf93750d267e92ef4a6d90bbd6a61" +checksum = "bc6ab463ae35acccb5cba66c0084c985257b797d288b6050cc2f6ac1b266cb78" dependencies = [ + "dyn-clone", "schemars_derive", "serde", "serde_json", @@ -2585,9 +2736,9 @@ dependencies = [ [[package]] name = "schemars_derive" -version = "0.7.6" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11af7a475c9ee266cfaa9e303a47c830ebe072bf3101ab907a7b7b9d816fa01d" +checksum = "902fdfbcf871ae8f653bddf4b2c05905ddaabc08f69d32a915787e3be0d31356" dependencies = [ "proc-macro2", "quote", @@ -2674,9 +2825,9 @@ dependencies = [ [[package]] name = "serde-json-wasm" -version = "0.2.3" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "120bad73306616e91acd7ceed522ba96032a51cffeef3cc813de7f367df71e37" +checksum = "50eef3672ec8fa45f3457fd423ba131117786784a895548021976117c1ded449" dependencies = [ "serde", ] @@ -2797,6 +2948,10 @@ name = "signature" version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29f060a7d147e33490ec10da418795238fd7545bba241504d6b31a409f2e6210" +dependencies = [ + "digest 0.9.0", + "rand_core 0.5.1", +] [[package]] name = "slab" @@ -2995,9 +3150,9 @@ checksum = "2d67a5a62ba6e01cb2192ff309324cb4875d0c451d55fe2319433abe7a05a8ee" [[package]] name = "subtle" -version = "2.2.3" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "502d53007c02d7605a05df1c1a73ee436952781653da5d0bf57ad608f66932c1" +checksum = "1e81da0851ada1f3e9d4312c704aa4f8806f0f9d69faaf8df2f3464b4a9437c2" [[package]] name = "syn" @@ -3647,6 +3802,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "wyz" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85e60b0d1b5f99db2556934e21937020776a5d31520bf169e851ac44e6420214" + [[package]] name = "x25519-dalek" version = "1.1.0" diff --git a/common/mixnet-contract/Cargo.toml b/common/mixnet-contract/Cargo.toml index 75a67f9140..5130f70776 100644 --- a/common/mixnet-contract/Cargo.toml +++ b/common/mixnet-contract/Cargo.toml @@ -7,6 +7,6 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -cosmwasm-std = { version = "0.13.2" } +cosmwasm-std = { version = "0.14.0" } serde = { version = "1.0", features = ["derive"] } -schemars = "0.7" +schemars = "0.8" diff --git a/common/mixnet-contract/src/gateway.rs b/common/mixnet-contract/src/gateway.rs index 301a011278..1abee2a4ef 100644 --- a/common/mixnet-contract/src/gateway.rs +++ b/common/mixnet-contract/src/gateway.rs @@ -1,7 +1,7 @@ // due to code generated by JsonSchema #![allow(clippy::field_reassign_with_default)] -use cosmwasm_std::{Coin, HumanAddr}; +use cosmwasm_std::{Addr, Coin}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::fmt::Display; @@ -49,12 +49,12 @@ impl Gateway { #[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)] pub struct GatewayBond { pub amount: Vec, - pub owner: HumanAddr, + pub owner: Addr, pub gateway: Gateway, } impl GatewayBond { - pub fn new(amount: Vec, owner: HumanAddr, gateway: Gateway) -> Self { + pub fn new(amount: Vec, owner: Addr, gateway: Gateway) -> Self { GatewayBond { amount, owner, @@ -66,7 +66,7 @@ impl GatewayBond { &self.amount } - pub fn owner(&self) -> &HumanAddr { + pub fn owner(&self) -> &Addr { &self.owner } @@ -93,15 +93,11 @@ impl Display for GatewayBond { pub struct PagedGatewayResponse { pub nodes: Vec, pub per_page: usize, - pub start_next_after: Option, + pub start_next_after: Option, } impl PagedGatewayResponse { - pub fn new( - nodes: Vec, - per_page: usize, - start_next_after: Option, - ) -> Self { + pub fn new(nodes: Vec, per_page: usize, start_next_after: Option) -> Self { PagedGatewayResponse { nodes, per_page, @@ -112,6 +108,6 @@ impl PagedGatewayResponse { #[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)] pub struct GatewayOwnershipResponse { - pub address: HumanAddr, + pub address: Addr, pub has_gateway: bool, } diff --git a/common/mixnet-contract/src/lib.rs b/common/mixnet-contract/src/lib.rs index 0ffefd312d..cd1dedee33 100644 --- a/common/mixnet-contract/src/lib.rs +++ b/common/mixnet-contract/src/lib.rs @@ -1,6 +1,6 @@ mod gateway; mod mixnode; -pub use cosmwasm_std::{Coin, HumanAddr}; +pub use cosmwasm_std::{Coin, Addr}; pub use gateway::{Gateway, GatewayBond, GatewayOwnershipResponse, PagedGatewayResponse}; pub use mixnode::{MixNode, MixNodeBond, MixOwnershipResponse, PagedResponse}; diff --git a/common/mixnet-contract/src/mixnode.rs b/common/mixnet-contract/src/mixnode.rs index cd205a0a50..83aca98c63 100644 --- a/common/mixnet-contract/src/mixnode.rs +++ b/common/mixnet-contract/src/mixnode.rs @@ -1,7 +1,7 @@ // due to code generated by JsonSchema #![allow(clippy::field_reassign_with_default)] -use cosmwasm_std::{Coin, HumanAddr}; +use cosmwasm_std::{Addr, Coin}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::fmt::Display; @@ -49,12 +49,12 @@ impl MixNode { #[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)] pub struct MixNodeBond { pub amount: Vec, - pub owner: HumanAddr, + pub owner: Addr, pub mix_node: MixNode, } impl MixNodeBond { - pub fn new(amount: Vec, owner: HumanAddr, mix_node: MixNode) -> Self { + pub fn new(amount: Vec, owner: Addr, mix_node: MixNode) -> Self { MixNodeBond { amount, owner, @@ -66,7 +66,7 @@ impl MixNodeBond { &self.amount } - pub fn owner(&self) -> &HumanAddr { + pub fn owner(&self) -> &Addr { &self.owner } @@ -97,15 +97,11 @@ impl Display for MixNodeBond { pub struct PagedResponse { pub nodes: Vec, pub per_page: usize, - pub start_next_after: Option, + pub start_next_after: Option, } impl PagedResponse { - pub fn new( - nodes: Vec, - per_page: usize, - start_next_after: Option, - ) -> Self { + pub fn new(nodes: Vec, per_page: usize, start_next_after: Option) -> Self { PagedResponse { nodes, per_page, @@ -116,6 +112,6 @@ impl PagedResponse { #[derive(Clone, Debug, Deserialize, PartialEq, Serialize, JsonSchema)] pub struct MixOwnershipResponse { - pub address: HumanAddr, + pub address: Addr, pub has_node: bool, } diff --git a/contracts/mixnet/Cargo.lock b/contracts/mixnet/Cargo.lock index 04a7d9a5ae..34467e9eb4 100644 --- a/contracts/mixnet/Cargo.lock +++ b/contracts/mixnet/Cargo.lock @@ -7,19 +7,70 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" [[package]] -name = "cosmwasm-derive" -version = "0.13.2" +name = "bitvec" +version = "0.18.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de70197a0fe4e402aa260da00ec62d9bf091afe87866e9f3347691d591b60f89" +checksum = "98fcd36dda4e17b7d7abc64cb549bf0201f4ab71e00700c798ca7e62ed3761fa" +dependencies = [ + "funty", + "radium", + "wyz", +] + +[[package]] +name = "block-buffer" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" +dependencies = [ + "generic-array", +] + +[[package]] +name = "byteorder" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "const-oid" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f6b64db6932c7e49332728e3a6bd82c6b7e16016607d20923b537c3bc4c0d5f" + +[[package]] +name = "cosmwasm-crypto" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ddbf475b0e8a9bd813607d59144ad3f71d90dd66c5e975a46ac2b72ce754121" +dependencies = [ + "digest", + "ed25519-zebra", + "k256", + "rand_core", + "thiserror", +] + +[[package]] +name = "cosmwasm-derive" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4e62de21147741486c6d4adc28850b102dcad1888d9fc2d0a200ca423284563" dependencies = [ "syn", ] [[package]] name = "cosmwasm-schema" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a98b56c1c839e5cfda1be0e0f152728b34bdcd5a2e921905947f6d088bab2c68" +checksum = "d6a9a6a4ca3b4d7b56f943312a65857cdfc84424f9c2773889f4cd17f36fba61" dependencies = [ "schemars", "serde_json", @@ -27,11 +78,12 @@ dependencies = [ [[package]] name = "cosmwasm-std" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02173c4eb78ef76863f5190f60a45278d11e7c8b142327c149e18128b2b97f85" +checksum = "db14129579ddb1dbd8a28376673d61090f35c9069978eb875d489c275bb76315" dependencies = [ "base64", + "cosmwasm-crypto", "cosmwasm-derive", "schemars", "serde", @@ -41,20 +93,202 @@ dependencies = [ [[package]] name = "cosmwasm-storage" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2cdb5f6c3181c921c02b0018af66178e60bc7be088f81ec730b22ff51240404" +checksum = "13b03dc324ef7b5bce224e096d67bc67e12aadc8fbacb7c8c796eac40cf7c4b8" dependencies = [ "cosmwasm-std", "serde", ] +[[package]] +name = "cpufeatures" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed00c67cb5d0a7d64a44f6ad2668db7e7530311dd53ea79bcd4fb022c64911c8" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-mac" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4857fd85a0c34b3c3297875b747c1e02e06b6a0ea32dd892d8192b9ce0813ea6" +dependencies = [ + "generic-array", + "subtle", +] + +[[package]] +name = "curve25519-dalek" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "639891fde0dbea823fc3d798a0fdf9d2f9440a42d64a78ab3488b0ca025117b3" +dependencies = [ + "byteorder", + "digest", + "rand_core", + "subtle", + "zeroize", +] + +[[package]] +name = "der" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51f59c66c30bb7445c8320a5f9233e437e3572368099f25532a59054328899b4" +dependencies = [ + "const-oid", +] + +[[package]] +name = "digest" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" +dependencies = [ + "generic-array", +] + +[[package]] +name = "dyn-clone" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee2626afccd7561a06cf1367e2950c4718ea04565e20fb5029b6c7d8ad09abcf" + +[[package]] +name = "ecdsa" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fbdb4ff710acb4db8ca29f93b897529ea6d6a45626d5183b47e012aa6ae7e4" +dependencies = [ + "elliptic-curve", + "hmac", + "signature", +] + +[[package]] +name = "ed25519-zebra" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a128b76af6dd4b427e34a6fd43dc78dbfe73672ec41ff615a2414c1a0ad0409" +dependencies = [ + "curve25519-dalek", + "hex", + "rand_core", + "serde", + "sha2", + "thiserror", +] + +[[package]] +name = "elliptic-curve" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2db227e61a43a34915680bdda462ec0e212095518020a88a1f91acd16092c39" +dependencies = [ + "bitvec", + "digest", + "ff", + "funty", + "generic-array", + "group", + "pkcs8", + "rand_core", + "subtle", + "zeroize", +] + +[[package]] +name = "ff" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01646e077d4ebda82b73f1bca002ea1e91561a77df2431a9e79729bcc31950ef" +dependencies = [ + "bitvec", + "rand_core", + "subtle", +] + +[[package]] +name = "funty" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fed34cd105917e91daa4da6b3728c47b068749d6a62c59811f06ed2ac71d9da7" + +[[package]] +name = "generic-array" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "501466ecc8a30d1d3b7fc9229b122b2ce8ed6e9d9223f1138d4babb253e51817" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "group" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc11f9f5fbf1943b48ae7c2bf6846e7d827a512d1be4f23af708f5ca5d01dde1" +dependencies = [ + "ff", + "rand_core", + "subtle", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1441c6b1e930e2817404b5046f1f989899143a12bf92de603b69f4e0aee1e15" +dependencies = [ + "crypto-mac", + "digest", +] + [[package]] name = "itoa" version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736" +[[package]] +name = "k256" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4476a0808212a9e81ce802eb1a0cfc60e73aea296553bacc0fac7e1268bc572a" +dependencies = [ + "cfg-if", + "ecdsa", + "elliptic-curve", + "sha2", +] + +[[package]] +name = "libc" +version = "0.2.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "789da6d93f1b866ffe175afc5322a4d76c038605a1c3319bb57b06967ca98a36" + [[package]] name = "mixnet-contract" version = "0.1.0" @@ -77,6 +311,21 @@ dependencies = [ "thiserror", ] +[[package]] +name = "opaque-debug" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" + +[[package]] +name = "pkcs8" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4839a901843f3942576e65857f0ebf2e190ef7024d3c62a94099ba3f819ad1d" +dependencies = [ + "der", +] + [[package]] name = "proc-macro2" version = "1.0.24" @@ -95,6 +344,21 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "radium" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "def50a86306165861203e7f84ecffbbdfdea79f0e51039b33de1e952358c47ac" + +[[package]] +name = "rand_core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" +dependencies = [ + "getrandom", +] + [[package]] name = "ryu" version = "1.0.5" @@ -103,10 +367,11 @@ checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" [[package]] name = "schemars" -version = "0.7.6" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be77ed66abed6954aabf6a3e31a84706bedbf93750d267e92ef4a6d90bbd6a61" +checksum = "bc6ab463ae35acccb5cba66c0084c985257b797d288b6050cc2f6ac1b266cb78" dependencies = [ + "dyn-clone", "schemars_derive", "serde", "serde_json", @@ -114,9 +379,9 @@ dependencies = [ [[package]] name = "schemars_derive" -version = "0.7.6" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11af7a475c9ee266cfaa9e303a47c830ebe072bf3101ab907a7b7b9d816fa01d" +checksum = "902fdfbcf871ae8f653bddf4b2c05905ddaabc08f69d32a915787e3be0d31356" dependencies = [ "proc-macro2", "quote", @@ -135,9 +400,9 @@ dependencies = [ [[package]] name = "serde-json-wasm" -version = "0.2.3" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "120bad73306616e91acd7ceed522ba96032a51cffeef3cc813de7f367df71e37" +checksum = "50eef3672ec8fa45f3457fd423ba131117786784a895548021976117c1ded449" dependencies = [ "serde", ] @@ -175,6 +440,35 @@ dependencies = [ "serde", ] +[[package]] +name = "sha2" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b362ae5752fd2137731f9fa25fd4d9058af34666ca1966fb969119cc35719f12" +dependencies = [ + "block-buffer", + "cfg-if", + "cpufeatures", + "digest", + "opaque-debug", +] + +[[package]] +name = "signature" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29f060a7d147e33490ec10da418795238fd7545bba241504d6b31a409f2e6210" +dependencies = [ + "digest", + "rand_core", +] + +[[package]] +name = "subtle" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e81da0851ada1f3e9d4312c704aa4f8806f0f9d69faaf8df2f3464b4a9437c2" + [[package]] name = "syn" version = "1.0.60" @@ -206,8 +500,38 @@ dependencies = [ "syn", ] +[[package]] +name = "typenum" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f6906492a7cd215bfa4cf595b600146ccfac0c79bcbd1f3000162af5e8b06" + [[package]] name = "unicode-xid" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" + +[[package]] +name = "version_check" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" + +[[package]] +name = "wasi" +version = "0.9.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" + +[[package]] +name = "wyz" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85e60b0d1b5f99db2556934e21937020776a5d31520bf169e851ac44e6420214" + +[[package]] +name = "zeroize" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4756f7db3f7b5574938c3eb1c117038b8e07f95ee6718c0efad4ac21508f1efd" diff --git a/contracts/mixnet/Cargo.toml b/contracts/mixnet/Cargo.toml index b482d2ff6b..1d9819d318 100644 --- a/contracts/mixnet/Cargo.toml +++ b/contracts/mixnet/Cargo.toml @@ -34,11 +34,11 @@ backtraces = ["cosmwasm-std/backtraces"] [dependencies] mixnet-contract = { path = "../../common/mixnet-contract" } -cosmwasm-std = { version = "0.13.2", features = ["iterator"] } -cosmwasm-storage = { version = "0.13.2", features = ["iterator"] } -schemars = "0.7" +cosmwasm-std = { version = "0.14.0", features = ["iterator"] } +cosmwasm-storage = { version = "0.14.0", features = ["iterator"] } +schemars = "0.8" serde = { version = "1.0.103", default-features = false, features = ["derive"] } thiserror = { version = "1.0.23" } [dev-dependencies] -cosmwasm-schema = { version = "0.13.2" } +cosmwasm-schema = { version = "0.14.0" } diff --git a/contracts/mixnet/examples/schema.rs b/contracts/mixnet/examples/schema.rs index cbe5ce4e9c..ad28a2d7c4 100644 --- a/contracts/mixnet/examples/schema.rs +++ b/contracts/mixnet/examples/schema.rs @@ -1,6 +1,6 @@ use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; use mixnet_contract::MixNodeBond; -use mixnet_contracts::msg::{HandleMsg, InitMsg, QueryMsg}; +use mixnet_contracts::msg::{ExecuteMsg, InstantiateMsg, QueryMsg}; use mixnet_contracts::state::State; use std::env::current_dir; use std::fs::create_dir_all; @@ -11,8 +11,8 @@ fn main() { create_dir_all(&out_dir).unwrap(); remove_schemas(&out_dir).unwrap(); - export_schema(&schema_for!(InitMsg), &out_dir); - export_schema(&schema_for!(HandleMsg), &out_dir); + export_schema(&schema_for!(InstantiateMsg), &out_dir); + export_schema(&schema_for!(ExecuteMsg), &out_dir); export_schema(&schema_for!(QueryMsg), &out_dir); export_schema(&schema_for!(State), &out_dir); export_schema(&schema_for!(MixNodeBond), &out_dir); diff --git a/contracts/mixnet/src/contract.rs b/contracts/mixnet/src/contract.rs index fd69ed5c4d..09cb439d12 100644 --- a/contracts/mixnet/src/contract.rs +++ b/contracts/mixnet/src/contract.rs @@ -1,11 +1,11 @@ use crate::helpers::calculate_epoch_reward_rate; -use crate::msg::{HandleMsg, InitMsg, MigrateMsg, QueryMsg}; +use crate::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg}; use crate::state::{State, StateParams}; use crate::storage::config; use crate::{error::ContractError, queries, transactions}; use cosmwasm_std::{ - to_binary, Decimal, Deps, DepsMut, Env, HandleResponse, HumanAddr, InitResponse, MessageInfo, - MigrateResponse, QueryResponse, Uint128, + entry_point, to_binary, Addr, Decimal, Deps, DepsMut, Env, MessageInfo, QueryResponse, + Response, Uint128, }; pub const INITIAL_DEFAULT_EPOCH_LENGTH: u32 = 2; @@ -27,13 +27,13 @@ const NETWORK_MONITOR_ADDRESS: &str = "hal1v9qauwdq5terag6uvfsdytcs2d0sdmfdq6e83 /// Constant specifying denomination of the coin used for bonding pub const DENOM: &str = "uhal"; -fn default_initial_state(owner: HumanAddr) -> State { +fn default_initial_state(owner: Addr) -> State { let mixnode_bond_reward_rate = Decimal::percent(INITIAL_MIXNODE_BOND_REWARD_RATE); let gateway_bond_reward_rate = Decimal::percent(INITIAL_GATEWAY_BOND_REWARD_RATE); State { owner, - network_monitor_address: NETWORK_MONITOR_ADDRESS.into(), + network_monitor_address: Addr::unchecked(NETWORK_MONITOR_ADDRESS), // we trust our hardcoded value params: StateParams { epoch_length: INITIAL_DEFAULT_EPOCH_LENGTH, minimum_mixnode_bond: INITIAL_MIXNODE_BOND, @@ -58,42 +58,45 @@ fn default_initial_state(owner: HumanAddr) -> State { /// `deps` contains Storage, API and Querier /// `env` contains block, message and contract info /// `msg` is the contract initialization message, sort of like a constructor call. -pub fn init( +#[entry_point] +pub fn instantiate( deps: DepsMut, _env: Env, info: MessageInfo, - _msg: InitMsg, -) -> Result { + _msg: InstantiateMsg, +) -> Result { let state = default_initial_state(info.sender); config(deps.storage).save(&state)?; - Ok(InitResponse::default()) + Ok(Response::default()) } /// Handle an incoming message -pub fn handle( +#[entry_point] +pub fn execute( deps: DepsMut, - env: Env, + _env: Env, info: MessageInfo, - msg: HandleMsg, -) -> Result { + msg: ExecuteMsg, +) -> Result { match msg { - HandleMsg::BondMixnode { mix_node } => transactions::try_add_mixnode(deps, info, mix_node), - HandleMsg::UnbondMixnode {} => transactions::try_remove_mixnode(deps, info, env), - HandleMsg::BondGateway { gateway } => transactions::try_add_gateway(deps, info, gateway), - HandleMsg::UnbondGateway {} => transactions::try_remove_gateway(deps, info, env), - HandleMsg::UpdateStateParams(params) => { + ExecuteMsg::BondMixnode { mix_node } => transactions::try_add_mixnode(deps, info, mix_node), + ExecuteMsg::UnbondMixnode {} => transactions::try_remove_mixnode(deps, info), + ExecuteMsg::BondGateway { gateway } => transactions::try_add_gateway(deps, info, gateway), + ExecuteMsg::UnbondGateway {} => transactions::try_remove_gateway(deps, info), + ExecuteMsg::UpdateStateParams(params) => { transactions::try_update_state_params(deps, info, params) } - HandleMsg::RewardMixnode { owner, uptime } => { + ExecuteMsg::RewardMixnode { owner, uptime } => { transactions::try_reward_mixnode(deps, info, owner, uptime) } - HandleMsg::RewardGateway { owner, uptime } => { + ExecuteMsg::RewardGateway { owner, uptime } => { transactions::try_reward_gateway(deps, info, owner, uptime) } } } +#[entry_point] pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> Result { let query_res = match msg { QueryMsg::GetMixNodes { start_after, limit } => { @@ -114,12 +117,8 @@ pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> Result Result { +#[entry_point] +pub fn migrate(_deps: DepsMut, _env: Env, _msg: MigrateMsg) -> Result { Ok(Default::default()) } @@ -135,10 +134,10 @@ pub mod tests { fn initialize_contract() { let mut deps = mock_dependencies(&[]); let env = mock_env(); - let msg = InitMsg {}; + let msg = InstantiateMsg {}; let info = mock_info("creator", &[]); - let res = init(deps.as_mut(), env.clone(), info, msg).unwrap(); + let res = instantiate(deps.as_mut(), env.clone(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); // mix_node_bonds should be empty after initialization diff --git a/contracts/mixnet/src/error.rs b/contracts/mixnet/src/error.rs index 9a66239cac..dc519df69f 100644 --- a/contracts/mixnet/src/error.rs +++ b/contracts/mixnet/src/error.rs @@ -1,5 +1,5 @@ use crate::contract::DENOM; -use cosmwasm_std::{HumanAddr, StdError}; +use cosmwasm_std::{Addr, StdError}; use thiserror::Error; /// Custom errors for contract failure conditions. @@ -25,7 +25,7 @@ pub enum ContractError { InsufficientGatewayBond { received: u128, minimum: u128 }, #[error("Account ({account:?}) does not own any gateway bonds")] - GatewayBondNotFound { account: HumanAddr }, + GatewayBondNotFound { account: Addr }, #[error("Unauthorized")] Unauthorized, @@ -55,8 +55,8 @@ pub enum ContractError { AlreadyOwnsGateway, #[error("Mixnode with this identity already exists. Its owner is {owner:?}")] - DuplicateMixnode { owner: HumanAddr }, + DuplicateMixnode { owner: Addr }, #[error("Gateway with this identity already exists. Its owner is {owner:?}")] - DuplicateGateway { owner: HumanAddr }, + DuplicateGateway { owner: Addr }, } diff --git a/contracts/mixnet/src/helpers.rs b/contracts/mixnet/src/helpers.rs index 5fbc245e53..ed15c3124c 100644 --- a/contracts/mixnet/src/helpers.rs +++ b/contracts/mixnet/src/helpers.rs @@ -26,7 +26,7 @@ fn decimal_sub_one(value: Decimal) -> Decimal { assert!(value >= Decimal::one()); let value_uint128 = value * DECIMAL_FRACTIONAL; - let uint128_sub_one = (value_uint128 - DECIMAL_FRACTIONAL).unwrap(); + let uint128_sub_one = value_uint128.checked_sub(DECIMAL_FRACTIONAL).unwrap(); Decimal::from_ratio(uint128_sub_one, DECIMAL_FRACTIONAL) } diff --git a/contracts/mixnet/src/lib.rs b/contracts/mixnet/src/lib.rs index 92c4113eeb..b9ebdc473a 100644 --- a/contracts/mixnet/src/lib.rs +++ b/contracts/mixnet/src/lib.rs @@ -7,6 +7,3 @@ pub mod state; pub(crate) mod storage; pub mod support; pub mod transactions; - -#[cfg(target_arch = "wasm32")] -cosmwasm_std::create_entry_points_with_migration!(contract); diff --git a/contracts/mixnet/src/msg.rs b/contracts/mixnet/src/msg.rs index 51bfb18690..772b4e9d42 100644 --- a/contracts/mixnet/src/msg.rs +++ b/contracts/mixnet/src/msg.rs @@ -1,15 +1,14 @@ use crate::state::StateParams; -use cosmwasm_std::HumanAddr; use mixnet_contract::{Gateway, MixNode}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] -pub struct InitMsg {} +pub struct InstantiateMsg {} #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] -pub enum HandleMsg { +pub enum ExecuteMsg { BondMixnode { mix_node: MixNode, }, @@ -21,13 +20,13 @@ pub enum HandleMsg { UpdateStateParams(StateParams), RewardMixnode { - owner: HumanAddr, + owner: String, // percentage value in range 0-100 uptime: u32, }, RewardGateway { - owner: HumanAddr, + owner: String, // percentage value in range 0-100 uptime: u32, }, @@ -38,17 +37,17 @@ pub enum HandleMsg { pub enum QueryMsg { GetMixNodes { limit: Option, - start_after: Option, + start_after: Option, }, GetGateways { - start_after: Option, + start_after: Option, limit: Option, }, OwnsMixnode { - address: HumanAddr, + address: String, }, OwnsGateway { - address: HumanAddr, + address: String, }, StateParams {}, } diff --git a/contracts/mixnet/src/queries.rs b/contracts/mixnet/src/queries.rs index 996c59cb8c..a5b5e8e604 100644 --- a/contracts/mixnet/src/queries.rs +++ b/contracts/mixnet/src/queries.rs @@ -1,7 +1,6 @@ use crate::state::StateParams; use crate::storage::{gateways_read, mixnodes_read, read_state_params}; use cosmwasm_std::Deps; -use cosmwasm_std::HumanAddr; use cosmwasm_std::Order; use cosmwasm_std::StdResult; use mixnet_contract::{ @@ -14,11 +13,24 @@ const DEFAULT_LIMIT: u32 = 50; pub fn query_mixnodes_paged( deps: Deps, - start_after: Option, + start_after: Option, limit: Option, ) -> StdResult { + let input_cline = start_after.clone(); + let start_after_addr = start_after + .map(|start_after| deps.api.addr_validate(&start_after)) // try to validate address + .map_or(Ok(None), |start_after| start_after.map(Some)); // move result in front of the option + + let start_after_addr = match start_after_addr { + Ok(a) => a, + Err(err) => { + println!("{:?} is not a valid address", input_cline); + return Err(err); + } + }; + let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; - let start = calculate_start_value(start_after); + let start = calculate_start_value(start_after_addr); let nodes = mixnodes_read(deps.storage) .range(start.as_deref(), None, Order::Ascending) @@ -33,11 +45,15 @@ pub fn query_mixnodes_paged( pub(crate) fn query_gateways_paged( deps: Deps, - start_after: Option, + start_after: Option, limit: Option, ) -> StdResult { + let start_after_addr = start_after + .map(|start_after| deps.api.addr_validate(&start_after)) // try to validate address + .map_or(Ok(None), |start_after| start_after.map(Some))?; // move result in front of the option + let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize; - let start = calculate_start_value(start_after); + let start = calculate_start_value(start_after_addr); let nodes = gateways_read(deps.storage) .range(start.as_deref(), None, Order::Ascending) @@ -50,25 +66,29 @@ pub(crate) fn query_gateways_paged( Ok(PagedGatewayResponse::new(nodes, limit, start_next_after)) } -pub(crate) fn query_owns_mixnode( - deps: Deps, - address: HumanAddr, -) -> StdResult { +pub(crate) fn query_owns_mixnode(deps: Deps, address: String) -> StdResult { + let validated_address = deps.api.addr_validate(&address)?; + let has_node = mixnodes_read(deps.storage) - .may_load(address.as_ref())? + .may_load(validated_address.as_str().as_bytes())? .is_some(); - Ok(MixOwnershipResponse { address, has_node }) + Ok(MixOwnershipResponse { + address: validated_address, + has_node, + }) } pub(crate) fn query_owns_gateway( deps: Deps, - address: HumanAddr, + address: String, ) -> StdResult { + let validated_address = deps.api.addr_validate(&address)?; + let has_gateway = gateways_read(deps.storage) - .may_load(address.as_ref())? + .may_load(validated_address.as_str().as_bytes())? .is_some(); Ok(GatewayOwnershipResponse { - address, + address: validated_address, has_gateway, }) } @@ -79,11 +99,9 @@ pub(crate) fn query_state_params(deps: Deps) -> StateParams { /// Adds a 0 byte to terminate the `start_after` value given. This allows CosmWasm /// to get the succeeding key as the start of the next page. -fn calculate_start_value( - start_after: std::option::Option, -) -> Option> { +fn calculate_start_value(start_after: std::option::Option) -> Option> { start_after.as_ref().map(|addr| { - let mut bytes = addr.as_bytes().to_owned(); + let mut bytes = addr.as_str().as_bytes().to_owned(); bytes.push(0); bytes }) @@ -95,7 +113,7 @@ mod tests { use crate::state::State; use crate::storage::{config, gateways, mixnodes}; use crate::support::tests::helpers; - use cosmwasm_std::Storage; + use cosmwasm_std::{Addr, Storage}; #[test] fn mixnodes_empty_on_init() { @@ -157,10 +175,15 @@ mod tests { #[test] fn pagination_works() { + let addr1 = "hal100"; + let addr2 = "hal101"; + let addr3 = "hal102"; + let addr4 = "hal103"; + let mut deps = helpers::init_contract(); let node = helpers::mixnode_bond_fixture(); mixnodes(&mut deps.storage) - .save("1".as_bytes(), &node) + .save(addr1.as_bytes(), &node) .unwrap(); let per_page = 2; @@ -171,7 +194,7 @@ mod tests { // save another mixnodes(&mut deps.storage) - .save("2".as_bytes(), &node) + .save(addr2.as_bytes(), &node) .unwrap(); // page1 should have 2 results on it @@ -179,7 +202,7 @@ mod tests { assert_eq!(2, page1.nodes.len()); mixnodes(&mut deps.storage) - .save("3".as_bytes(), &node) + .save(addr3.as_bytes(), &node) .unwrap(); // page1 still has 2 results @@ -187,7 +210,7 @@ mod tests { assert_eq!(2, page1.nodes.len()); // retrieving the next page should start after the last key on this page - let start_after = HumanAddr::from("2"); + let start_after = String::from(addr2); let page2 = query_mixnodes_paged( deps.as_ref(), Option::from(start_after), @@ -199,10 +222,10 @@ mod tests { // save another one mixnodes(&mut deps.storage) - .save("4".as_bytes(), &node) + .save(addr4.as_bytes(), &node) .unwrap(); - let start_after = HumanAddr::from("2"); + let start_after = String::from(addr2); let page2 = query_mixnodes_paged( deps.as_ref(), Option::from(start_after), @@ -269,10 +292,15 @@ mod tests { #[test] fn gateway_pagination_works() { + let addr1 = "hal100"; + let addr2 = "hal101"; + let addr3 = "hal102"; + let addr4 = "hal103"; + let mut deps = helpers::init_contract(); let node = helpers::gateway_bond_fixture(); gateways(&mut deps.storage) - .save("1".as_bytes(), &node) + .save(addr1.as_bytes(), &node) .unwrap(); let per_page = 2; @@ -283,7 +311,7 @@ mod tests { // save another gateways(&mut deps.storage) - .save("2".as_bytes(), &node) + .save(addr2.as_bytes(), &node) .unwrap(); // page1 should have 2 results on it @@ -291,7 +319,7 @@ mod tests { assert_eq!(2, page1.nodes.len()); gateways(&mut deps.storage) - .save("3".as_bytes(), &node) + .save(addr3.as_bytes(), &node) .unwrap(); // page1 still has 2 results @@ -299,7 +327,7 @@ mod tests { assert_eq!(2, page1.nodes.len()); // retrieving the next page should start after the last key on this page - let start_after = HumanAddr::from("2"); + let start_after = String::from(addr2); let page2 = query_gateways_paged( deps.as_ref(), Option::from(start_after), @@ -311,10 +339,10 @@ mod tests { // save another one gateways(&mut deps.storage) - .save("4".as_bytes(), &node) + .save(addr4.as_bytes(), &node) .unwrap(); - let start_after = HumanAddr::from("2"); + let start_after = String::from(addr2); let page2 = query_gateways_paged( deps.as_ref(), Option::from(start_after), @@ -395,8 +423,8 @@ mod tests { let mut deps = helpers::init_contract(); let dummy_state = State { - owner: "someowner".into(), - network_monitor_address: "monitor".into(), + owner: Addr::unchecked("someowner"), + network_monitor_address: Addr::unchecked("monitor"), params: StateParams { epoch_length: 1, minimum_mixnode_bond: 123u128.into(), diff --git a/contracts/mixnet/src/state.rs b/contracts/mixnet/src/state.rs index ece82842d0..90e0124258 100644 --- a/contracts/mixnet/src/state.rs +++ b/contracts/mixnet/src/state.rs @@ -1,11 +1,11 @@ -use cosmwasm_std::{Decimal, HumanAddr, Uint128}; +use cosmwasm_std::{Addr, Decimal, Uint128}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct State { - pub owner: HumanAddr, // only the owner account can update state - pub network_monitor_address: HumanAddr, + pub owner: Addr, // only the owner account can update state + pub network_monitor_address: Addr, pub params: StateParams, // helper values to avoid having to recalculate them on every single payment operation diff --git a/contracts/mixnet/src/storage.rs b/contracts/mixnet/src/storage.rs index f35f3e8df2..f5dace120b 100644 --- a/contracts/mixnet/src/storage.rs +++ b/contracts/mixnet/src/storage.rs @@ -1,5 +1,5 @@ use crate::state::{State, StateParams}; -use cosmwasm_std::{Decimal, HumanAddr, StdError, StdResult, Storage}; +use cosmwasm_std::{Addr, Decimal, StdError, StdResult, Storage}; use cosmwasm_storage::{ bucket, bucket_read, singleton, singleton_read, Bucket, ReadonlyBucket, ReadonlySingleton, Singleton, @@ -53,11 +53,11 @@ pub fn mixnodes_read(storage: &dyn Storage) -> ReadonlyBucket { const PREFIX_MIXNODES_OWNERS: &[u8] = b"mix-owners"; -pub fn mixnodes_owners(storage: &mut dyn Storage) -> Bucket { +pub fn mixnodes_owners(storage: &mut dyn Storage) -> Bucket { bucket(storage, PREFIX_MIXNODES_OWNERS) } -pub fn mixnodes_owners_read(storage: &dyn Storage) -> ReadonlyBucket { +pub fn mixnodes_owners_read(storage: &dyn Storage) -> ReadonlyBucket { bucket_read(storage, PREFIX_MIXNODES_OWNERS) } @@ -110,11 +110,11 @@ pub fn gateways_read(storage: &dyn Storage) -> ReadonlyBucket { const PREFIX_GATEWAYS_OWNERS: &[u8] = b"gateway-owners"; -pub fn gateways_owners(storage: &mut dyn Storage) -> Bucket { +pub fn gateways_owners(storage: &mut dyn Storage) -> Bucket { bucket(storage, PREFIX_GATEWAYS_OWNERS) } -pub fn gateways_owners_read(storage: &dyn Storage) -> ReadonlyBucket { +pub fn gateways_owners_read(storage: &dyn Storage) -> ReadonlyBucket { bucket_read(storage, PREFIX_GATEWAYS_OWNERS) } @@ -204,7 +204,7 @@ mod tests { // increases the reward appropriately if node exists let mixnode_bond = MixNodeBond { amount: coins(1000, DENOM), - owner: std::str::from_utf8(node_owner).unwrap().into(), + owner: Addr::unchecked(std::str::from_utf8(node_owner).unwrap()), mix_node: mix_node_fixture(), }; @@ -231,7 +231,7 @@ mod tests { let mixnode_bond = MixNodeBond { amount: coins(bond_value, DENOM), - owner: std::str::from_utf8(node_owner).unwrap().into(), + owner: Addr::unchecked(std::str::from_utf8(node_owner).unwrap()), mix_node: mix_node_fixture(), }; @@ -259,7 +259,7 @@ mod tests { // increases the reward appropriately if node exists let gateway_bond = GatewayBond { amount: coins(1000, DENOM), - owner: std::str::from_utf8(node_owner).unwrap().into(), + owner: Addr::unchecked(std::str::from_utf8(node_owner).unwrap()), gateway: gateway_fixture(), }; @@ -286,7 +286,7 @@ mod tests { let gateway_bond = GatewayBond { amount: coins(1000, DENOM), - owner: std::str::from_utf8(node_owner).unwrap().into(), + owner: Addr::unchecked(std::str::from_utf8(node_owner).unwrap()), gateway: gateway_fixture(), }; diff --git a/contracts/mixnet/src/support/tests.rs b/contracts/mixnet/src/support/tests.rs index af36f071e4..0a09fce08b 100644 --- a/contracts/mixnet/src/support/tests.rs +++ b/contracts/mixnet/src/support/tests.rs @@ -1,10 +1,10 @@ #[cfg(test)] pub mod helpers { use super::*; - use crate::contract::init; + use crate::contract::instantiate; use crate::contract::query; use crate::contract::DENOM; - use crate::msg::InitMsg; + use crate::msg::InstantiateMsg; use crate::msg::QueryMsg; use crate::transactions::{try_add_gateway, try_add_mixnode}; use cosmwasm_std::coins; @@ -15,8 +15,8 @@ pub mod helpers { use cosmwasm_std::testing::MockApi; use cosmwasm_std::testing::MockQuerier; use cosmwasm_std::testing::MockStorage; + use cosmwasm_std::Addr; use cosmwasm_std::Coin; - use cosmwasm_std::HumanAddr; use cosmwasm_std::OwnedDeps; use cosmwasm_std::{Empty, MemoryStorage}; use mixnet_contract::{ @@ -93,10 +93,10 @@ pub mod helpers { pub fn init_contract() -> OwnedDeps> { let mut deps = mock_dependencies(&[]); - let msg = InitMsg {}; + let msg = InstantiateMsg {}; let env = mock_env(); let info = mock_info("creator", &[]); - init(deps.as_mut(), env.clone(), info, msg).unwrap(); + instantiate(deps.as_mut(), env.clone(), info, msg).unwrap(); return deps; } @@ -120,7 +120,7 @@ pub mod helpers { "aaaa".to_string(), "0.10.0".to_string(), ); - MixNodeBond::new(coins(50, DENOM), HumanAddr::from("foo"), mix_node) + MixNodeBond::new(coins(50, DENOM), Addr::unchecked("foo"), mix_node) } pub fn gateway_fixture() -> Gateway { @@ -143,11 +143,11 @@ pub mod helpers { "identity".to_string(), "0.10.0".to_string(), ); - GatewayBond::new(coins(50, DENOM), HumanAddr::from("foo"), gateway) + GatewayBond::new(coins(50, DENOM), Addr::unchecked("foo"), gateway) } pub fn query_contract_balance( - address: HumanAddr, + address: Addr, deps: OwnedDeps, ) -> Vec { let querier = deps.as_ref().querier; diff --git a/contracts/mixnet/src/transactions.rs b/contracts/mixnet/src/transactions.rs index 4900702df2..ac7676841c 100644 --- a/contracts/mixnet/src/transactions.rs +++ b/contracts/mixnet/src/transactions.rs @@ -8,9 +8,7 @@ use crate::storage::{ mixnodes_read, read_gateway_epoch_reward_rate, read_mixnode_epoch_reward_rate, read_state_params, }; -use cosmwasm_std::{ - attr, BankMsg, Coin, Decimal, DepsMut, Env, HandleResponse, HumanAddr, MessageInfo, Uint128, -}; +use cosmwasm_std::{attr, BankMsg, Coin, Decimal, DepsMut, MessageInfo, Response, Uint128}; use mixnet_contract::{Gateway, GatewayBond, MixNode, MixNodeBond}; fn validate_mixnode_bond(bond: &[Coin], minimum_bond: Uint128) -> Result<(), ContractError> { @@ -43,17 +41,17 @@ pub(crate) fn try_add_mixnode( deps: DepsMut, info: MessageInfo, mix_node: MixNode, -) -> Result { +) -> Result { // if the client has an active bonded gateway, don't allow mixnode bonding if gateways_read(deps.storage) - .may_load(info.sender.as_ref())? + .may_load(info.sender.as_str().as_bytes())? .is_some() { return Err(ContractError::AlreadyOwnsGateway); } let minimum_bond = read_state_params(deps.storage).minimum_mixnode_bond; - validate_mixnode_bond(&info.sent_funds, minimum_bond)?; + validate_mixnode_bond(&info.funds, minimum_bond)?; // check if this node wasn't already claimed by somebody else let mut was_present = false; @@ -68,9 +66,9 @@ pub(crate) fn try_add_mixnode( was_present = true } - let bond = MixNodeBond::new(info.sent_funds, info.sender.clone(), mix_node); + let bond = MixNodeBond::new(info.funds, info.sender.clone(), mix_node); - let sender_bytes = info.sender.as_bytes(); + let sender_bytes = info.sender.as_str().as_bytes(); let attributes = vec![attr("overwritten", was_present)]; // TODO: now this can be potentially problematic. What if the first call doesn't fail but the second one does? @@ -78,8 +76,9 @@ pub(crate) fn try_add_mixnode( mixnodes(deps.storage).save(sender_bytes, &bond)?; mixnodes_owners(deps.storage).save(bond.mix_node.identity_key.as_bytes(), &info.sender)?; - Ok(HandleResponse { - messages: vec![], + Ok(Response { + submessages: Vec::new(), + messages: Vec::new(), attributes, data: None, }) @@ -88,30 +87,31 @@ pub(crate) fn try_add_mixnode( pub(crate) fn try_remove_mixnode( deps: DepsMut, info: MessageInfo, - env: Env, -) -> Result { +) -> Result { + let sender_bytes = info.sender.as_str().as_bytes(); + // find the bond, return ContractError::MixNodeBondNotFound if it doesn't exist let mixnode_bond = mixnodes_read(deps.storage) - .may_load(info.sender.as_bytes())? + .may_load(sender_bytes)? .ok_or(ContractError::MixNodeBondNotFound {})?; // send bonded funds back to the bond owner let messages = vec![BankMsg::Send { - from_address: env.contract.address, - to_address: info.sender.clone(), + to_address: info.sender.as_str().to_owned(), amount: mixnode_bond.amount().to_vec(), } .into()]; // remove the bond from the list of bonded mixnodes - mixnodes(deps.storage).remove(info.sender.as_bytes()); + mixnodes(deps.storage).remove(sender_bytes); // remove the node ownership mixnodes_owners(deps.storage).remove(mixnode_bond.mix_node.identity_key.as_bytes()); // log our actions let attributes = vec![attr("action", "unbond"), attr("mixnode_bond", mixnode_bond)]; - Ok(HandleResponse { + Ok(Response { + submessages: Vec::new(), messages, attributes, data: None, @@ -148,17 +148,17 @@ pub(crate) fn try_add_gateway( deps: DepsMut, info: MessageInfo, gateway: Gateway, -) -> Result { +) -> Result { // if the client has an active bonded mixnode, don't allow gateway bonding if mixnodes_read(deps.storage) - .may_load(info.sender.as_ref())? + .may_load(info.sender.as_str().as_bytes())? .is_some() { return Err(ContractError::AlreadyOwnsMixnode); } let minimum_bond = read_state_params(deps.storage).minimum_gateway_bond; - validate_gateway_bond(&info.sent_funds, minimum_bond)?; + validate_gateway_bond(&info.funds, minimum_bond)?; // check if this node wasn't already claimed by somebody else let mut was_present = false; @@ -173,9 +173,9 @@ pub(crate) fn try_add_gateway( was_present = true; } - let bond = GatewayBond::new(info.sent_funds, info.sender.clone(), gateway); + let bond = GatewayBond::new(info.funds, info.sender.clone(), gateway); - let sender_bytes = info.sender.as_bytes(); + let sender_bytes = info.sender.as_str().as_bytes(); let attributes = vec![attr("overwritten", was_present)]; // TODO: now this can be potentially problematic. What if the first call doesn't fail but the second one does? @@ -183,8 +183,9 @@ pub(crate) fn try_add_gateway( gateways(deps.storage).save(sender_bytes, &bond)?; gateways_owners(deps.storage).save(bond.gateway.identity_key.as_bytes(), &info.sender)?; - Ok(HandleResponse { - messages: vec![], + Ok(Response { + submessages: Vec::new(), + messages: Vec::new(), attributes, data: None, }) @@ -193,9 +194,8 @@ pub(crate) fn try_add_gateway( pub(crate) fn try_remove_gateway( deps: DepsMut, info: MessageInfo, - env: Env, -) -> Result { - let sender_bytes = info.sender.as_bytes(); +) -> Result { + let sender_bytes = info.sender.as_str().as_bytes(); // find the bond, return ContractError::GatewayBondNotFound if it doesn't exist let gateway_bond = match gateways_read(deps.storage).may_load(sender_bytes)? { @@ -209,8 +209,7 @@ pub(crate) fn try_remove_gateway( // send bonded funds back to the bond owner let messages = vec![BankMsg::Send { - from_address: env.contract.address, - to_address: info.sender.clone(), + to_address: info.sender.as_str().to_owned(), amount: gateway_bond.amount().to_vec(), } .into()]; @@ -227,7 +226,8 @@ pub(crate) fn try_remove_gateway( attr("gateway_bond", gateway_bond), ]; - Ok(HandleResponse { + Ok(Response { + submessages: Vec::new(), messages, attributes, data: None, @@ -238,7 +238,7 @@ pub(crate) fn try_update_state_params( deps: DepsMut, info: MessageInfo, params: StateParams, -) -> Result { +) -> Result { // note: In any other case, I wouldn't have attempted to unwrap this result, but in here // if we fail to load the stored state we would already be in the undefined behaviour land, // so we better just blow up immediately. @@ -279,36 +279,43 @@ pub(crate) fn try_update_state_params( config(deps.storage).save(&state)?; - Ok(HandleResponse::default()) + Ok(Response::default()) } pub(crate) fn try_reward_mixnode( deps: DepsMut, info: MessageInfo, - node_owner: HumanAddr, + node_owner: String, uptime: u32, -) -> Result { +) -> Result { let state = config_read(deps.storage).load().unwrap(); // check if this is executed by the monitor, if not reject the transaction if info.sender != state.network_monitor_address { return Err(ContractError::Unauthorized); } + // in theory network monitor should never send untrusted data, but validating it regardless + // wouldn't hurt... + let validated_address = deps.api.addr_validate(&node_owner)?; let reward = read_mixnode_epoch_reward_rate(deps.storage); let scaled_reward = scale_reward_by_uptime(reward, uptime)?; - increase_mixnode_bond(deps.storage, node_owner.as_bytes(), scaled_reward)?; + increase_mixnode_bond( + deps.storage, + validated_address.as_str().as_bytes(), + scaled_reward, + )?; - Ok(HandleResponse::default()) + Ok(Response::default()) } pub(crate) fn try_reward_gateway( deps: DepsMut, info: MessageInfo, - gateway_owner: HumanAddr, + gateway_owner: String, uptime: u32, -) -> Result { +) -> Result { let state = config_read(deps.storage).load().unwrap(); // check if this is executed by the owner, if not reject the transaction @@ -316,29 +323,37 @@ pub(crate) fn try_reward_gateway( return Err(ContractError::Unauthorized); } + // in theory network monitor should never send untrusted data, but validating it regardless + // wouldn't hurt... + let validated_address = deps.api.addr_validate(&gateway_owner)?; + let reward = read_gateway_epoch_reward_rate(deps.storage); let scaled_reward = scale_reward_by_uptime(reward, uptime)?; - increase_gateway_bond(deps.storage, gateway_owner.as_bytes(), scaled_reward)?; + increase_gateway_bond( + deps.storage, + validated_address.as_str().as_bytes(), + scaled_reward, + )?; - Ok(HandleResponse::default()) + Ok(Response::default()) } #[cfg(test)] pub mod tests { use super::*; use crate::contract::{ - handle, init, query, INITIAL_DEFAULT_EPOCH_LENGTH, INITIAL_GATEWAY_BOND, + execute, instantiate, query, INITIAL_DEFAULT_EPOCH_LENGTH, INITIAL_GATEWAY_BOND, INITIAL_GATEWAY_BOND_REWARD_RATE, INITIAL_MIXNODE_BOND, INITIAL_MIXNODE_BOND_REWARD_RATE, }; use crate::helpers::calculate_epoch_reward_rate; - use crate::msg::{HandleMsg, InitMsg, QueryMsg}; + use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg}; use crate::state::StateParams; use crate::storage::{read_gateway_bond, read_gateway_epoch_reward_rate, read_mixnode_bond}; use crate::support::tests::helpers; use crate::support::tests::helpers::{gateway_fixture, mix_node_fixture}; use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; - use cosmwasm_std::{coins, from_binary, Uint128}; + use cosmwasm_std::{coins, from_binary, Addr, Uint128}; use mixnet_contract::{PagedGatewayResponse, PagedResponse}; fn good_mixnode_bond() -> Vec { @@ -356,7 +371,7 @@ pub mod tests { // you must send at least 100 coins... let mut bond = good_mixnode_bond(); - bond[0].amount = (INITIAL_MIXNODE_BOND - Uint128(1)).unwrap(); + bond[0].amount = INITIAL_MIXNODE_BOND.checked_sub(Uint128(1)).unwrap(); let result = validate_mixnode_bond(&bond, INITIAL_MIXNODE_BOND); assert_eq!( result, @@ -391,12 +406,12 @@ pub mod tests { // if we don't send enough funds let insufficient_bond = Into::::into(INITIAL_MIXNODE_BOND) - 1; let info = mock_info("anyone", &coins(insufficient_bond, DENOM)); - let msg = HandleMsg::BondMixnode { + let msg = ExecuteMsg::BondMixnode { mix_node: helpers::mix_node_fixture(), }; // we are informed that we didn't send enough funds - let result = handle(deps.as_mut(), mock_env(), info, msg); + let result = execute(deps.as_mut(), mock_env(), info, msg); assert_eq!( result, Err(ContractError::InsufficientMixNodeBond { @@ -420,7 +435,7 @@ pub mod tests { // if we send enough funds let info = mock_info("anyone", &coins(1000_000000, DENOM)); - let msg = HandleMsg::BondMixnode { + let msg = ExecuteMsg::BondMixnode { mix_node: MixNode { identity_key: "anyonesmixnode".into(), ..helpers::mix_node_fixture() @@ -428,7 +443,7 @@ pub mod tests { }; // we get back a message telling us everything was OK - let handle_response = handle(deps.as_mut(), mock_env(), info, msg); + let handle_response = execute(deps.as_mut(), mock_env(), info, msg); assert!(handle_response.is_ok()); // we can query topology and the new node is there @@ -453,18 +468,18 @@ pub mod tests { // if there was already a mixnode bonded by particular user let info = mock_info("foomper", &good_mixnode_bond()); - let msg = HandleMsg::BondMixnode { + let msg = ExecuteMsg::BondMixnode { mix_node: MixNode { identity_key: "foompermixnode".into(), ..helpers::mix_node_fixture() }, }; - let handle_response = handle(deps.as_mut(), mock_env(), info, msg).unwrap(); + let handle_response = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(handle_response.attributes[0], attr("overwritten", false)); let info = mock_info("foomper", &good_mixnode_bond()); - let msg = HandleMsg::BondMixnode { + let msg = ExecuteMsg::BondMixnode { mix_node: MixNode { identity_key: "foompermixnode".into(), ..helpers::mix_node_fixture() @@ -472,33 +487,33 @@ pub mod tests { }; // we get a log message about it (TODO: does it get back to the user?) - let handle_response = handle(deps.as_mut(), mock_env(), info, msg).unwrap(); + let handle_response = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(handle_response.attributes[0], attr("overwritten", true)); // bonding fails if the user already owns a gateway let info = mock_info("gateway-owner", &good_gateway_bond()); - let msg = HandleMsg::BondGateway { + let msg = ExecuteMsg::BondGateway { gateway: helpers::gateway_fixture(), }; - handle(deps.as_mut(), mock_env(), info, msg).unwrap(); + execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let info = mock_info("gateway-owner", &good_mixnode_bond()); - let msg = HandleMsg::BondMixnode { + let msg = ExecuteMsg::BondMixnode { mix_node: helpers::mix_node_fixture(), }; - let handle_response = handle(deps.as_mut(), mock_env(), info, msg); + let handle_response = execute(deps.as_mut(), mock_env(), info, msg); assert_eq!(handle_response, Err(ContractError::AlreadyOwnsGateway)); // but after he unbonds it, it's all fine again let info = mock_info("gateway-owner", &[]); - let msg = HandleMsg::UnbondGateway {}; - handle(deps.as_mut(), mock_env(), info, msg).unwrap(); + let msg = ExecuteMsg::UnbondGateway {}; + execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let info = mock_info("gateway-owner", &good_mixnode_bond()); - let msg = HandleMsg::BondMixnode { + let msg = ExecuteMsg::BondMixnode { mix_node: helpers::mix_node_fixture(), }; - let handle_response = handle(deps.as_mut(), mock_env(), info, msg); + let handle_response = execute(deps.as_mut(), mock_env(), info, msg); assert!(handle_response.is_ok()); // adding another node from another account, but with the same IP, should fail (or we would have a weird state). Is that right? Think about this, not sure yet. @@ -510,7 +525,7 @@ pub mod tests { let mut deps = helpers::init_contract(); let info = mock_info("mix-owner", &good_mixnode_bond()); - let msg = HandleMsg::BondMixnode { + let msg = ExecuteMsg::BondMixnode { mix_node: MixNode { identity_key: "myAwesomeMixnode".to_string(), ..helpers::mix_node_fixture() @@ -524,11 +539,11 @@ pub mod tests { .is_none()); // it's all fine, owner is saved - let handle_response = handle(deps.as_mut(), mock_env(), info, msg); + let handle_response = execute(deps.as_mut(), mock_env(), info, msg); assert!(handle_response.is_ok()); assert_eq!( - HumanAddr::from("mix-owner"), + Addr::unchecked("mix-owner"), mixnodes_owners_read(deps.as_ref().storage) .load("myAwesomeMixnode".as_bytes()) .unwrap() @@ -540,35 +555,35 @@ pub mod tests { let mut deps = helpers::init_contract(); let info = mock_info("mix-owner", &good_mixnode_bond()); - let msg = HandleMsg::BondMixnode { + let msg = ExecuteMsg::BondMixnode { mix_node: MixNode { identity_key: "myAwesomeMixnode".to_string(), ..helpers::mix_node_fixture() }, }; - handle(deps.as_mut(), mock_env(), info, msg).unwrap(); + execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // request fails giving the existing owner address in the message let info = mock_info("mix-owner-pretender", &good_mixnode_bond()); - let msg = HandleMsg::BondMixnode { + let msg = ExecuteMsg::BondMixnode { mix_node: MixNode { identity_key: "myAwesomeMixnode".to_string(), ..helpers::mix_node_fixture() }, }; - let handle_response = handle(deps.as_mut(), mock_env(), info, msg); + let handle_response = execute(deps.as_mut(), mock_env(), info, msg); assert_eq!( Err(ContractError::DuplicateMixnode { - owner: "mix-owner".into() + owner: Addr::unchecked("mix-owner") }), handle_response ); // owner is not changed assert_eq!( - HumanAddr::from("mix-owner"), + Addr::unchecked("mix-owner"), mixnodes_owners_read(deps.as_ref().storage) .load("myAwesomeMixnode".as_bytes()) .unwrap() @@ -580,7 +595,7 @@ pub mod tests { let mut deps = helpers::init_contract(); let info = mock_info("mix-owner", &good_mixnode_bond()); - let msg = HandleMsg::BondMixnode { + let msg = ExecuteMsg::BondMixnode { mix_node: MixNode { identity_key: "myAwesomeMixnode".to_string(), host: "1.1.1.1:1789".into(), @@ -588,10 +603,10 @@ pub mod tests { }, }; - handle(deps.as_mut(), mock_env(), info, msg).unwrap(); + execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let info = mock_info("mix-owner", &good_mixnode_bond()); - let msg = HandleMsg::BondMixnode { + let msg = ExecuteMsg::BondMixnode { mix_node: MixNode { identity_key: "myAwesomeMixnode".to_string(), host: "2.2.2.2:1789".into(), @@ -599,7 +614,7 @@ pub mod tests { }, }; - assert!(handle(deps.as_mut(), mock_env(), info, msg).is_ok()); + assert!(execute(deps.as_mut(), mock_env(), info, msg).is_ok()); // make sure the host information was updated assert_eq!( @@ -613,7 +628,7 @@ pub mod tests { // and nothing was changed regarding ownership assert_eq!( - HumanAddr::from("mix-owner"), + Addr::unchecked("mix-owner"), mixnodes_owners_read(deps.as_ref().storage) .load("myAwesomeMixnode".as_bytes()) .unwrap() @@ -624,14 +639,14 @@ pub mod tests { fn mixnode_remove() { let env = mock_env(); let mut deps = mock_dependencies(&[]); - let msg = InitMsg {}; + let msg = InstantiateMsg {}; let info = mock_info("creator", &[]); - init(deps.as_mut(), env.clone(), info, msg).unwrap(); + instantiate(deps.as_mut(), env.clone(), info, msg).unwrap(); // try un-registering when no nodes exist yet let info = mock_info("anyone", &coins(999_9999, DENOM)); - let msg = HandleMsg::UnbondMixnode {}; - let result = handle(deps.as_mut(), mock_env(), info, msg); + let msg = ExecuteMsg::UnbondMixnode {}; + let result = execute(deps.as_mut(), mock_env(), info, msg); // we're told that there is no node for our address assert_eq!(result, Err(ContractError::MixNodeBondNotFound {})); @@ -641,8 +656,8 @@ pub mod tests { // attempt to un-register fred's node, which doesn't exist let info = mock_info("fred", &coins(999_9999, DENOM)); - let msg = HandleMsg::UnbondMixnode {}; - let result = handle(deps.as_mut(), mock_env(), info, msg); + let msg = ExecuteMsg::UnbondMixnode {}; + let result = execute(deps.as_mut(), mock_env(), info, msg); assert_eq!(result, Err(ContractError::MixNodeBondNotFound {})); // bob's node is still there @@ -658,7 +673,7 @@ pub mod tests { let page: PagedResponse = from_binary(&res).unwrap(); let first_node = &page.nodes[0]; assert_eq!(1, page.nodes.len()); - assert_eq!("bob", first_node.owner()); + assert_eq!(&Addr::unchecked("bob"), first_node.owner()); // add a node owned by fred let fred_bond = good_mixnode_bond(); @@ -669,8 +684,8 @@ pub mod tests { // un-register fred's node let info = mock_info("fred", &coins(999_9999, DENOM)); - let msg = HandleMsg::UnbondMixnode {}; - let remove_fred = handle(deps.as_mut(), mock_env(), info.clone(), msg).unwrap(); + let msg = ExecuteMsg::UnbondMixnode {}; + let remove_fred = execute(deps.as_mut(), mock_env(), info.clone(), msg).unwrap(); // we should see log messages come back showing an unbond message let expected_attributes = vec![ @@ -683,14 +698,14 @@ pub mod tests { // we should see a funds transfer from the contract back to fred let expected_messages = vec![BankMsg::Send { - from_address: env.contract.address, - to_address: info.sender, + to_address: info.sender.as_str().to_owned(), amount: fred_bond, } .into()]; // run the handler and check that we got back the correct results - let expected = HandleResponse { + let expected = Response { + submessages: Vec::new(), messages: expected_messages, attributes: expected_attributes, data: None, @@ -700,7 +715,7 @@ pub mod tests { // only 1 node now exists, owned by bob: let mix_node_bonds = helpers::get_mix_nodes(&mut deps); assert_eq!(1, mix_node_bonds.len()); - assert_eq!("bob", mix_node_bonds[0].owner()); + assert_eq!(&Addr::unchecked("bob"), mix_node_bonds[0].owner()); } #[test] @@ -708,25 +723,25 @@ pub mod tests { let mut deps = helpers::init_contract(); let info = mock_info("mix-owner", &good_mixnode_bond()); - let msg = HandleMsg::BondMixnode { + let msg = ExecuteMsg::BondMixnode { mix_node: MixNode { identity_key: "myAwesomeMixnode".to_string(), ..helpers::mix_node_fixture() }, }; - handle(deps.as_mut(), mock_env(), info, msg).unwrap(); + execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!( - HumanAddr::from("mix-owner"), + Addr::unchecked("mix-owner"), mixnodes_owners_read(deps.as_ref().storage) .load("myAwesomeMixnode".as_bytes()) .unwrap() ); let info = mock_info("mix-owner", &[]); - let msg = HandleMsg::UnbondMixnode {}; + let msg = ExecuteMsg::UnbondMixnode {}; - assert!(handle(deps.as_mut(), mock_env(), info, msg).is_ok()); + assert!(execute(deps.as_mut(), mock_env(), info, msg).is_ok()); assert!(mixnodes_owners_read(deps.as_ref().storage) .may_load("myAwesomeMixnode".as_bytes()) @@ -735,16 +750,16 @@ pub mod tests { // and since it's removed, it can be reclaimed let info = mock_info("mix-owner", &good_mixnode_bond()); - let msg = HandleMsg::BondMixnode { + let msg = ExecuteMsg::BondMixnode { mix_node: MixNode { identity_key: "myAwesomeMixnode".to_string(), ..helpers::mix_node_fixture() }, }; - assert!(handle(deps.as_mut(), mock_env(), info, msg).is_ok()); + assert!(execute(deps.as_mut(), mock_env(), info, msg).is_ok()); assert_eq!( - HumanAddr::from("mix-owner"), + Addr::unchecked("mix-owner"), mixnodes_owners_read(deps.as_ref().storage) .load("myAwesomeMixnode".as_bytes()) .unwrap() @@ -766,7 +781,7 @@ pub mod tests { // you must send at least 100 coins... let mut bond = good_gateway_bond(); - bond[0].amount = (INITIAL_GATEWAY_BOND - Uint128(1)).unwrap(); + bond[0].amount = INITIAL_GATEWAY_BOND.checked_sub(Uint128(1)).unwrap(); let result = validate_gateway_bond(&bond, INITIAL_GATEWAY_BOND); assert_eq!( result, @@ -801,12 +816,12 @@ pub mod tests { // if we fail validation (by say not sending enough funds let insufficient_bond = Into::::into(INITIAL_GATEWAY_BOND) - 1; let info = mock_info("anyone", &coins(insufficient_bond, DENOM)); - let msg = HandleMsg::BondGateway { + let msg = ExecuteMsg::BondGateway { gateway: helpers::gateway_fixture(), }; // we are informed that we didn't send enough funds - let result = handle(deps.as_mut(), mock_env(), info, msg); + let result = execute(deps.as_mut(), mock_env(), info, msg); assert_eq!( result, Err(ContractError::InsufficientGatewayBond { @@ -830,7 +845,7 @@ pub mod tests { // if we send enough funds let info = mock_info("anyone", &good_gateway_bond()); - let msg = HandleMsg::BondGateway { + let msg = ExecuteMsg::BondGateway { gateway: Gateway { identity_key: "anyonesgateway".into(), ..helpers::gateway_fixture() @@ -838,7 +853,7 @@ pub mod tests { }; // we get back a message telling us everything was OK - let handle_response = handle(deps.as_mut(), mock_env(), info, msg); + let handle_response = execute(deps.as_mut(), mock_env(), info, msg); assert!(handle_response.is_ok()); // we can query topology and the new node is there @@ -863,18 +878,18 @@ pub mod tests { // if there was already a gateway bonded by particular user let info = mock_info("foomper", &good_gateway_bond()); - let msg = HandleMsg::BondGateway { + let msg = ExecuteMsg::BondGateway { gateway: Gateway { identity_key: "foompersgateway".into(), ..helpers::gateway_fixture() }, }; - let handle_response = handle(deps.as_mut(), mock_env(), info, msg).unwrap(); + let handle_response = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(handle_response.attributes[0], attr("overwritten", false)); let info = mock_info("foomper", &good_gateway_bond()); - let msg = HandleMsg::BondGateway { + let msg = ExecuteMsg::BondGateway { gateway: Gateway { identity_key: "foompersgateway".into(), ..helpers::gateway_fixture() @@ -882,33 +897,33 @@ pub mod tests { }; // we get a log message about it (TODO: does it get back to the user?) - let handle_response = handle(deps.as_mut(), mock_env(), info, msg).unwrap(); + let handle_response = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(handle_response.attributes[0], attr("overwritten", true)); // bonding fails if the user already owns a mixnode let info = mock_info("mixnode-owner", &good_mixnode_bond()); - let msg = HandleMsg::BondMixnode { + let msg = ExecuteMsg::BondMixnode { mix_node: helpers::mix_node_fixture(), }; - handle(deps.as_mut(), mock_env(), info, msg).unwrap(); + execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let info = mock_info("mixnode-owner", &good_gateway_bond()); - let msg = HandleMsg::BondGateway { + let msg = ExecuteMsg::BondGateway { gateway: helpers::gateway_fixture(), }; - let handle_response = handle(deps.as_mut(), mock_env(), info, msg); + let handle_response = execute(deps.as_mut(), mock_env(), info, msg); assert_eq!(handle_response, Err(ContractError::AlreadyOwnsMixnode)); // but after he unbonds it, it's all fine again let info = mock_info("mixnode-owner", &[]); - let msg = HandleMsg::UnbondMixnode {}; - handle(deps.as_mut(), mock_env(), info, msg).unwrap(); + let msg = ExecuteMsg::UnbondMixnode {}; + execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let info = mock_info("mixnode-owner", &good_gateway_bond()); - let msg = HandleMsg::BondGateway { + let msg = ExecuteMsg::BondGateway { gateway: helpers::gateway_fixture(), }; - let handle_response = handle(deps.as_mut(), mock_env(), info, msg); + let handle_response = execute(deps.as_mut(), mock_env(), info, msg); assert!(handle_response.is_ok()); // adding another node from another account, but with the same IP, should fail (or we would have a weird state). @@ -920,7 +935,7 @@ pub mod tests { let mut deps = helpers::init_contract(); let info = mock_info("gateway-owner", &good_gateway_bond()); - let msg = HandleMsg::BondGateway { + let msg = ExecuteMsg::BondGateway { gateway: Gateway { identity_key: "myAwesomeGateway".to_string(), ..helpers::gateway_fixture() @@ -934,11 +949,11 @@ pub mod tests { .is_none()); // it's all fine, owner is saved - let handle_response = handle(deps.as_mut(), mock_env(), info, msg); + let handle_response = execute(deps.as_mut(), mock_env(), info, msg); assert!(handle_response.is_ok()); assert_eq!( - HumanAddr::from("gateway-owner"), + Addr::unchecked("gateway-owner"), gateways_owners_read(deps.as_ref().storage) .load("myAwesomeGateway".as_bytes()) .unwrap() @@ -950,35 +965,35 @@ pub mod tests { let mut deps = helpers::init_contract(); let info = mock_info("gateway-owner", &good_gateway_bond()); - let msg = HandleMsg::BondGateway { + let msg = ExecuteMsg::BondGateway { gateway: Gateway { identity_key: "myAwesomeGateway".to_string(), ..helpers::gateway_fixture() }, }; - handle(deps.as_mut(), mock_env(), info, msg).unwrap(); + execute(deps.as_mut(), mock_env(), info, msg).unwrap(); // request fails giving the existing owner address in the message let info = mock_info("gateway-owner-pretender", &good_gateway_bond()); - let msg = HandleMsg::BondGateway { + let msg = ExecuteMsg::BondGateway { gateway: Gateway { identity_key: "myAwesomeGateway".to_string(), ..helpers::gateway_fixture() }, }; - let handle_response = handle(deps.as_mut(), mock_env(), info, msg); + let handle_response = execute(deps.as_mut(), mock_env(), info, msg); assert_eq!( Err(ContractError::DuplicateGateway { - owner: "gateway-owner".into() + owner: Addr::unchecked("gateway-owner") }), handle_response ); // owner is not changed assert_eq!( - HumanAddr::from("gateway-owner"), + Addr::unchecked("gateway-owner"), gateways_owners_read(deps.as_ref().storage) .load("myAwesomeGateway".as_bytes()) .unwrap() @@ -990,7 +1005,7 @@ pub mod tests { let mut deps = helpers::init_contract(); let info = mock_info("gateway-owner", &good_gateway_bond()); - let msg = HandleMsg::BondGateway { + let msg = ExecuteMsg::BondGateway { gateway: Gateway { identity_key: "myAwesomeGateway".to_string(), mix_host: "1.1.1.1:1789".into(), @@ -998,10 +1013,10 @@ pub mod tests { }, }; - handle(deps.as_mut(), mock_env(), info, msg).unwrap(); + execute(deps.as_mut(), mock_env(), info, msg).unwrap(); let info = mock_info("gateway-owner", &good_gateway_bond()); - let msg = HandleMsg::BondGateway { + let msg = ExecuteMsg::BondGateway { gateway: Gateway { identity_key: "myAwesomeGateway".to_string(), mix_host: "2.2.2.2:1789".into(), @@ -1009,7 +1024,7 @@ pub mod tests { }, }; - assert!(handle(deps.as_mut(), mock_env(), info, msg).is_ok()); + assert!(execute(deps.as_mut(), mock_env(), info, msg).is_ok()); // make sure the host information was updated assert_eq!( @@ -1023,7 +1038,7 @@ pub mod tests { // and nothing was changed regarding ownership assert_eq!( - HumanAddr::from("gateway-owner"), + Addr::unchecked("gateway-owner"), gateways_owners_read(deps.as_ref().storage) .load("myAwesomeGateway".as_bytes()) .unwrap() @@ -1034,20 +1049,20 @@ pub mod tests { fn gateway_remove() { let env = mock_env(); let mut deps = mock_dependencies(&[]); - let msg = InitMsg {}; + let msg = InstantiateMsg {}; let info = mock_info("creator", &[]); - init(deps.as_mut(), env.clone(), info, msg).unwrap(); + instantiate(deps.as_mut(), env.clone(), info, msg).unwrap(); // try unbond when no nodes exist yet let info = mock_info("anyone", &[]); - let msg = HandleMsg::UnbondGateway {}; - let result = handle(deps.as_mut(), mock_env(), info, msg); + let msg = ExecuteMsg::UnbondGateway {}; + let result = execute(deps.as_mut(), mock_env(), info, msg); // we're told that there is no node for our address assert_eq!( result, Err(ContractError::GatewayBondNotFound { - account: "anyone".into() + account: Addr::unchecked("anyone") }) ); @@ -1056,12 +1071,12 @@ pub mod tests { // attempt to unbond fred's node, which doesn't exist let info = mock_info("fred", &[]); - let msg = HandleMsg::UnbondGateway {}; - let result = handle(deps.as_mut(), mock_env(), info, msg); + let msg = ExecuteMsg::UnbondGateway {}; + let result = execute(deps.as_mut(), mock_env(), info, msg); assert_eq!( result, Err(ContractError::GatewayBondNotFound { - account: "fred".into() + account: Addr::unchecked("fred") }) ); @@ -1070,7 +1085,7 @@ pub mod tests { assert_eq!(1, nodes.len()); let first_node = &nodes[0]; - assert_eq!("bob", first_node.owner()); + assert_eq!(&Addr::unchecked("bob"), first_node.owner()); // add a node owned by fred let fred_bond = good_gateway_bond(); @@ -1081,8 +1096,8 @@ pub mod tests { // unbond fred's node let info = mock_info("fred", &[]); - let msg = HandleMsg::UnbondGateway {}; - let remove_fred = handle(deps.as_mut(), mock_env(), info.clone(), msg).unwrap(); + let msg = ExecuteMsg::UnbondGateway {}; + let remove_fred = execute(deps.as_mut(), mock_env(), info.clone(), msg).unwrap(); // we should see log messages come back showing an unbond message let expected_attributes = vec![ @@ -1096,14 +1111,14 @@ pub mod tests { // we should see a funds transfer from the contract back to fred let expected_messages = vec![BankMsg::Send { - from_address: env.contract.address, - to_address: info.sender, + to_address: info.sender.as_str().to_owned(), amount: fred_bond, } .into()]; // run the handler and check that we got back the correct results - let expected = HandleResponse { + let expected = Response { + submessages: Vec::new(), messages: expected_messages, attributes: expected_attributes, data: None, @@ -1113,7 +1128,7 @@ pub mod tests { // only 1 node now exists, owned by bob: let gateway_bonds = helpers::get_gateways(&mut deps); assert_eq!(1, gateway_bonds.len()); - assert_eq!("bob", gateway_bonds[0].owner()); + assert_eq!(&Addr::unchecked("bob"), gateway_bonds[0].owner()); } #[test] @@ -1121,25 +1136,25 @@ pub mod tests { let mut deps = helpers::init_contract(); let info = mock_info("gateway-owner", &good_mixnode_bond()); - let msg = HandleMsg::BondGateway { + let msg = ExecuteMsg::BondGateway { gateway: Gateway { identity_key: "myAwesomeGateway".to_string(), ..helpers::gateway_fixture() }, }; - handle(deps.as_mut(), mock_env(), info, msg).unwrap(); + execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!( - HumanAddr::from("gateway-owner"), + Addr::unchecked("gateway-owner"), gateways_owners_read(deps.as_ref().storage) .load("myAwesomeGateway".as_bytes()) .unwrap() ); let info = mock_info("gateway-owner", &[]); - let msg = HandleMsg::UnbondGateway {}; + let msg = ExecuteMsg::UnbondGateway {}; - assert!(handle(deps.as_mut(), mock_env(), info, msg).is_ok()); + assert!(execute(deps.as_mut(), mock_env(), info, msg).is_ok()); assert!(gateways_owners_read(deps.as_ref().storage) .may_load("myAwesomeGateway".as_bytes()) @@ -1148,16 +1163,16 @@ pub mod tests { // and since it's removed, it can be reclaimed let info = mock_info("gateway-owner", &good_mixnode_bond()); - let msg = HandleMsg::BondGateway { + let msg = ExecuteMsg::BondGateway { gateway: Gateway { identity_key: "myAwesomeGateway".to_string(), ..helpers::gateway_fixture() }, }; - assert!(handle(deps.as_mut(), mock_env(), info, msg).is_ok()); + assert!(execute(deps.as_mut(), mock_env(), info, msg).is_ok()); assert_eq!( - HumanAddr::from("gateway-owner"), + Addr::unchecked("gateway-owner"), gateways_owners_read(deps.as_ref().storage) .load("myAwesomeGateway".as_bytes()) .unwrap() @@ -1185,7 +1200,7 @@ pub mod tests { // but works fine from the creator account let info = mock_info("creator", &[]); let res = try_update_state_params(deps.as_mut(), info, new_params.clone()); - assert_eq!(res, Ok(HandleResponse::default())); + assert_eq!(res, Ok(Response::default())); // and the state is actually updated let current_state = config_read(deps.as_ref().storage).load().unwrap(); @@ -1289,14 +1304,14 @@ pub mod tests { assert_eq!(res, Err(ContractError::Unauthorized)); // errors out if the target owner hasn't bound any mixnodes - let info = mock_info(network_monitor_address.clone(), &[]); + let info = mock_info(network_monitor_address.as_str(), &[]); let res = try_reward_mixnode(deps.as_mut(), info, "node-owner".into(), 100); assert!(res.is_err()); let initial_bond = 100_000000; let mixnode_bond = MixNodeBond { amount: coins(initial_bond, DENOM), - owner: "node-owner".into(), + owner: Addr::unchecked("node-owner"), mix_node: mix_node_fixture(), }; @@ -1310,7 +1325,7 @@ pub mod tests { // if node was 100% up, it will get full epoch reward let expected_bond = Uint128(initial_bond) * reward + Uint128(initial_bond); - let info = mock_info(network_monitor_address.clone(), &[]); + let info = mock_info(network_monitor_address.as_str(), &[]); try_reward_mixnode(deps.as_mut(), info, "node-owner".into(), 100).unwrap(); assert_eq!( @@ -1322,7 +1337,7 @@ pub mod tests { let scaled_reward = scale_reward_by_uptime(reward, 20).unwrap(); let expected_bond = expected_bond * scaled_reward + expected_bond; - let info = mock_info(network_monitor_address, &[]); + let info = mock_info(network_monitor_address.as_str(), &[]); try_reward_mixnode(deps.as_mut(), info, "node-owner".into(), 20).unwrap(); assert_eq!( @@ -1343,14 +1358,14 @@ pub mod tests { assert_eq!(res, Err(ContractError::Unauthorized)); // errors out if the target owner hasn't bound any mixnodes - let info = mock_info(network_monitor_address.clone(), &[]); + let info = mock_info(network_monitor_address.as_str(), &[]); let res = try_reward_gateway(deps.as_mut(), info, "node-owner".into(), 100); assert!(res.is_err()); let initial_bond = 100_000000; let gateway_bond = GatewayBond { amount: coins(initial_bond, DENOM), - owner: "node-owner".into(), + owner: Addr::unchecked("node-owner"), gateway: gateway_fixture(), }; @@ -1364,7 +1379,7 @@ pub mod tests { // if node was 100% up, it will get full epoch reward let expected_bond = Uint128(initial_bond) * reward + Uint128(initial_bond); - let info = mock_info(network_monitor_address.clone(), &[]); + let info = mock_info(network_monitor_address.as_str(), &[]); try_reward_gateway(deps.as_mut(), info, "node-owner".into(), 100).unwrap(); assert_eq!( @@ -1376,7 +1391,7 @@ pub mod tests { let scaled_reward = scale_reward_by_uptime(reward, 20).unwrap(); let expected_bond = expected_bond * scaled_reward + expected_bond; - let info = mock_info(network_monitor_address, &[]); + let info = mock_info(network_monitor_address.as_str(), &[]); try_reward_gateway(deps.as_mut(), info, "node-owner".into(), 20).unwrap(); assert_eq!( From da339a83cdb4e564b11fa369b2534611b27886b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Stuczy=C5=84ski?= Date: Thu, 27 May 2021 11:29:31 +0100 Subject: [PATCH 2/7] Updated the rest of the codebase --- common/client-libs/validator-client/src/lib.rs | 6 +++--- common/client-libs/validator-client/src/models.rs | 6 +++--- common/topology/src/gateway.rs | 2 +- common/topology/src/mix.rs | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/common/client-libs/validator-client/src/lib.rs b/common/client-libs/validator-client/src/lib.rs index 4cd2c4b163..08d8845b48 100644 --- a/common/client-libs/validator-client/src/lib.rs +++ b/common/client-libs/validator-client/src/lib.rs @@ -4,7 +4,7 @@ use crate::models::{QueryRequest, QueryResponse}; use crate::ValidatorClientError::ValidatorError; use core::fmt::{self, Display, Formatter}; -use mixnet_contract::{GatewayBond, HumanAddr, MixNodeBond, PagedGatewayResponse, PagedResponse}; +use mixnet_contract::{Addr, GatewayBond, MixNodeBond, PagedGatewayResponse, PagedResponse}; use rand::seq::SliceRandom; use rand::thread_rng; use serde::Deserialize; @@ -175,7 +175,7 @@ impl Client { async fn get_mix_nodes_paged( &mut self, - start_after: Option, + start_after: Option, ) -> Result { let query_content_json = serde_json::to_string(&QueryRequest::GetMixNodes { limit: self.config.mixnode_page_limit, @@ -208,7 +208,7 @@ impl Client { async fn get_gateways_paged( &mut self, - start_after: Option, + start_after: Option, ) -> Result { let query_content_json = serde_json::to_string(&QueryRequest::GetGateways { limit: self.config.gateway_page_limit, diff --git a/common/client-libs/validator-client/src/models.rs b/common/client-libs/validator-client/src/models.rs index 1b4089b1ba..5f75b77c81 100644 --- a/common/client-libs/validator-client/src/models.rs +++ b/common/client-libs/validator-client/src/models.rs @@ -3,7 +3,7 @@ use crate::serde_helpers::{de_i64_from_str, de_paged_query_response_from_str}; use core::fmt::{self, Display, Formatter}; -use mixnet_contract::HumanAddr; +use mixnet_contract::Addr; use serde::{Deserialize, Serialize}; // TODO: this is a duplicate code but it really does not feel @@ -14,10 +14,10 @@ use serde::{Deserialize, Serialize}; pub(super) enum QueryRequest { GetMixNodes { limit: Option, - start_after: Option, + start_after: Option, }, GetGateways { - start_after: Option, + start_after: Option, limit: Option, }, } diff --git a/common/topology/src/gateway.rs b/common/topology/src/gateway.rs index f358f90d49..4c62db62f7 100644 --- a/common/topology/src/gateway.rs +++ b/common/topology/src/gateway.rs @@ -121,7 +121,7 @@ impl<'a> TryFrom<&'a GatewayBond> for Node { return Err(GatewayConversionError::InvalidStake); } Ok(Node { - owner: bond.owner.0.clone(), + owner: bond.owner.as_str().to_owned(), stake: bond .amount .first() diff --git a/common/topology/src/mix.rs b/common/topology/src/mix.rs index 058794a176..a97e342745 100644 --- a/common/topology/src/mix.rs +++ b/common/topology/src/mix.rs @@ -113,7 +113,7 @@ impl<'a> TryFrom<&'a MixNodeBond> for Node { return Err(MixnodeConversionError::InvalidStake); } Ok(Node { - owner: bond.owner.0.clone(), + owner: bond.owner.as_str().to_owned(), stake: bond .amount .first() From 27e704ab8073a29a81a57d9e37b5915b60743b11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Stuczy=C5=84ski?= Date: Thu, 27 May 2021 11:42:11 +0100 Subject: [PATCH 3/7] Reordered imports --- common/mixnet-contract/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/mixnet-contract/src/lib.rs b/common/mixnet-contract/src/lib.rs index cd1dedee33..b5c9a15ced 100644 --- a/common/mixnet-contract/src/lib.rs +++ b/common/mixnet-contract/src/lib.rs @@ -1,6 +1,6 @@ mod gateway; mod mixnode; -pub use cosmwasm_std::{Coin, Addr}; +pub use cosmwasm_std::{Addr, Coin}; pub use gateway::{Gateway, GatewayBond, GatewayOwnershipResponse, PagedGatewayResponse}; pub use mixnode::{MixNode, MixNodeBond, MixOwnershipResponse, PagedResponse}; From 50fbe55be9b1868d8f6dc3f26ee4fc9366bba177 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Stuczy=C5=84ski?= Date: Fri, 18 Jun 2021 12:01:29 +0100 Subject: [PATCH 4/7] Missing imports --- common/client-libs/validator-client/src/lib.rs | 4 +++- common/client-libs/validator-client/src/models.rs | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/common/client-libs/validator-client/src/lib.rs b/common/client-libs/validator-client/src/lib.rs index 7cb1394ac2..11ec497274 100644 --- a/common/client-libs/validator-client/src/lib.rs +++ b/common/client-libs/validator-client/src/lib.rs @@ -4,7 +4,9 @@ use crate::models::{QueryRequest, QueryResponse}; use crate::ValidatorClientError::ValidatorError; use core::fmt::{self, Display, Formatter}; -use mixnet_contract::{Addr, GatewayBond, IdentityKey, LayerDistribution, MixNodeBond, PagedGatewayResponse, PagedResponse}; +use mixnet_contract::{ + GatewayBond, IdentityKey, LayerDistribution, MixNodeBond, PagedGatewayResponse, PagedResponse, +}; use rand::seq::SliceRandom; use rand::thread_rng; use serde::Deserialize; diff --git a/common/client-libs/validator-client/src/models.rs b/common/client-libs/validator-client/src/models.rs index a0c992fcbd..c98c9963ab 100644 --- a/common/client-libs/validator-client/src/models.rs +++ b/common/client-libs/validator-client/src/models.rs @@ -3,7 +3,7 @@ use crate::serde_helpers::{de_i64_from_str, de_paged_query_response_from_str}; use core::fmt::{self, Display, Formatter}; -use mixnet_contract::Addr; +use mixnet_contract::IdentityKey; use serde::{Deserialize, Serialize}; // TODO: this is a duplicate code but it really does not feel From dff7a8976a64abdda1e059b458a8fd179230b070 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Stuczy=C5=84ski?= Date: Fri, 18 Jun 2021 12:15:34 +0100 Subject: [PATCH 5/7] cargo fmt --- common/mixnet-contract/src/gateway.rs | 8 ++++++-- common/mixnet-contract/src/mixnode.rs | 8 ++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/common/mixnet-contract/src/gateway.rs b/common/mixnet-contract/src/gateway.rs index 54da623ccb..d4bae81d17 100644 --- a/common/mixnet-contract/src/gateway.rs +++ b/common/mixnet-contract/src/gateway.rs @@ -1,8 +1,8 @@ // due to code generated by JsonSchema #![allow(clippy::field_reassign_with_default)] -use cosmwasm_std::{Addr, Coin}; use crate::{IdentityKey, SphinxKey}; +use cosmwasm_std::{Addr, Coin}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::fmt::Display; @@ -102,7 +102,11 @@ pub struct PagedGatewayResponse { } impl PagedGatewayResponse { - pub fn new(nodes: Vec, per_page: usize, start_next_after: Option) -> Self { + pub fn new( + nodes: Vec, + per_page: usize, + start_next_after: Option, + ) -> Self { PagedGatewayResponse { nodes, per_page, diff --git a/common/mixnet-contract/src/mixnode.rs b/common/mixnet-contract/src/mixnode.rs index 38fdeda8b2..c4bfa7da41 100644 --- a/common/mixnet-contract/src/mixnode.rs +++ b/common/mixnet-contract/src/mixnode.rs @@ -1,8 +1,8 @@ // due to code generated by JsonSchema #![allow(clippy::field_reassign_with_default)] -use cosmwasm_std::{Addr, Coin}; use crate::{IdentityKey, SphinxKey}; +use cosmwasm_std::{Addr, Coin}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::fmt::Display; @@ -125,7 +125,11 @@ pub struct PagedResponse { } impl PagedResponse { - pub fn new(nodes: Vec, per_page: usize, start_next_after: Option) -> Self { + pub fn new( + nodes: Vec, + per_page: usize, + start_next_after: Option, + ) -> Self { PagedResponse { nodes, per_page, From 7d69fa3ed55673315c0f134f89399469d58f5a32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Stuczy=C5=84ski?= Date: Fri, 18 Jun 2021 12:21:33 +0100 Subject: [PATCH 6/7] More cargo fmt action --- contracts/mixnet/src/support/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contracts/mixnet/src/support/tests.rs b/contracts/mixnet/src/support/tests.rs index 89cba360c2..79bb07c816 100644 --- a/contracts/mixnet/src/support/tests.rs +++ b/contracts/mixnet/src/support/tests.rs @@ -1,9 +1,9 @@ #[cfg(test)] pub mod helpers { use super::*; - use crate::contract::{instantiate, INITIAL_MIXNODE_BOND}; use crate::contract::query; use crate::contract::DENOM; + use crate::contract::{instantiate, INITIAL_MIXNODE_BOND}; use crate::msg::InstantiateMsg; use crate::msg::QueryMsg; use crate::transactions::{try_add_gateway, try_add_mixnode}; From 08964f8775bcac729ef8d4bf987d9c365d01fe44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C4=99drzej=20Stuczy=C5=84ski?= Date: Fri, 18 Jun 2021 12:32:13 +0100 Subject: [PATCH 7/7] Introduced type alias for IdentityKey reference --- common/mixnet-contract/src/lib.rs | 1 + contracts/mixnet/src/storage.rs | 47 +++++++++++++++++----------- contracts/mixnet/src/transactions.rs | 4 +-- 3 files changed, 31 insertions(+), 21 deletions(-) diff --git a/common/mixnet-contract/src/lib.rs b/common/mixnet-contract/src/lib.rs index c7dd376082..d43d9d33fe 100644 --- a/common/mixnet-contract/src/lib.rs +++ b/common/mixnet-contract/src/lib.rs @@ -20,4 +20,5 @@ pub struct LayerDistribution { // type aliases for better reasoning about available data pub type IdentityKey = String; +pub type IdentityKeyRef<'a> = &'a str; pub type SphinxKey = String; diff --git a/contracts/mixnet/src/storage.rs b/contracts/mixnet/src/storage.rs index e41dcf3dc2..a2ee80285d 100644 --- a/contracts/mixnet/src/storage.rs +++ b/contracts/mixnet/src/storage.rs @@ -5,7 +5,7 @@ use cosmwasm_storage::{ bucket, bucket_read, singleton, singleton_read, Bucket, ReadonlyBucket, ReadonlySingleton, Singleton, }; -use mixnet_contract::{GatewayBond, IdentityKey, LayerDistribution, MixNodeBond}; +use mixnet_contract::{GatewayBond, IdentityKey, IdentityKeyRef, LayerDistribution, MixNodeBond}; // storage prefixes // all of them must be unique and presumably not be a prefix of a different one @@ -180,7 +180,7 @@ pub(crate) fn increase_mixnode_bond( pub(crate) fn increase_mix_delegated_stakes( storage: &mut dyn Storage, - mix_identity: &IdentityKey, + mix_identity: IdentityKey, scaled_reward_rate: Decimal, ) -> StdResult<()> { let chunk_size = queries::DELEGATION_PAGE_MAX_LIMIT as usize; @@ -188,7 +188,7 @@ pub(crate) fn increase_mix_delegated_stakes( let mut chunk_start: Option> = None; loop { // get `chunk_size` of delegations - let delegations_chunk = mix_delegations_read(storage, mix_identity) + let delegations_chunk = mix_delegations_read(storage, &mix_identity) .range(chunk_start.as_deref(), None, Order::Ascending) .take(chunk_size) .collect::>>()?; @@ -213,7 +213,7 @@ pub(crate) fn increase_mix_delegated_stakes( for (delegator_address, amount) in delegations_chunk.into_iter() { let reward = amount * scaled_reward_rate; let new_amount = amount + reward; - mix_delegations(storage, mix_identity).save(&delegator_address, &new_amount)?; + mix_delegations(storage, &mix_identity).save(&delegator_address, &new_amount)?; } } @@ -222,7 +222,7 @@ pub(crate) fn increase_mix_delegated_stakes( pub(crate) fn increase_gateway_delegated_stakes( storage: &mut dyn Storage, - gateway_identity: &IdentityKey, + gateway_identity: IdentityKey, scaled_reward_rate: Decimal, ) -> StdResult<()> { let chunk_size = queries::DELEGATION_PAGE_MAX_LIMIT as usize; @@ -230,7 +230,7 @@ pub(crate) fn increase_gateway_delegated_stakes( let mut chunk_start: Option> = None; loop { // get `chunk_size` of delegations - let delegations_chunk = gateway_delegations_read(storage, gateway_identity) + let delegations_chunk = gateway_delegations_read(storage, &gateway_identity) .range(chunk_start.as_deref(), None, Order::Ascending) .take(chunk_size) .collect::>>()?; @@ -255,7 +255,8 @@ pub(crate) fn increase_gateway_delegated_stakes( for (delegator_address, amount) in delegations_chunk.into_iter() { let reward = amount * scaled_reward_rate; let new_amount = amount + reward; - gateway_delegations(storage, gateway_identity).save(&delegator_address, &new_amount)?; + gateway_delegations(storage, &gateway_identity) + .save(&delegator_address, &new_amount)?; } } @@ -316,21 +317,21 @@ pub(crate) fn increase_gateway_bond( // delegation related pub fn mix_delegations<'a>( storage: &'a mut dyn Storage, - mix_identity: &'a IdentityKey, + mix_identity: IdentityKeyRef, ) -> Bucket<'a, Uint128> { Bucket::multilevel(storage, &[PREFIX_MIX_DELEGATION, mix_identity.as_bytes()]) } pub fn mix_delegations_read<'a>( storage: &'a dyn Storage, - mix_identity: &'a IdentityKey, + mix_identity: IdentityKeyRef, ) -> ReadonlyBucket<'a, Uint128> { ReadonlyBucket::multilevel(storage, &[PREFIX_MIX_DELEGATION, mix_identity.as_bytes()]) } pub fn gateway_delegations<'a>( storage: &'a mut dyn Storage, - gateway_identity: &'a IdentityKey, + gateway_identity: IdentityKeyRef, ) -> Bucket<'a, Uint128> { Bucket::multilevel( storage, @@ -340,7 +341,7 @@ pub fn gateway_delegations<'a>( pub fn gateway_delegations_read<'a>( storage: &'a dyn Storage, - gateway_identity: &'a IdentityKey, + gateway_identity: IdentityKeyRef, ) -> ReadonlyBucket<'a, Uint128> { ReadonlyBucket::multilevel( storage, @@ -537,7 +538,8 @@ mod tests { // 0.001 let reward = Decimal::from_ratio(1u128, 1000u128); - increase_mix_delegated_stakes(&mut deps.storage, &node_identity, reward).unwrap(); + increase_mix_delegated_stakes(&mut deps.storage, node_identity.clone(), reward) + .unwrap(); // there are no 'new' delegations magically added assert!( @@ -561,7 +563,8 @@ mod tests { .save(delegator_address.as_bytes(), &Uint128(1000)) .unwrap(); - increase_mix_delegated_stakes(&mut deps.storage, &node_identity, reward).unwrap(); + increase_mix_delegated_stakes(&mut deps.storage, node_identity.clone(), reward) + .unwrap(); assert_eq!( Uint128(1001), mix_delegations_read(&mut deps.storage, &node_identity) @@ -585,7 +588,8 @@ mod tests { .unwrap(); } - increase_mix_delegated_stakes(&mut deps.storage, &node_identity, reward).unwrap(); + increase_mix_delegated_stakes(&mut deps.storage, node_identity.clone(), reward) + .unwrap(); for i in 0..100 { let delegator_address = Addr::unchecked(format!("address{}", i)); @@ -613,7 +617,8 @@ mod tests { .unwrap(); } - increase_mix_delegated_stakes(&mut deps.storage, &node_identity, reward).unwrap(); + increase_mix_delegated_stakes(&mut deps.storage, node_identity.clone(), reward) + .unwrap(); for i in 0..queries::DELEGATION_PAGE_MAX_LIMIT * 10 { let delegator_address = Addr::unchecked(format!("address{}", i)); @@ -641,7 +646,8 @@ mod tests { // 0.001 let reward = Decimal::from_ratio(1u128, 1000u128); - increase_gateway_delegated_stakes(&mut deps.storage, &node_identity, reward).unwrap(); + increase_gateway_delegated_stakes(&mut deps.storage, node_identity.clone(), reward) + .unwrap(); // there are no 'new' delegations magically added assert!( @@ -665,7 +671,8 @@ mod tests { .save(delegator_address.as_bytes(), &Uint128(1000)) .unwrap(); - increase_gateway_delegated_stakes(&mut deps.storage, &node_identity, reward).unwrap(); + increase_gateway_delegated_stakes(&mut deps.storage, node_identity.clone(), reward) + .unwrap(); assert_eq!( Uint128(1001), gateway_delegations_read(&mut deps.storage, &node_identity) @@ -689,7 +696,8 @@ mod tests { .unwrap(); } - increase_gateway_delegated_stakes(&mut deps.storage, &node_identity, reward).unwrap(); + increase_gateway_delegated_stakes(&mut deps.storage, node_identity.clone(), reward) + .unwrap(); for i in 0..100 { let delegator_address = Addr::unchecked(format!("address{}", i)); @@ -717,7 +725,8 @@ mod tests { .unwrap(); } - increase_gateway_delegated_stakes(&mut deps.storage, &node_identity, reward).unwrap(); + increase_gateway_delegated_stakes(&mut deps.storage, node_identity.clone(), reward) + .unwrap(); for i in 0..queries::DELEGATION_PAGE_MAX_LIMIT * 10 { let delegator_address = Addr::unchecked(format!("address{}", i)); diff --git a/contracts/mixnet/src/transactions.rs b/contracts/mixnet/src/transactions.rs index 28e415129a..3f70ae364d 100644 --- a/contracts/mixnet/src/transactions.rs +++ b/contracts/mixnet/src/transactions.rs @@ -339,7 +339,7 @@ pub(crate) fn try_reward_mixnode( let scaled_reward = scale_reward_by_uptime(reward, uptime)?; increase_mixnode_bond(deps.storage, current_bond, scaled_reward)?; - increase_mix_delegated_stakes(deps.storage, &mix_identity, scaled_reward)?; + increase_mix_delegated_stakes(deps.storage, mix_identity, scaled_reward)?; Ok(Response::default()) } @@ -372,7 +372,7 @@ pub(crate) fn try_reward_gateway( let scaled_reward = scale_reward_by_uptime(reward, uptime)?; increase_gateway_bond(deps.storage, current_bond, scaled_reward)?; - increase_gateway_delegated_stakes(deps.storage, &gateway_identity, scaled_reward)?; + increase_gateway_delegated_stakes(deps.storage, gateway_identity, scaled_reward)?; Ok(Response::default()) }