diff --git a/Cargo.lock b/Cargo.lock index b441ea228..fc58b286e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12,6 +12,14 @@ dependencies = [ "regex", ] +[[package]] +name = "abi-generator" +version = "0.1.0" +dependencies = [ + "clap 4.1.8", + "ethers", +] + [[package]] name = "addr2line" version = "0.19.0" @@ -166,18 +174,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "auto_impl" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7862e21c893d65a1650125d157eaeec691439379a1cee17ee49031b79236ada4" -dependencies = [ - "proc-macro-error", - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "auto_impl" version = "1.0.1" @@ -244,7 +240,6 @@ dependencies = [ "ethereum-types 0.14.1", "evm", "faster-hex", - "getrandom 0.2.8", "hasher", "hex", "lazy_static", @@ -1197,23 +1192,6 @@ dependencies = [ "serde", ] -[[package]] -name = "ckb-vm-aot" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97d90662540a6a3b0d71e58d789016efe817d2cd0c4ec6b26bcaf7f9b18fe7cf" -dependencies = [ - "cc", - "ckb-vm", - "ckb-vm-definitions", - "derive_more", - "goblin 0.2.3", - "goblin 0.4.0", - "libc", - "memmap2", - "scroll", -] - [[package]] name = "ckb-vm-definitions" version = "0.22.1" @@ -1271,6 +1249,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d7ae14b20b94cb02149ed21a86c423859cbe18dc7ed69845cace50e52b40a5" dependencies = [ "bitflags", + "clap_derive", "clap_lex 0.3.2", "is-terminal", "once_cell", @@ -1278,6 +1257,19 @@ dependencies = [ "termcolor", ] +[[package]] +name = "clap_derive" +version = "4.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44bec8e5c9d09e439c4335b1af0abaab56dcf3b94999a936e1bb47b9134288f0" +dependencies = [ + "heck", + "proc-macro-error", + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "clap_lex" version = "0.2.4" @@ -1524,7 +1516,6 @@ dependencies = [ "common-config-parser", "core-consensus", "core-executor", - "fastrand", "json", "jsonrpsee", "log", @@ -1564,7 +1555,6 @@ dependencies = [ "core-metadata", "core-network", "core-storage", - "creep", "criterion", "futures", "json", @@ -1573,44 +1563,12 @@ dependencies = [ "num-traits", "overlord", "parking_lot 0.12.1", - "rand 0.7.3", "rlp", "rlp-derive", "serde", "serde_json", ] -[[package]] -name = "core-cross-client" -version = "0.1.0" -dependencies = [ - "arc-swap", - "axon-protocol", - "ckb-jsonrpc-types", - "ckb-sdk", - "ckb-types", - "common-config-parser", - "common-crypto", - "core-executor", - "ethabi 17.2.0", - "ethabi-contract", - "ethabi-derive", - "ethers-contract", - "ethers-core 1.0.2", - "ethers-providers", - "futures", - "jsonrpc-core", - "lazy_static", - "log", - "molecule", - "rand 0.7.3", - "rlp", - "serde", - "serde_json", - "sled", - "tokio-util 0.7.7", -] - [[package]] name = "core-executor" version = "0.1.0" @@ -1628,7 +1586,6 @@ dependencies = [ "common-config-parser", "common-crypto", "common-merkle", - "core-cross-client", "core-interoperation", "core-rpc-client", "core-storage", @@ -1637,11 +1594,8 @@ dependencies = [ "ethabi-contract", "ethabi-derive", "ethers", - "ethers-contract", - "ethers-core 1.0.2", "evm", "futures", - "getrandom 0.2.8", "hashbrown 0.13.2", "hasher", "lazy_static", @@ -1650,8 +1604,6 @@ dependencies = [ "molecule", "once_cell", "parking_lot 0.12.1", - "rand 0.7.3", - "rand 0.8.5", "revm", "ripemd", "rlp", @@ -1694,15 +1646,13 @@ dependencies = [ "ckb-traits", "ckb-types", "ckb-vm", - "ckb-vm-aot", "core-executor", "core-rpc-client", "core-storage", "ed25519-dalek", - "ethers-core 1.0.2", + "ethers-core 2.0.0", "lazy_static", "log", - "rand 0.7.3", "serde_json", ] @@ -1725,7 +1675,6 @@ dependencies = [ "futures", "log", "parking_lot 0.12.1", - "rand 0.7.3", "rlp", "rlp-derive", ] @@ -1739,12 +1688,11 @@ dependencies = [ "common-apm", "core-executor", "core-storage", - "ethers-contract", + "ethers-contract 1.0.2", "ethers-core 1.0.2", - "ethers-providers", + "ethers-providers 1.0.2", "lazy_static", "parking_lot 0.12.1", - "rand 0.7.3", "serde_json", ] @@ -1764,7 +1712,6 @@ dependencies = [ "log", "parking_lot 0.12.1", "prost", - "rand 0.7.3", "rlp", "serde", "serde_json", @@ -1803,7 +1750,6 @@ dependencies = [ "common-memory-tracker", "core-api", "core-consensus", - "core-cross-client", "core-executor", "core-interoperation", "core-mempool", @@ -1811,8 +1757,7 @@ dependencies = [ "core-network", "core-rpc-client", "core-storage", - "core-tx-assembler", - "ethers-signers 2.0.0", + "ethers-signers", "futures", "log", "rlp", @@ -1842,26 +1787,6 @@ dependencies = [ "lru 0.10.0", "num-traits", "parking_lot 0.12.1", - "rand 0.7.3", -] - -[[package]] -name = "core-tx-assembler" -version = "0.1.0" -dependencies = [ - "arc-swap", - "axon-protocol", - "ckb-jsonrpc-types", - "ckb-sdk", - "ckb-types", - "common-crypto", - "core-rpc-client", - "lazy_static", - "log", - "molecule", - "rand 0.7.3", - "serde", - "serde_json", ] [[package]] @@ -2312,6 +2237,25 @@ dependencies = [ "cfg-if 1.0.0", ] +[[package]] +name = "enr" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "492a7e5fc2504d5fdce8e124d3e263b244a68b283cac67a69eda0cd43e0aebad" +dependencies = [ + "base64 0.13.1", + "bs58", + "bytes", + "hex", + "k256", + "log", + "rand 0.8.5", + "rlp", + "serde", + "sha3", + "zeroize", +] + [[package]] name = "enum-repr-derive" version = "0.2.0" @@ -2402,23 +2346,6 @@ dependencies = [ "uint", ] -[[package]] -name = "ethabi" -version = "17.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4966fba78396ff92db3b817ee71143eccd98acf0f876b8d600e585a670c5d1b" -dependencies = [ - "ethereum-types 0.13.1", - "hex", - "once_cell", - "regex", - "serde", - "serde_json", - "sha3", - "thiserror", - "uint", -] - [[package]] name = "ethabi" version = "18.0.0" @@ -2531,26 +2458,26 @@ dependencies = [ [[package]] name = "ethers" -version = "1.0.2" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11f26f9d8d80da18ca72aca51804c65eb2153093af3bec74fd5ce32aa0c1f665" +checksum = "839a392641e746a1ff365ef7c901238410b5c6285d240cf2409ffaaa7df9a78a" dependencies = [ "ethers-addressbook", - "ethers-contract", - "ethers-core 1.0.2", + "ethers-contract 2.0.0", + "ethers-core 2.0.0", "ethers-etherscan", "ethers-middleware", - "ethers-providers", - "ethers-signers 1.0.2", + "ethers-providers 2.0.0", + "ethers-signers", ] [[package]] name = "ethers-addressbook" -version = "1.0.2" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe4be54dd2260945d784e06ccdeb5ad573e8f1541838cee13a1ab885485eaa0b" +checksum = "9e1e010165c08a2a3fa43c0bb8bc9d596f079a021aaa2cc4e8d921df09709c95" dependencies = [ - "ethers-core 1.0.2", + "ethers-core 2.0.0", "once_cell", "serde", "serde_json", @@ -2562,10 +2489,29 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e9c3c3e119a89f0a9a1e539e7faecea815f74ddcf7c90d0b00d1f524db2fdc9c" dependencies = [ - "ethers-contract-abigen", - "ethers-contract-derive", + "ethers-contract-abigen 1.0.2", + "ethers-contract-derive 1.0.2", "ethers-core 1.0.2", - "ethers-providers", + "ethers-providers 1.0.2", + "futures-util", + "hex", + "once_cell", + "pin-project", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "ethers-contract" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be33fd47a06cc8f97caf614cf7cf91af9dd6dcd767511578895fa884b430c4b8" +dependencies = [ + "ethers-contract-abigen 2.0.0", + "ethers-contract-derive 2.0.0", + "ethers-core 2.0.0", + "ethers-providers 2.0.0", "futures-util", "hex", "once_cell", @@ -2600,13 +2546,41 @@ dependencies = [ "walkdir", ] +[[package]] +name = "ethers-contract-abigen" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60d9f9ecb4a18c1693de954404b66e0c9df31dac055b411645e38c4efebf3dbc" +dependencies = [ + "Inflector", + "cfg-if 1.0.0", + "dunce", + "ethers-core 2.0.0", + "ethers-etherscan", + "eyre", + "getrandom 0.2.8", + "hex", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "reqwest", + "serde", + "serde_json", + "syn", + "tokio", + "toml 0.5.11", + "url", + "walkdir", +] + [[package]] name = "ethers-contract-derive" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f192e8e4cf2b038318aae01e94e7644e0659a76219e94bcd3203df744341d61f" dependencies = [ - "ethers-contract-abigen", + "ethers-contract-abigen 1.0.2", "ethers-core 1.0.2", "hex", "proc-macro2", @@ -2615,6 +2589,22 @@ dependencies = [ "syn", ] +[[package]] +name = "ethers-contract-derive" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "001b33443a67e273120923df18bab907a0744ad4b5fef681a8b0691f2ee0f3de" +dependencies = [ + "ethers-contract-abigen 2.0.0", + "ethers-core 2.0.0", + "eyre", + "hex", + "proc-macro2", + "quote", + "serde_json", + "syn", +] + [[package]] name = "ethers-core" version = "1.0.2" @@ -2625,7 +2615,6 @@ dependencies = [ "bytes", "cargo_metadata", "chrono", - "convert_case 0.6.0", "elliptic-curve", "ethabi 18.0.0", "generic-array 0.14.6", @@ -2633,7 +2622,6 @@ dependencies = [ "k256", "once_cell", "open-fastrlp", - "proc-macro2", "rand 0.8.5", "rlp", "rlp-derive", @@ -2654,6 +2642,7 @@ checksum = "d5925cba515ac18eb5c798ddf6069cc33ae00916cb08ae64194364a1b35c100b" dependencies = [ "arrayvec", "bytes", + "cargo_metadata", "chrono", "convert_case 0.6.0", "elliptic-curve", @@ -2663,6 +2652,7 @@ dependencies = [ "hex", "k256", "num_enum", + "once_cell", "open-fastrlp", "proc-macro2", "rand 0.8.5", @@ -2680,11 +2670,11 @@ dependencies = [ [[package]] name = "ethers-etherscan" -version = "1.0.2" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9713f525348e5dde025d09b0a4217429f8074e8ff22c886263cc191e87d8216" +checksum = "0d769437fafd0b47ea8b95e774e343c5195c77423f0f54b48d11c0d9ed2148ad" dependencies = [ - "ethers-core 1.0.2", + "ethers-core 2.0.0", "getrandom 0.2.8", "reqwest", "semver", @@ -2697,17 +2687,17 @@ dependencies = [ [[package]] name = "ethers-middleware" -version = "1.0.2" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e71df7391b0a9a51208ffb5c7f2d068900e99d6b3128d3a4849d138f194778b7" +checksum = "a7dd311b76eab9d15209e4fd16bb419e25543709cbdf33079e8923dfa597517c" dependencies = [ "async-trait", - "auto_impl 0.5.0", - "ethers-contract", - "ethers-core 1.0.2", + "auto_impl", + "ethers-contract 2.0.0", + "ethers-core 2.0.0", "ethers-etherscan", - "ethers-providers", - "ethers-signers 1.0.2", + "ethers-providers 2.0.0", + "ethers-signers", "futures-locks", "futures-util", "instant", @@ -2728,7 +2718,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1a9e0597aa6b2fdc810ff58bc95e4eeaa2c219b3e615ed025106ecb027407d8" dependencies = [ "async-trait", - "auto_impl 1.0.1", + "auto_impl", "base64 0.13.1", "ethers-core 1.0.2", "futures-channel", @@ -2747,7 +2737,7 @@ dependencies = [ "serde_json", "thiserror", "tokio", - "tokio-tungstenite", + "tokio-tungstenite 0.17.2", "tracing", "tracing-futures", "url", @@ -2759,21 +2749,41 @@ dependencies = [ ] [[package]] -name = "ethers-signers" -version = "1.0.2" +name = "ethers-providers" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f41ced186867f64773db2e55ffdd92959e094072a1d09a5e5e831d443204f98" +checksum = "ed7174af93619e81844d3d49887106a3721e5caecdf306e0b824bfb4316db3be" dependencies = [ "async-trait", - "coins-bip32", - "coins-bip39", - "elliptic-curve", - "eth-keystore", - "ethers-core 1.0.2", + "auto_impl", + "base64 0.21.0", + "enr", + "ethers-core 2.0.0", + "futures-channel", + "futures-core", + "futures-timer", + "futures-util", + "getrandom 0.2.8", + "hashers", "hex", - "rand 0.8.5", - "sha2 0.10.6", + "http", + "once_cell", + "parking_lot 0.11.2", + "pin-project", + "reqwest", + "serde", + "serde_json", "thiserror", + "tokio", + "tokio-tungstenite 0.18.0", + "tracing", + "tracing-futures", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-timer", + "web-sys", + "ws_stream_wasm", ] [[package]] @@ -2801,7 +2811,7 @@ version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f4448c65b71e8e2b9718232d84d09045eeaaccb2320494e6bd6dbf7e58fec8ff" dependencies = [ - "auto_impl 1.0.1", + "auto_impl", "environmental", "ethereum", "evm-core", @@ -2846,7 +2856,7 @@ version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c79b9459ce64f1a28688397c4013764ce53cd57bb84efc16b5187fa9b05b13ad" dependencies = [ - "auto_impl 1.0.1", + "auto_impl", "environmental", "evm-core", "primitive-types 0.12.1", @@ -2987,16 +2997,6 @@ dependencies = [ "percent-encoding", ] -[[package]] -name = "fs2" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" -dependencies = [ - "libc", - "winapi", -] - [[package]] name = "fuchsia-cprng" version = "0.1.1" @@ -3173,9 +3173,9 @@ dependencies = [ "common-crypto", "core-executor", "core-metadata", - "ethers-contract", + "ethers-contract 2.0.0", "ethers-core 1.0.2", - "ethers-providers", + "ethers-providers 2.0.0", "ophelia", "rand 0.7.3", "serde", @@ -4375,7 +4375,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "786393f80485445794f6043fd3138854dd109cc6c4bd1a6383db304c9ce9b9ce" dependencies = [ "arrayvec", - "auto_impl 1.0.1", + "auto_impl", "bytes", "ethereum-types 0.14.1", "open-fastrlp-derive", @@ -5295,7 +5295,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73d84c8f9836efb0f5f5f8de4700a953c4e1f3119e5cfcb0aad8e5be73daf991" dependencies = [ "arrayref", - "auto_impl 1.0.1", + "auto_impl", "bytes", "hashbrown 0.13.2", "num_enum", @@ -5844,6 +5844,17 @@ dependencies = [ "digest 0.10.6", ] +[[package]] +name = "sha1" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3" +dependencies = [ + "cfg-if 1.0.0", + "cpufeatures", + "digest 0.10.6", +] + [[package]] name = "sha2" version = "0.8.2" @@ -5930,22 +5941,6 @@ dependencies = [ "autocfg", ] -[[package]] -name = "sled" -version = "0.34.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f96b4737c2ce5987354855aed3797279def4ebf734436c6aa4552cf8e169935" -dependencies = [ - "crc32fast", - "crossbeam-epoch", - "crossbeam-utils", - "fs2", - "fxhash", - "libc", - "log", - "parking_lot 0.11.2", -] - [[package]] name = "smallvec" version = "1.10.0" @@ -6452,7 +6447,23 @@ dependencies = [ "rustls", "tokio", "tokio-rustls", - "tungstenite", + "tungstenite 0.17.3", + "webpki", + "webpki-roots", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54319c93411147bced34cb5609a80e0a8e44c5999c93903a81cd866630ec0bfd" +dependencies = [ + "futures-util", + "log", + "rustls", + "tokio", + "tokio-rustls", + "tungstenite 0.18.0", "webpki", "webpki-roots", ] @@ -6680,6 +6691,27 @@ dependencies = [ "webpki", ] +[[package]] +name = "tungstenite" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30ee6ab729cd4cf0fd55218530c4522ed30b7b6081752839b68fcec8d0960788" +dependencies = [ + "base64 0.13.1", + "byteorder", + "bytes", + "http", + "httparse", + "log", + "rand 0.8.5", + "rustls", + "sha1", + "thiserror", + "url", + "utf-8", + "webpki", +] + [[package]] name = "typemap-ors" version = "1.0.0" diff --git a/Cargo.toml b/Cargo.toml index 5fdb572a4..9a5273aa0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,7 +30,6 @@ members = [ "core/api", "core/cli", "core/consensus", - "core/cross-client", "core/executor", "core/mempool", "core/metadata", @@ -39,7 +38,7 @@ members = [ "core/run", "core/storage", - "core/tx-assembler", + "devtools/abi-generator", "devtools/genesis-generator", "devtools/keypair", diff --git a/core/api/Cargo.toml b/core/api/Cargo.toml index 23ac9944a..9f21b5290 100644 --- a/core/api/Cargo.toml +++ b/core/api/Cargo.toml @@ -22,5 +22,4 @@ core-executor = { path = "../../core/executor" } protocol = { path = "../../protocol", package = "axon-protocol" } [dev-dependencies] -fastrand = "1.8" json = "0.12" diff --git a/core/api/src/adapter.rs b/core/api/src/adapter.rs index 7d6729148..3783da8b8 100644 --- a/core/api/src/adapter.rs +++ b/core/api/src/adapter.rs @@ -3,9 +3,8 @@ use std::sync::Arc; use core_executor::{AxonExecutor, AxonExecutorAdapter, MPTTrie}; use protocol::traits::{APIAdapter, Context, Executor, ExecutorAdapter, MemPool, Network, Storage}; use protocol::types::{ - Account, BigEndianHash, Block, BlockNumber, Bytes, ExecutorContext, Hash, HashWithDirection, - Header, Proposal, Receipt, SignedTransaction, TxResp, H160, MAX_BLOCK_GAS_LIMIT, NIL_DATA, - RLP_NULL, U256, + Account, BigEndianHash, Block, BlockNumber, Bytes, ExecutorContext, Hash, Header, Proposal, + Receipt, SignedTransaction, TxResp, H160, MAX_BLOCK_GAS_LIMIT, NIL_DATA, RLP_NULL, U256, }; use protocol::{async_trait, codec::ProtocolCodec, trie, ProtocolResult}; @@ -196,14 +195,6 @@ where self.storage.get_code_by_hash(ctx, hash).await } - async fn get_crosschain_record_by_hash( - &self, - ctx: Context, - hash: &Hash, - ) -> ProtocolResult> { - self.storage.get_crosschain_record(ctx, hash).await - } - async fn peer_count(&self, ctx: Context) -> ProtocolResult { self.net.peer_count(ctx).map(Into::into) } diff --git a/core/api/src/jsonrpc/crosschain_types.rs b/core/api/src/jsonrpc/crosschain_types.rs deleted file mode 100644 index 320942a09..000000000 --- a/core/api/src/jsonrpc/crosschain_types.rs +++ /dev/null @@ -1,16 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use protocol::types::{Direction, H256}; - -use crate::jsonrpc::web3_types::{Web3Receipt, Web3Transaction}; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] -pub struct CrossChainTransaction { - pub request_tx_hash: H256, - pub relay_tx_hash: H256, - pub direction: Direction, - #[serde(skip_serializing_if = "Option::is_none")] - pub axon_tx: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub receipt: Option, -} diff --git a/core/api/src/jsonrpc/impl/crosschain.rs b/core/api/src/jsonrpc/impl/crosschain.rs deleted file mode 100644 index 845f094fd..000000000 --- a/core/api/src/jsonrpc/impl/crosschain.rs +++ /dev/null @@ -1,71 +0,0 @@ -use std::sync::Arc; - -use protocol::traits::{APIAdapter, Context}; -use protocol::{async_trait, types::H256}; - -use crate::jsonrpc::web3_types::{Web3Receipt, Web3Transaction}; -use crate::jsonrpc::{ - crosschain_types::CrossChainTransaction, AxonCrossChainRpcServer, Error, RpcResult, -}; - -pub struct CrossChainRpcImpl { - adapter: Arc, -} - -impl CrossChainRpcImpl { - pub fn new(adapter: Arc) -> Self { - CrossChainRpcImpl { adapter } - } -} - -#[async_trait] -impl AxonCrossChainRpcServer for CrossChainRpcImpl { - async fn get_crosschain_result( - &self, - tx_hash: H256, - ) -> RpcResult> { - let ctx = Context::new(); - if let Some(hash_with_dir) = self - .adapter - .get_crosschain_record_by_hash(ctx.clone(), &tx_hash) - .await - .map_err(|e| Error::Custom(e.to_string()))? - { - if !hash_with_dir.direction.is_from_ckb() { - return Ok(Some(CrossChainTransaction { - request_tx_hash: tx_hash, - relay_tx_hash: hash_with_dir.tx_hash, - direction: hash_with_dir.direction, - axon_tx: None, - receipt: None, - })); - } - - let hash = hash_with_dir.tx_hash; - let stx = self - .adapter - .get_transaction_by_hash(ctx.clone(), hash) - .await - .map_err(|e| Error::Custom(e.to_string()))? - .ok_or_else(|| { - Error::Custom(format!("Can not get transaction by hash {:?}", hash)) - })?; - let receipt = self - .adapter - .get_receipt_by_tx_hash(ctx, hash) - .await - .map_err(|e| Error::Custom(e.to_string()))? - .ok_or_else(|| Error::Custom(format!("Can not get receipt by hash {:?}", hash)))?; - - return Ok(Some(CrossChainTransaction { - request_tx_hash: tx_hash, - relay_tx_hash: hash, - direction: hash_with_dir.direction, - axon_tx: Some(Web3Transaction::from((stx.clone(), receipt.clone()))), - receipt: Some(Web3Receipt::new(receipt, stx)), - })); - } - - Ok(None) - } -} diff --git a/core/api/src/jsonrpc/impl/mod.rs b/core/api/src/jsonrpc/impl/mod.rs index 5f16a46b0..7faefcecb 100644 --- a/core/api/src/jsonrpc/impl/mod.rs +++ b/core/api/src/jsonrpc/impl/mod.rs @@ -1,9 +1,7 @@ -mod crosschain; mod filter; mod node; mod web3; -pub use crosschain::CrossChainRpcImpl; pub use filter::filter_module; pub use node::NodeRpcImpl; pub use web3::{from_receipt_to_web3_log, Web3RpcImpl}; diff --git a/core/api/src/jsonrpc/mod.rs b/core/api/src/jsonrpc/mod.rs index 425e64fbe..ed8ccd6cc 100644 --- a/core/api/src/jsonrpc/mod.rs +++ b/core/api/src/jsonrpc/mod.rs @@ -1,4 +1,3 @@ -mod crosschain_types; mod error; mod r#impl; mod web3_types; @@ -19,7 +18,7 @@ use crate::jsonrpc::web3_types::{ Web3Filter, Web3Log, Web3Receipt, Web3SyncStatus, Web3Transaction, }; use crate::jsonrpc::ws_subscription::{ws_subscription_module, HexIdProvider}; -use crate::{jsonrpc::crosschain_types::CrossChainTransaction, APIError}; +use crate::APIError; type RpcResult = Result; @@ -201,15 +200,6 @@ pub trait AxonNodeRpc { fn pprof(&self, enable: bool) -> RpcResult; } -#[rpc(server)] -pub trait AxonCrossChainRpc { - #[method(name = "getCrosschainResult")] - async fn get_crosschain_result( - &self, - tx_hash: H256, - ) -> RpcResult>; -} - pub async fn run_jsonrpc_server( config: Config, adapter: Arc, @@ -219,11 +209,9 @@ pub async fn run_jsonrpc_server( let mut rpc = r#impl::Web3RpcImpl::new(Arc::clone(&adapter), config.rpc.gas_cap).into_rpc(); let node_rpc = r#impl::NodeRpcImpl::new(&config.rpc.client_version, config.data_path).into_rpc(); - let crosschain_rpc = r#impl::CrossChainRpcImpl::new(Arc::clone(&adapter)).into_rpc(); let filter = r#impl::filter_module(Arc::clone(&adapter)).into_rpc(); rpc.merge(node_rpc).unwrap(); - rpc.merge(crosschain_rpc).unwrap(); rpc.merge(filter).unwrap(); if let Some(addr) = config.rpc.http_listening_address { diff --git a/core/api/src/jsonrpc/web3_types.rs b/core/api/src/jsonrpc/web3_types.rs index a3ba71456..bed06e89a 100644 --- a/core/api/src/jsonrpc/web3_types.rs +++ b/core/api/src/jsonrpc/web3_types.rs @@ -755,6 +755,7 @@ pub struct RawLoggerFilter { #[cfg(test)] mod tests { use super::*; + use protocol::rand::random; #[test] fn test_sync_status_json() { @@ -763,9 +764,9 @@ mod tests { assert!(json.is_boolean()); let status = Web3SyncStatus::Doing(SyncStatus { - starting_block: fastrand::u64(..).into(), - current_block: fastrand::u64(..).into(), - highest_block: fastrand::u64(..).into(), + starting_block: random::().into(), + current_block: random::().into(), + highest_block: random::().into(), known_states: U256::default(), pulled_states: U256::default(), }); diff --git a/core/consensus/Cargo.toml b/core/consensus/Cargo.toml index 3b64f5c2a..eaa2c3ce0 100644 --- a/core/consensus/Cargo.toml +++ b/core/consensus/Cargo.toml @@ -7,7 +7,6 @@ edition = "2021" [dependencies] arc-swap = "1.6" -creep = "0.2" futures = { version = "0.3", features = ["async-await"] } json = "0.12" lazy_static = "1.4" @@ -35,7 +34,6 @@ protocol = { path = "../../protocol", package = "axon-protocol" } bit-vec = "0.6" criterion = "0.4" num-traits = "0.2" -rand = "0.7" [features] default = [] diff --git a/core/consensus/benches/bench_wal.rs b/core/consensus/benches/bench_wal.rs index 2bf6a51a8..7482c43e4 100644 --- a/core/consensus/benches/bench_wal.rs +++ b/core/consensus/benches/bench_wal.rs @@ -1,11 +1,10 @@ use criterion::{criterion_group, criterion_main, Criterion}; -use rand::random; -use rand::rngs::OsRng; use common_crypto::{ Crypto, PrivateKey, Secp256k1Recoverable, Secp256k1RecoverablePrivateKey, Signature, }; use core_consensus::SignedTxsWAL; +use protocol::rand::{random, rngs::OsRng}; use protocol::types::{ Bytes, Eip1559Transaction, Hash, Hasher, SignatureComponents, SignedTransaction, TransactionAction, UnsignedTransaction, UnverifiedTransaction, diff --git a/core/consensus/src/adapter.rs b/core/consensus/src/adapter.rs index 07603eb02..bbec8f88d 100644 --- a/core/consensus/src/adapter.rs +++ b/core/consensus/src/adapter.rs @@ -10,13 +10,12 @@ use common_apm_derive::trace_span; use core_executor::{AxonExecutor, AxonExecutorAdapter}; use core_network::{PeerId, PeerIdExt}; use protocol::traits::{ - CommonConsensusAdapter, ConsensusAdapter, Context, CrossChain, Executor, Gossip, MemPool, - MessageTarget, MetadataControl, Network, PeerTrust, Priority, Rpc, Storage, - SynchronizationAdapter, + CommonConsensusAdapter, ConsensusAdapter, Context, Executor, Gossip, MemPool, MessageTarget, + MetadataControl, Network, PeerTrust, Priority, Rpc, Storage, SynchronizationAdapter, }; use protocol::types::{ - BatchSignedTxs, Block, BlockNumber, Bytes, ExecResp, Hash, Header, Hex, Log, MerkleRoot, - Metadata, PackedTxHashes, Proof, Proposal, Receipt, SignedTransaction, Validator, U256, + BatchSignedTxs, Block, BlockNumber, Bytes, ExecResp, Hash, Header, Hex, MerkleRoot, Metadata, + PackedTxHashes, Proof, Proposal, Receipt, SignedTransaction, Validator, U256, }; use protocol::{async_trait, tokio::task, trie, ProtocolResult}; @@ -34,7 +33,6 @@ pub struct OverlordConsensusAdapter< M: MemPool, N: Rpc + PeerTrust + Gossip + 'static, S: Storage, - CS: CrossChain, MT: MetadataControl, DB: trie::DB, > { @@ -43,19 +41,17 @@ pub struct OverlordConsensusAdapter< storage: Arc, trie_db: Arc, - cross_client: Arc, metadata: Arc, overlord_handler: RwLock>>, crypto: Arc, } #[async_trait] -impl ConsensusAdapter for OverlordConsensusAdapter +impl ConsensusAdapter for OverlordConsensusAdapter where M: MemPool + 'static, N: Network + Rpc + PeerTrust + Gossip + 'static, S: Storage + 'static, - CS: CrossChain + 'static, MT: MetadataControl + 'static, DB: trie::DB + 'static, { @@ -129,12 +125,11 @@ where } #[async_trait] -impl SynchronizationAdapter for OverlordConsensusAdapter +impl SynchronizationAdapter for OverlordConsensusAdapter where M: MemPool + 'static, N: Network + Rpc + PeerTrust + Gossip + 'static, S: Storage + 'static, - CS: CrossChain + 'static, MT: MetadataControl + 'static, DB: trie::DB + 'static, { @@ -232,12 +227,11 @@ where } #[async_trait] -impl CommonConsensusAdapter for OverlordConsensusAdapter +impl CommonConsensusAdapter for OverlordConsensusAdapter where M: MemPool + 'static, N: Network + Rpc + PeerTrust + Gossip + 'static, S: Storage + 'static, - CS: CrossChain + 'static, MT: MetadataControl + 'static, DB: trie::DB + 'static, { @@ -542,22 +536,6 @@ where Ok(()) } - async fn notify_block_logs( - &self, - ctx: Context, - block_number: u64, - block_hash: Hash, - logs: &[Vec], - ) { - self.cross_client - .set_evm_log(ctx, block_number, block_hash, logs) - .await - } - - async fn notify_checkpoint(&self, ctx: Context, block: Block, proof: Proof) { - self.cross_client.set_checkpoint(ctx, block, proof).await - } - #[trace_span(kind = "consensus.adapter")] fn verify_proof_signature( &self, @@ -628,12 +606,11 @@ where } } -impl OverlordConsensusAdapter +impl OverlordConsensusAdapter where M: MemPool + 'static, N: Rpc + PeerTrust + Gossip + 'static, S: Storage + 'static, - CS: CrossChain + 'static, MT: MetadataControl + 'static, DB: trie::DB + 'static, { @@ -642,7 +619,6 @@ where mempool: Arc, storage: Arc, trie_db: Arc, - cross_client: Arc, metadata: Arc, crypto: Arc, ) -> ProtocolResult { @@ -652,7 +628,6 @@ where storage, metadata, trie_db, - cross_client, overlord_handler: RwLock::new(None), crypto, }) diff --git a/core/consensus/src/consensus.rs b/core/consensus/src/consensus.rs index cda9b95d9..87fe0f95f 100644 --- a/core/consensus/src/consensus.rs +++ b/core/consensus/src/consensus.rs @@ -1,12 +1,11 @@ use std::sync::Arc; -use creep::Context; use overlord::types::{ AggregatedVote, Node, OverlordMsg, SignedChoke, SignedProposal, SignedVote, Status, }; use overlord::{DurationConfig, Overlord, OverlordHandler}; -use protocol::traits::{Consensus, ConsensusAdapter, NodeInfo}; +use protocol::traits::{Consensus, ConsensusAdapter, Context, NodeInfo}; use protocol::types::{Proposal, Validator, H160}; use protocol::{ async_trait, codec::ProtocolCodec, tokio::sync::Mutex as AsyncMutex, ProtocolResult, @@ -110,7 +109,6 @@ impl OverlordConsensus { adapter: Arc, lock: Arc>, consensus_wal: Arc, - cross_period_interval: u64, ) -> Self { let engine = Arc::new(ConsensusEngine::new( status, @@ -121,7 +119,6 @@ impl OverlordConsensus { Arc::clone(&crypto), lock, consensus_wal, - cross_period_interval, )); let status = engine.status(); let metadata = adapter.get_metadata_unchecked(Context::new(), status.last_number + 1); diff --git a/core/consensus/src/engine.rs b/core/consensus/src/engine.rs index 4099755d6..7b7c75700 100644 --- a/core/consensus/src/engine.rs +++ b/core/consensus/src/engine.rs @@ -51,7 +51,6 @@ pub struct ConsensusEngine { crypto: Arc, lock: Arc>, - cross_period_interval: u64, last_commit_time: RwLock, consensus_wal: Arc, last_check_block_fail_reason: RwLock, @@ -456,7 +455,6 @@ impl ConsensusEngine { crypto: Arc, lock: Arc>, consensus_wal: Arc, - cross_period_interval: u64, ) -> Self { Self { status, @@ -467,7 +465,6 @@ impl ConsensusEngine { adapter, crypto, lock, - cross_period_interval, last_commit_time: RwLock::new(time_now()), consensus_wal, last_check_block_fail_reason: RwLock::new(String::new()), @@ -598,7 +595,7 @@ impl ConsensusEngine { let is_change_metadata = self.contains_change_metadata(&txs); let next_block_number = block_number + 1; - let (receipts, mut logs) = generate_receipts_and_logs( + let (receipts, _logs) = generate_receipts_and_logs( block_number, block_hash, block.header.state_root, @@ -606,19 +603,6 @@ impl ConsensusEngine { &resp, ); - // Call cross client - let _ = logs.split_off(block.header.call_system_script_count as usize); - self.adapter - .notify_block_logs(ctx.clone(), block_number, block_hash, &logs) - .await; - - // Submit checkpoint - if block_number % self.cross_period_interval == 0 { - self.adapter - .notify_checkpoint(ctx.clone(), block.clone(), proof.clone()) - .await; - } - // Save signed transactions self.adapter .save_signed_txs(ctx.clone(), block_number, txs) diff --git a/core/consensus/src/tests/mod.rs b/core/consensus/src/tests/mod.rs index f3d220df5..8dd50f15f 100644 --- a/core/consensus/src/tests/mod.rs +++ b/core/consensus/src/tests/mod.rs @@ -5,16 +5,14 @@ pub mod synchronization; use std::{collections::HashMap, str::FromStr}; -use rand::random; - -use creep::Context; +use protocol::rand::random; use protocol::{ async_trait, codec::hex_decode, - traits::{CommonConsensusAdapter, SynchronizationAdapter}, + traits::{CommonConsensusAdapter, Context, SynchronizationAdapter}, types::{ Address, Block, BlockNumber, Bytes, Eip1559Transaction, ExecResp, Hash, Hasher, Header, - Hex, Log, MerkleRoot, Metadata, Proof, Proposal, Public, Receipt, SignatureComponents, + Hex, MerkleRoot, Metadata, Proof, Proposal, Public, Receipt, SignatureComponents, SignedTransaction, TransactionAction, UnsignedTransaction, UnverifiedTransaction, Validator, H160, H256, U256, }, @@ -321,17 +319,6 @@ impl CommonConsensusAdapter for MockSyncAdapter { Ok(()) } - async fn notify_block_logs( - &self, - ctx: Context, - block_number: u64, - block_hash: Hash, - logs: &[Vec], - ) { - } - - async fn notify_checkpoint(&self, ctx: Context, block: Block, proof: Proof) {} - fn verify_proof_signature( &self, ctx: Context, diff --git a/core/consensus/src/tests/synchronization.rs b/core/consensus/src/tests/synchronization.rs index eb76ee745..072829abf 100644 --- a/core/consensus/src/tests/synchronization.rs +++ b/core/consensus/src/tests/synchronization.rs @@ -1,17 +1,17 @@ use std::sync::Arc; +use protocol::{ + tokio::{self, sync::Mutex as AsyncMutex}, + traits::{Context, Synchronization}, + types::{Block, Header}, +}; + use crate::{ status::{CurrentStatus, StatusAgent}, synchronization::{OverlordSynchronization, RichBlock}, tests::MockSyncAdapter, util::time_now, }; -use creep::Context; -use protocol::{ - tokio::{self, sync::Mutex as AsyncMutex}, - traits::Synchronization, - types::{Block, Header}, -}; pub fn get_mock_synchronization() -> OverlordSynchronization { let sync_txs_chunk_size = 50; diff --git a/core/consensus/src/wal.rs b/core/consensus/src/wal.rs index f4f547800..7b162642d 100644 --- a/core/consensus/src/wal.rs +++ b/core/consensus/src/wal.rs @@ -1,13 +1,9 @@ -use std::fs; use std::io::{ErrorKind, Read, Write}; use std::path::{Path, PathBuf}; -use std::str::FromStr; -use std::time::SystemTime; - -use creep::Context; +use std::{fs, str::FromStr, time::SystemTime}; use common_apm_derive::trace_span; -use protocol::traits::MessageCodec; +use protocol::traits::{Context, MessageCodec}; use protocol::types::{BatchSignedTxs, BufMut, Bytes, BytesMut, Hash, Hasher, SignedTransaction}; use protocol::ProtocolResult; @@ -322,9 +318,8 @@ mod tests { use common_crypto::{ Crypto, PrivateKey, Secp256k1Recoverable, Secp256k1RecoverablePrivateKey, Signature, }; - use rand::random; - use rand::rngs::OsRng; + use protocol::rand::{random, rngs::OsRng}; use protocol::types::{ Bytes, Eip1559Transaction, Hash, SignatureComponents, SignedTransaction, TransactionAction, UnsignedTransaction, UnverifiedTransaction, diff --git a/core/cross-client/Cargo.toml b/core/cross-client/Cargo.toml deleted file mode 100644 index 146196d8a..000000000 --- a/core/cross-client/Cargo.toml +++ /dev/null @@ -1,35 +0,0 @@ -[package] -name = "core-cross-client" -version = "0.1.0" -edition = "2021" -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -arc-swap = "1.6" -ckb-jsonrpc-types = "0.106" -ckb-sdk = "2.4" -ckb-types = "0.106" -ethabi = "17.2" -ethabi-contract = { git = "https://github.com/rust-ethereum/ethabi.git", rev = "7edf185" } -ethabi-derive = { git = "https://github.com/rust-ethereum/ethabi.git", rev = "7edf185" } -ethers-contract = "1.0" -ethers-core = "1.0" -ethers-providers = "1.0" -futures = "0.3" -jsonrpc-core = "18.0" -lazy_static = "1.4" -log = "0.4" -molecule = "0.7" -rlp = "0.5" -serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" -sled = "0.34" -tokio-util = { version = "0.7", features = ["codec"] } - -common-config-parser = { path = "../../common/config-parser" } -common-crypto = { path = "../../common/crypto" } -core-executor = { path = "../../core/executor" } -protocol = { path = "../../protocol", package = "axon-protocol" } - -[dev-dependencies] -rand = "0.7" diff --git a/core/cross-client/Makefile b/core/cross-client/Makefile deleted file mode 100644 index cfc3d7b9d..000000000 --- a/core/cross-client/Makefile +++ /dev/null @@ -1,6 +0,0 @@ -SCHEMA_PATH := src/schemas -SCHEMA_DEST_PATH := src/generated - -schema: - moleculec --language rust --schema-file ${SCHEMA_PATH}/axon.mol > ${SCHEMA_DEST_PATH}/axon.rs - moleculec --language rust --schema-file ${SCHEMA_PATH}/crosschain.mol > ${SCHEMA_DEST_PATH}/crosschain.rs diff --git a/core/cross-client/crosschain_abi.json b/core/cross-client/crosschain_abi.json deleted file mode 100644 index d21a8c5ef..000000000 --- a/core/cross-client/crosschain_abi.json +++ /dev/null @@ -1,650 +0,0 @@ -[ - { - "inputs": [ - { - "internalType": "address", - "name": "metadata", - "type": "address" - }, - { - "internalType": "address", - "name": "wCKB", - "type": "address" - } - ], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "uint256", - "name": "minWCKB", - "type": "uint256" - } - ], - "name": "ChangeMinWCKB", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "address", - "name": "token", - "type": "address" - }, - { - "components": [ - { - "internalType": "uint256", - "name": "feeRatio", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "threshold", - "type": "uint256" - } - ], - "indexed": false, - "internalType": "struct DataType.TokenConfig", - "name": "config", - "type": "tuple" - } - ], - "name": "ChangeTokenConfig", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "address", - "name": "tokenAddress", - "type": "address" - }, - { - "internalType": "uint256", - "name": "sUDTAmount", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "CKBAmount", - "type": "uint256" - }, - { - "internalType": "bytes32", - "name": "txHash", - "type": "bytes32" - } - ], - "indexed": false, - "internalType": "struct DataType.CKBToAxonRecord[]", - "name": "records", - "type": "tuple[]" - } - ], - "name": "CrossFromCKB", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "bytes32", - "name": "currentRecordHash", - "type": "bytes32" - }, - { - "indexed": false, - "internalType": "bytes32[]", - "name": "remainRecordsHash", - "type": "bytes32[]" - } - ], - "name": "CrossLimitRecord", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "string", - "name": "to", - "type": "string" - }, - { - "indexed": false, - "internalType": "address", - "name": "token", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "amount", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "minWCKBAmount", - "type": "uint256" - } - ], - "name": "CrossToCKB", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "string", - "name": "to", - "type": "string" - }, - { - "indexed": false, - "internalType": "address", - "name": "token", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "amount", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "minWCKBAmount", - "type": "uint256" - } - ], - "name": "CrossToCKBAlert", - "type": "event" - }, - { - "inputs": [], - "name": "AT_ADDRESS", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "token", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "typehash", - "type": "bytes32" - } - ], - "name": "addMirrorToken", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "token", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "typehash", - "type": "bytes32" - } - ], - "name": "addToken", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "token", - "type": "address" - } - ], - "name": "addWhitelist", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "address", - "name": "tokenAddress", - "type": "address" - }, - { - "internalType": "uint256", - "name": "amount", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "minWCKBAmount", - "type": "uint256" - }, - { - "internalType": "string", - "name": "to", - "type": "string" - }, - { - "internalType": "uint256", - "name": "limitSign", - "type": "uint256" - } - ], - "internalType": "struct DataType.AxonToCKBRecord", - "name": "record", - "type": "tuple" - } - ], - "name": "approveLimitTx", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "address", - "name": "tokenAddress", - "type": "address" - }, - { - "internalType": "uint256", - "name": "sUDTAmount", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "CKBAmount", - "type": "uint256" - }, - { - "internalType": "bytes32", - "name": "txHash", - "type": "bytes32" - } - ], - "internalType": "struct DataType.CKBToAxonRecord[]", - "name": "records", - "type": "tuple[]" - }, - { - "internalType": "uint256", - "name": "nonce", - "type": "uint256" - } - ], - "name": "crossFromCKB", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "string", - "name": "to", - "type": "string" - }, - { - "internalType": "address", - "name": "token", - "type": "address" - }, - { - "internalType": "uint256", - "name": "amount", - "type": "uint256" - } - ], - "name": "crossTokenToCKB", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "token", - "type": "address" - }, - { - "internalType": "uint256", - "name": "value", - "type": "uint256" - } - ], - "name": "fee", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "typehash", - "type": "bytes32" - } - ], - "name": "getTokenAddress", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "token", - "type": "address" - } - ], - "name": "getTokenConfig", - "outputs": [ - { - "components": [ - { - "internalType": "uint256", - "name": "feeRatio", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "threshold", - "type": "uint256" - } - ], - "internalType": "struct DataType.TokenConfig", - "name": "", - "type": "tuple" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "token", - "type": "address" - } - ], - "name": "getTypehash", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "getWCKBAddress", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "getWCKBMin", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "token", - "type": "address" - } - ], - "name": "isMirrorToken", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "token", - "type": "address" - } - ], - "name": "isWhitelist", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "limitTxes", - "outputs": [ - { - "components": [ - { - "internalType": "address", - "name": "tokenAddress", - "type": "address" - }, - { - "internalType": "uint256", - "name": "amount", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "minWCKBAmount", - "type": "uint256" - }, - { - "internalType": "string", - "name": "to", - "type": "string" - }, - { - "internalType": "uint256", - "name": "limitSign", - "type": "uint256" - } - ], - "internalType": "struct DataType.AxonToCKBRecord[]", - "name": "", - "type": "tuple[]" - }, - { - "internalType": "bytes32[]", - "name": "", - "type": "bytes32[]" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "string", - "name": "to", - "type": "string" - } - ], - "name": "lockAT", - "outputs": [], - "stateMutability": "payable", - "type": "function" - }, - { - "inputs": [], - "name": "mirrorTokens", - "outputs": [ - { - "internalType": "address[]", - "name": "", - "type": "address[]" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "token", - "type": "address" - } - ], - "name": "removeWhitelist", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "token", - "type": "address" - }, - { - "components": [ - { - "internalType": "uint256", - "name": "feeRatio", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "threshold", - "type": "uint256" - } - ], - "internalType": "struct DataType.TokenConfig", - "name": "config", - "type": "tuple" - } - ], - "name": "setTokenConfig", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "amount", - "type": "uint256" - } - ], - "name": "setWCKBMin", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "whitelist", - "outputs": [ - { - "internalType": "address[]", - "name": "", - "type": "address[]" - } - ], - "stateMutability": "view", - "type": "function" - } -] diff --git a/core/cross-client/src/abi/crosschain_abi.rs b/core/cross-client/src/abi/crosschain_abi.rs deleted file mode 100644 index fc6af4522..000000000 --- a/core/cross-client/src/abi/crosschain_abi.rs +++ /dev/null @@ -1,1111 +0,0 @@ -pub use crosschain::*; -#[allow(clippy::too_many_arguments, non_camel_case_types)] -pub mod crosschain { - #![allow(clippy::enum_variant_names)] - #![allow(dead_code)] - #![allow(clippy::type_complexity)] - #![allow(unused_imports)] - use ethers_contract::{ - builders::{ContractCall, Event}, - Contract, Lazy, - }; - use ethers_core::{ - abi::{Abi, Detokenize, InvalidOutputType, Token, Tokenizable}, - types::*, - }; - use ethers_providers::Middleware; - #[doc = "crosschain was auto-generated with ethers-rs Abigen. More information at: https://github.com/gakonst/ethers-rs"] - use std::sync::Arc; - # [rustfmt::skip] const __ABI : & str = "[\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"metadata\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"wCKB\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"constructor\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"minWCKB\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"ChangeMinWCKB\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": false,\n \"internalType\": \"address\",\n \"name\": \"token\",\n \"type\": \"address\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"feeRatio\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n }\n ],\n \"indexed\": false,\n \"internalType\": \"struct DataType.TokenConfig\",\n \"name\": \"config\",\n \"type\": \"tuple\"\n }\n ],\n \"name\": \"ChangeTokenConfig\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"components\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"tokenAddress\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"sUDTAmount\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"CKBAmount\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"indexed\": false,\n \"internalType\": \"struct DataType.CKBToAxonRecord[]\",\n \"name\": \"records\",\n \"type\": \"tuple[]\"\n }\n ],\n \"name\": \"CrossFromCKB\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": false,\n \"internalType\": \"bytes32\",\n \"name\": \"currentRecordHash\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"bytes32[]\",\n \"name\": \"remainRecordsHash\",\n \"type\": \"bytes32[]\"\n }\n ],\n \"name\": \"CrossLimitRecord\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": false,\n \"internalType\": \"string\",\n \"name\": \"to\",\n \"type\": \"string\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"address\",\n \"name\": \"token\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"amount\",\n \"type\": \"uint256\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"minWCKBAmount\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"CrossToCKB\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": false,\n \"internalType\": \"string\",\n \"name\": \"to\",\n \"type\": \"string\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"address\",\n \"name\": \"token\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"amount\",\n \"type\": \"uint256\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"minWCKBAmount\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"CrossToCKBAlert\",\n \"type\": \"event\"\n },\n {\n \"inputs\": [],\n \"name\": \"AT_ADDRESS\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"token\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"typehash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"addMirrorToken\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"token\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"typehash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"addToken\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"token\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"addWhitelist\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"components\": [\n {\n \"internalType\": \"address\",\n \"name\": \"tokenAddress\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"amount\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"minWCKBAmount\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"string\",\n \"name\": \"to\",\n \"type\": \"string\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"limitSign\",\n \"type\": \"uint256\"\n }\n ],\n \"internalType\": \"struct DataType.AxonToCKBRecord\",\n \"name\": \"record\",\n \"type\": \"tuple\"\n }\n ],\n \"name\": \"approveLimitTx\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"components\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"tokenAddress\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"sUDTAmount\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"CKBAmount\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"internalType\": \"struct DataType.CKBToAxonRecord[]\",\n \"name\": \"records\",\n \"type\": \"tuple[]\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"nonce\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"crossFromCKB\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"string\",\n \"name\": \"to\",\n \"type\": \"string\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"token\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"amount\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"crossTokenToCKB\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"token\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"fee\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"typehash\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"getTokenAddress\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"token\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"getTokenConfig\",\n \"outputs\": [\n {\n \"components\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"feeRatio\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n }\n ],\n \"internalType\": \"struct DataType.TokenConfig\",\n \"name\": \"\",\n \"type\": \"tuple\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"token\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"getTypehash\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"getWCKBAddress\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"getWCKBMin\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"token\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"isMirrorToken\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"token\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"isWhitelist\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"limitTxes\",\n \"outputs\": [\n {\n \"components\": [\n {\n \"internalType\": \"address\",\n \"name\": \"tokenAddress\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"amount\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"minWCKBAmount\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"string\",\n \"name\": \"to\",\n \"type\": \"string\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"limitSign\",\n \"type\": \"uint256\"\n }\n ],\n \"internalType\": \"struct DataType.AxonToCKBRecord[]\",\n \"name\": \"\",\n \"type\": \"tuple[]\"\n },\n {\n \"internalType\": \"bytes32[]\",\n \"name\": \"\",\n \"type\": \"bytes32[]\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"string\",\n \"name\": \"to\",\n \"type\": \"string\"\n }\n ],\n \"name\": \"lockAT\",\n \"outputs\": [],\n \"stateMutability\": \"payable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"mirrorTokens\",\n \"outputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"\",\n \"type\": \"address[]\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"token\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"removeWhitelist\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"token\",\n \"type\": \"address\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"feeRatio\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"threshold\",\n \"type\": \"uint256\"\n }\n ],\n \"internalType\": \"struct DataType.TokenConfig\",\n \"name\": \"config\",\n \"type\": \"tuple\"\n }\n ],\n \"name\": \"setTokenConfig\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"amount\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"setWCKBMin\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"whitelist\",\n \"outputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"\",\n \"type\": \"address[]\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n }\n]\n" ; - #[doc = r" The parsed JSON-ABI of the contract."] - pub static CROSSCHAIN_ABI: ethers_contract::Lazy = - ethers_contract::Lazy::new(|| { - ethers_core::utils::__serde_json::from_str(__ABI).expect("invalid abi") - }); - pub struct crosschain(ethers_contract::Contract); - impl Clone for crosschain { - fn clone(&self) -> Self { - crosschain(self.0.clone()) - } - } - impl std::ops::Deref for crosschain { - type Target = ethers_contract::Contract; - - fn deref(&self) -> &Self::Target { - &self.0 - } - } - impl std::fmt::Debug for crosschain { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - f.debug_tuple(stringify!(crosschain)) - .field(&self.address()) - .finish() - } - } - impl crosschain { - #[doc = r" Creates a new contract instance with the specified `ethers`"] - #[doc = r" client at the given `Address`. The contract derefs to a `ethers::Contract`"] - #[doc = r" object"] - pub fn new>( - address: T, - client: ::std::sync::Arc, - ) -> Self { - ethers_contract::Contract::new(address.into(), CROSSCHAIN_ABI.clone(), client).into() - } - - #[doc = "Calls the contract's `AT_ADDRESS` (0x540f6dec) function"] - pub fn at_address( - &self, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([84, 15, 109, 236], ()) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `addMirrorToken` (0x65744d24) function"] - pub fn add_mirror_token( - &self, - token: ethers_core::types::Address, - typehash: [u8; 32], - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([101, 116, 77, 36], (token, typehash)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `addToken` (0xc0c1eebc) function"] - pub fn add_token( - &self, - token: ethers_core::types::Address, - typehash: [u8; 32], - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([192, 193, 238, 188], (token, typehash)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `addWhitelist` (0xf80f5dd5) function"] - pub fn add_whitelist( - &self, - token: ethers_core::types::Address, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([248, 15, 93, 213], token) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `approveLimitTx` (0x78196bd6) function"] - pub fn approve_limit_tx( - &self, - record: AxonToCKBRecord, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([120, 25, 107, 214], (record,)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `crossFromCKB` (0x6b23fd20) function"] - pub fn cross_from_ckb( - &self, - records: ::std::vec::Vec, - nonce: ethers_core::types::U256, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([107, 35, 253, 32], (records, nonce)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `crossTokenToCKB` (0xb8f564f8) function"] - pub fn cross_token_to_ckb( - &self, - to: String, - token: ethers_core::types::Address, - amount: ethers_core::types::U256, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([184, 245, 100, 248], (to, token, amount)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `fee` (0x9e6eda18) function"] - pub fn fee( - &self, - token: ethers_core::types::Address, - value: ethers_core::types::U256, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([158, 110, 218, 24], (token, value)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `getTokenAddress` (0xb12e4410) function"] - pub fn get_token_address( - &self, - typehash: [u8; 32], - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([177, 46, 68, 16], typehash) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `getTokenConfig` (0xcb67e3b1) function"] - pub fn get_token_config( - &self, - token: ethers_core::types::Address, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([203, 103, 227, 177], token) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `getTypehash` (0xe6c8283e) function"] - pub fn get_typehash( - &self, - token: ethers_core::types::Address, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([230, 200, 40, 62], token) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `getWCKBAddress` (0x2083d267) function"] - pub fn get_wckb_address( - &self, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([32, 131, 210, 103], ()) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `getWCKBMin` (0x19e4d989) function"] - pub fn get_wckb_min( - &self, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([25, 228, 217, 137], ()) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `isMirrorToken` (0xcb6ebb9b) function"] - pub fn is_mirror_token( - &self, - token: ethers_core::types::Address, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([203, 110, 187, 155], token) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `isWhitelist` (0xc683630d) function"] - pub fn is_whitelist( - &self, - token: ethers_core::types::Address, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([198, 131, 99, 13], token) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `limitTxes` (0xbf56fbd0) function"] - pub fn limit_txes( - &self, - ) -> ethers_contract::builders::ContractCall< - M, - (::std::vec::Vec, ::std::vec::Vec<[u8; 32]>), - > { - self.0 - .method_hash([191, 86, 251, 208], ()) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `lockAT` (0xdb2b749f) function"] - pub fn lock_at(&self, to: String) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([219, 43, 116, 159], to) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `mirrorTokens` (0x9938155d) function"] - pub fn mirror_tokens( - &self, - ) -> ethers_contract::builders::ContractCall> - { - self.0 - .method_hash([153, 56, 21, 93], ()) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `removeWhitelist` (0x78c8cda7) function"] - pub fn remove_whitelist( - &self, - token: ethers_core::types::Address, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([120, 200, 205, 167], token) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `setTokenConfig` (0x3edfdbb0) function"] - pub fn set_token_config( - &self, - token: ethers_core::types::Address, - config: TokenConfig, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([62, 223, 219, 176], (token, config)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `setWCKBMin` (0xa938d745) function"] - pub fn set_wckb_min( - &self, - amount: ethers_core::types::U256, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([169, 56, 215, 69], amount) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `whitelist` (0x93e59dc1) function"] - pub fn whitelist( - &self, - ) -> ethers_contract::builders::ContractCall> - { - self.0 - .method_hash([147, 229, 157, 193], ()) - .expect("method not found (this should never happen)") - } - - #[doc = "Gets the contract's `ChangeMinWCKB` event"] - pub fn change_min_wckb_filter( - &self, - ) -> ethers_contract::builders::Event { - self.0.event() - } - - #[doc = "Gets the contract's `ChangeTokenConfig` event"] - pub fn change_token_config_filter( - &self, - ) -> ethers_contract::builders::Event { - self.0.event() - } - - #[doc = "Gets the contract's `CrossFromCKB` event"] - pub fn cross_from_ckb_filter( - &self, - ) -> ethers_contract::builders::Event { - self.0.event() - } - - #[doc = "Gets the contract's `CrossLimitRecord` event"] - pub fn cross_limit_record_filter( - &self, - ) -> ethers_contract::builders::Event { - self.0.event() - } - - #[doc = "Gets the contract's `CrossToCKB` event"] - pub fn cross_to_ckb_filter(&self) -> ethers_contract::builders::Event { - self.0.event() - } - - #[doc = "Gets the contract's `CrossToCKBAlert` event"] - pub fn cross_to_ckb_alert_filter( - &self, - ) -> ethers_contract::builders::Event { - self.0.event() - } - - #[doc = r" Returns an [`Event`](#ethers_contract::builders::Event) builder for all events of this contract"] - pub fn events(&self) -> ethers_contract::builders::Event { - self.0.event_with_filter(Default::default()) - } - } - impl From> for crosschain { - fn from(contract: ethers_contract::Contract) -> Self { - Self(contract) - } - } - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthEvent, ethers_contract::EthDisplay, Default, - )] - #[ethevent(name = "ChangeMinWCKB", abi = "ChangeMinWCKB(uint256)")] - pub struct ChangeMinWCKBFilter { - pub min_wckb: ethers_core::types::U256, - } - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthEvent, ethers_contract::EthDisplay, Default, - )] - #[ethevent( - name = "ChangeTokenConfig", - abi = "ChangeTokenConfig(address,(uint256,uint256))" - )] - pub struct ChangeTokenConfigFilter { - pub token: ethers_core::types::Address, - pub config: TokenConfig, - } - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthEvent, ethers_contract::EthDisplay, Default, - )] - #[ethevent( - name = "CrossFromCKB", - abi = "CrossFromCKB((address,address,uint256,uint256,bytes32)[])" - )] - pub struct CrossFromCKBFilter { - pub records: ::std::vec::Vec, - } - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthEvent, ethers_contract::EthDisplay, Default, - )] - #[ethevent(name = "CrossLimitRecord", abi = "CrossLimitRecord(bytes32,bytes32[])")] - pub struct CrossLimitRecordFilter { - pub current_record_hash: [u8; 32], - pub remain_records_hash: Vec<[u8; 32]>, - } - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthEvent, ethers_contract::EthDisplay, Default, - )] - #[ethevent( - name = "CrossToCKB", - abi = "CrossToCKB(string,address,uint256,uint256)" - )] - pub struct CrossToCKBFilter { - pub to: String, - pub token: ethers_core::types::Address, - pub amount: ethers_core::types::U256, - pub min_wckb_amount: ethers_core::types::U256, - } - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthEvent, ethers_contract::EthDisplay, Default, - )] - #[ethevent( - name = "CrossToCKBAlert", - abi = "CrossToCKBAlert(string,address,uint256,uint256)" - )] - pub struct CrossToCKBAlertFilter { - pub to: String, - pub token: ethers_core::types::Address, - pub amount: ethers_core::types::U256, - pub min_wckb_amount: ethers_core::types::U256, - } - #[derive(Debug, Clone, PartialEq, Eq, ethers_contract::EthAbiType)] - pub enum crosschainEvents { - ChangeMinWCKBFilter(ChangeMinWCKBFilter), - ChangeTokenConfigFilter(ChangeTokenConfigFilter), - CrossFromCKBFilter(CrossFromCKBFilter), - CrossLimitRecordFilter(CrossLimitRecordFilter), - CrossToCKBFilter(CrossToCKBFilter), - CrossToCKBAlertFilter(CrossToCKBAlertFilter), - } - impl ethers_contract::EthLogDecode for crosschainEvents { - fn decode_log( - log: ðers_core::abi::RawLog, - ) -> ::std::result::Result - where - Self: Sized, - { - if let Ok(decoded) = ChangeMinWCKBFilter::decode_log(log) { - return Ok(crosschainEvents::ChangeMinWCKBFilter(decoded)); - } - if let Ok(decoded) = ChangeTokenConfigFilter::decode_log(log) { - return Ok(crosschainEvents::ChangeTokenConfigFilter(decoded)); - } - if let Ok(decoded) = CrossFromCKBFilter::decode_log(log) { - return Ok(crosschainEvents::CrossFromCKBFilter(decoded)); - } - if let Ok(decoded) = CrossLimitRecordFilter::decode_log(log) { - return Ok(crosschainEvents::CrossLimitRecordFilter(decoded)); - } - if let Ok(decoded) = CrossToCKBFilter::decode_log(log) { - return Ok(crosschainEvents::CrossToCKBFilter(decoded)); - } - if let Ok(decoded) = CrossToCKBAlertFilter::decode_log(log) { - return Ok(crosschainEvents::CrossToCKBAlertFilter(decoded)); - } - Err(ethers_core::abi::Error::InvalidData) - } - } - impl ::std::fmt::Display for crosschainEvents { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match self { - crosschainEvents::ChangeMinWCKBFilter(element) => element.fmt(f), - crosschainEvents::ChangeTokenConfigFilter(element) => element.fmt(f), - crosschainEvents::CrossFromCKBFilter(element) => element.fmt(f), - crosschainEvents::CrossLimitRecordFilter(element) => element.fmt(f), - crosschainEvents::CrossToCKBFilter(element) => element.fmt(f), - crosschainEvents::CrossToCKBAlertFilter(element) => element.fmt(f), - } - } - } - #[doc = "Container type for all input parameters for the `AT_ADDRESS` function with signature `AT_ADDRESS()` and selector `[84, 15, 109, 236]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "AT_ADDRESS", abi = "AT_ADDRESS()")] - pub struct AtAddressCall; - #[doc = "Container type for all input parameters for the `addMirrorToken` function with signature `addMirrorToken(address,bytes32)` and selector `[101, 116, 77, 36]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "addMirrorToken", abi = "addMirrorToken(address,bytes32)")] - pub struct AddMirrorTokenCall { - pub token: ethers_core::types::Address, - pub typehash: [u8; 32], - } - #[doc = "Container type for all input parameters for the `addToken` function with signature `addToken(address,bytes32)` and selector `[192, 193, 238, 188]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "addToken", abi = "addToken(address,bytes32)")] - pub struct AddTokenCall { - pub token: ethers_core::types::Address, - pub typehash: [u8; 32], - } - #[doc = "Container type for all input parameters for the `addWhitelist` function with signature `addWhitelist(address)` and selector `[248, 15, 93, 213]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "addWhitelist", abi = "addWhitelist(address)")] - pub struct AddWhitelistCall { - pub token: ethers_core::types::Address, - } - #[doc = "Container type for all input parameters for the `approveLimitTx` function with signature `approveLimitTx((address,uint256,uint256,string,uint256))` and selector `[120, 25, 107, 214]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall( - name = "approveLimitTx", - abi = "approveLimitTx((address,uint256,uint256,string,uint256))" - )] - pub struct ApproveLimitTxCall { - pub record: AxonToCKBRecord, - } - #[doc = "Container type for all input parameters for the `crossFromCKB` function with signature `crossFromCKB((address,address,uint256,uint256,bytes32)[],uint256)` and selector `[107, 35, 253, 32]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall( - name = "crossFromCKB", - abi = "crossFromCKB((address,address,uint256,uint256,bytes32)[],uint256)" - )] - pub struct CrossFromCKBCall { - pub records: ::std::vec::Vec, - pub nonce: ethers_core::types::U256, - } - #[doc = "Container type for all input parameters for the `crossTokenToCKB` function with signature `crossTokenToCKB(string,address,uint256)` and selector `[184, 245, 100, 248]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall( - name = "crossTokenToCKB", - abi = "crossTokenToCKB(string,address,uint256)" - )] - pub struct CrossTokenToCKBCall { - pub to: String, - pub token: ethers_core::types::Address, - pub amount: ethers_core::types::U256, - } - #[doc = "Container type for all input parameters for the `fee` function with signature `fee(address,uint256)` and selector `[158, 110, 218, 24]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "fee", abi = "fee(address,uint256)")] - pub struct FeeCall { - pub token: ethers_core::types::Address, - pub value: ethers_core::types::U256, - } - #[doc = "Container type for all input parameters for the `getTokenAddress` function with signature `getTokenAddress(bytes32)` and selector `[177, 46, 68, 16]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "getTokenAddress", abi = "getTokenAddress(bytes32)")] - pub struct GetTokenAddressCall { - pub typehash: [u8; 32], - } - #[doc = "Container type for all input parameters for the `getTokenConfig` function with signature `getTokenConfig(address)` and selector `[203, 103, 227, 177]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "getTokenConfig", abi = "getTokenConfig(address)")] - pub struct GetTokenConfigCall { - pub token: ethers_core::types::Address, - } - #[doc = "Container type for all input parameters for the `getTypehash` function with signature `getTypehash(address)` and selector `[230, 200, 40, 62]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "getTypehash", abi = "getTypehash(address)")] - pub struct GetTypehashCall { - pub token: ethers_core::types::Address, - } - #[doc = "Container type for all input parameters for the `getWCKBAddress` function with signature `getWCKBAddress()` and selector `[32, 131, 210, 103]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "getWCKBAddress", abi = "getWCKBAddress()")] - pub struct GetWCKBAddressCall; - #[doc = "Container type for all input parameters for the `getWCKBMin` function with signature `getWCKBMin()` and selector `[25, 228, 217, 137]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "getWCKBMin", abi = "getWCKBMin()")] - pub struct GetWCKBMinCall; - #[doc = "Container type for all input parameters for the `isMirrorToken` function with signature `isMirrorToken(address)` and selector `[203, 110, 187, 155]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "isMirrorToken", abi = "isMirrorToken(address)")] - pub struct IsMirrorTokenCall { - pub token: ethers_core::types::Address, - } - #[doc = "Container type for all input parameters for the `isWhitelist` function with signature `isWhitelist(address)` and selector `[198, 131, 99, 13]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "isWhitelist", abi = "isWhitelist(address)")] - pub struct IsWhitelistCall { - pub token: ethers_core::types::Address, - } - #[doc = "Container type for all input parameters for the `limitTxes` function with signature `limitTxes()` and selector `[191, 86, 251, 208]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "limitTxes", abi = "limitTxes()")] - pub struct LimitTxesCall; - #[doc = "Container type for all input parameters for the `lockAT` function with signature `lockAT(string)` and selector `[219, 43, 116, 159]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "lockAT", abi = "lockAT(string)")] - pub struct LockATCall { - pub to: String, - } - #[doc = "Container type for all input parameters for the `mirrorTokens` function with signature `mirrorTokens()` and selector `[153, 56, 21, 93]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "mirrorTokens", abi = "mirrorTokens()")] - pub struct MirrorTokensCall; - #[doc = "Container type for all input parameters for the `removeWhitelist` function with signature `removeWhitelist(address)` and selector `[120, 200, 205, 167]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "removeWhitelist", abi = "removeWhitelist(address)")] - pub struct RemoveWhitelistCall { - pub token: ethers_core::types::Address, - } - #[doc = "Container type for all input parameters for the `setTokenConfig` function with signature `setTokenConfig(address,(uint256,uint256))` and selector `[62, 223, 219, 176]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall( - name = "setTokenConfig", - abi = "setTokenConfig(address,(uint256,uint256))" - )] - pub struct SetTokenConfigCall { - pub token: ethers_core::types::Address, - pub config: TokenConfig, - } - #[doc = "Container type for all input parameters for the `setWCKBMin` function with signature `setWCKBMin(uint256)` and selector `[169, 56, 215, 69]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "setWCKBMin", abi = "setWCKBMin(uint256)")] - pub struct SetWCKBMinCall { - pub amount: ethers_core::types::U256, - } - #[doc = "Container type for all input parameters for the `whitelist` function with signature `whitelist()` and selector `[147, 229, 157, 193]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "whitelist", abi = "whitelist()")] - pub struct WhitelistCall; - #[derive(Debug, Clone, PartialEq, Eq, ethers_contract::EthAbiType)] - pub enum crosschainCalls { - AtAddress(AtAddressCall), - AddMirrorToken(AddMirrorTokenCall), - AddToken(AddTokenCall), - AddWhitelist(AddWhitelistCall), - ApproveLimitTx(ApproveLimitTxCall), - CrossFromCKB(CrossFromCKBCall), - CrossTokenToCKB(CrossTokenToCKBCall), - Fee(FeeCall), - GetTokenAddress(GetTokenAddressCall), - GetTokenConfig(GetTokenConfigCall), - GetTypehash(GetTypehashCall), - GetWCKBAddress(GetWCKBAddressCall), - GetWCKBMin(GetWCKBMinCall), - IsMirrorToken(IsMirrorTokenCall), - IsWhitelist(IsWhitelistCall), - LimitTxes(LimitTxesCall), - LockAT(LockATCall), - MirrorTokens(MirrorTokensCall), - RemoveWhitelist(RemoveWhitelistCall), - SetTokenConfig(SetTokenConfigCall), - SetWCKBMin(SetWCKBMinCall), - Whitelist(WhitelistCall), - } - impl ethers_core::abi::AbiDecode for crosschainCalls { - fn decode( - data: impl AsRef<[u8]>, - ) -> ::std::result::Result { - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::AtAddress(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::AddMirrorToken(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::AddToken(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::AddWhitelist(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::ApproveLimitTx(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::CrossFromCKB(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::CrossTokenToCKB(decoded)); - } - if let Ok(decoded) = ::decode(data.as_ref()) { - return Ok(crosschainCalls::Fee(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::GetTokenAddress(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::GetTokenConfig(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::GetTypehash(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::GetWCKBAddress(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::GetWCKBMin(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::IsMirrorToken(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::IsWhitelist(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::LimitTxes(decoded)); - } - if let Ok(decoded) = ::decode(data.as_ref()) - { - return Ok(crosschainCalls::LockAT(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::MirrorTokens(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::RemoveWhitelist(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::SetTokenConfig(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::SetWCKBMin(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(crosschainCalls::Whitelist(decoded)); - } - Err(ethers_core::abi::Error::InvalidData.into()) - } - } - impl ethers_core::abi::AbiEncode for crosschainCalls { - fn encode(self) -> Vec { - match self { - crosschainCalls::AtAddress(element) => element.encode(), - crosschainCalls::AddMirrorToken(element) => element.encode(), - crosschainCalls::AddToken(element) => element.encode(), - crosschainCalls::AddWhitelist(element) => element.encode(), - crosschainCalls::ApproveLimitTx(element) => element.encode(), - crosschainCalls::CrossFromCKB(element) => element.encode(), - crosschainCalls::CrossTokenToCKB(element) => element.encode(), - crosschainCalls::Fee(element) => element.encode(), - crosschainCalls::GetTokenAddress(element) => element.encode(), - crosschainCalls::GetTokenConfig(element) => element.encode(), - crosschainCalls::GetTypehash(element) => element.encode(), - crosschainCalls::GetWCKBAddress(element) => element.encode(), - crosschainCalls::GetWCKBMin(element) => element.encode(), - crosschainCalls::IsMirrorToken(element) => element.encode(), - crosschainCalls::IsWhitelist(element) => element.encode(), - crosschainCalls::LimitTxes(element) => element.encode(), - crosschainCalls::LockAT(element) => element.encode(), - crosschainCalls::MirrorTokens(element) => element.encode(), - crosschainCalls::RemoveWhitelist(element) => element.encode(), - crosschainCalls::SetTokenConfig(element) => element.encode(), - crosschainCalls::SetWCKBMin(element) => element.encode(), - crosschainCalls::Whitelist(element) => element.encode(), - } - } - } - impl ::std::fmt::Display for crosschainCalls { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match self { - crosschainCalls::AtAddress(element) => element.fmt(f), - crosschainCalls::AddMirrorToken(element) => element.fmt(f), - crosschainCalls::AddToken(element) => element.fmt(f), - crosschainCalls::AddWhitelist(element) => element.fmt(f), - crosschainCalls::ApproveLimitTx(element) => element.fmt(f), - crosschainCalls::CrossFromCKB(element) => element.fmt(f), - crosschainCalls::CrossTokenToCKB(element) => element.fmt(f), - crosschainCalls::Fee(element) => element.fmt(f), - crosschainCalls::GetTokenAddress(element) => element.fmt(f), - crosschainCalls::GetTokenConfig(element) => element.fmt(f), - crosschainCalls::GetTypehash(element) => element.fmt(f), - crosschainCalls::GetWCKBAddress(element) => element.fmt(f), - crosschainCalls::GetWCKBMin(element) => element.fmt(f), - crosschainCalls::IsMirrorToken(element) => element.fmt(f), - crosschainCalls::IsWhitelist(element) => element.fmt(f), - crosschainCalls::LimitTxes(element) => element.fmt(f), - crosschainCalls::LockAT(element) => element.fmt(f), - crosschainCalls::MirrorTokens(element) => element.fmt(f), - crosschainCalls::RemoveWhitelist(element) => element.fmt(f), - crosschainCalls::SetTokenConfig(element) => element.fmt(f), - crosschainCalls::SetWCKBMin(element) => element.fmt(f), - crosschainCalls::Whitelist(element) => element.fmt(f), - } - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: AtAddressCall) -> Self { - crosschainCalls::AtAddress(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: AddMirrorTokenCall) -> Self { - crosschainCalls::AddMirrorToken(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: AddTokenCall) -> Self { - crosschainCalls::AddToken(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: AddWhitelistCall) -> Self { - crosschainCalls::AddWhitelist(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: ApproveLimitTxCall) -> Self { - crosschainCalls::ApproveLimitTx(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: CrossFromCKBCall) -> Self { - crosschainCalls::CrossFromCKB(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: CrossTokenToCKBCall) -> Self { - crosschainCalls::CrossTokenToCKB(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: FeeCall) -> Self { - crosschainCalls::Fee(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: GetTokenAddressCall) -> Self { - crosschainCalls::GetTokenAddress(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: GetTokenConfigCall) -> Self { - crosschainCalls::GetTokenConfig(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: GetTypehashCall) -> Self { - crosschainCalls::GetTypehash(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: GetWCKBAddressCall) -> Self { - crosschainCalls::GetWCKBAddress(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: GetWCKBMinCall) -> Self { - crosschainCalls::GetWCKBMin(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: IsMirrorTokenCall) -> Self { - crosschainCalls::IsMirrorToken(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: IsWhitelistCall) -> Self { - crosschainCalls::IsWhitelist(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: LimitTxesCall) -> Self { - crosschainCalls::LimitTxes(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: LockATCall) -> Self { - crosschainCalls::LockAT(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: MirrorTokensCall) -> Self { - crosschainCalls::MirrorTokens(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: RemoveWhitelistCall) -> Self { - crosschainCalls::RemoveWhitelist(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: SetTokenConfigCall) -> Self { - crosschainCalls::SetTokenConfig(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: SetWCKBMinCall) -> Self { - crosschainCalls::SetWCKBMin(var) - } - } - impl ::std::convert::From for crosschainCalls { - fn from(var: WhitelistCall) -> Self { - crosschainCalls::Whitelist(var) - } - } - #[doc = "Container type for all return fields from the `AT_ADDRESS` function with signature `AT_ADDRESS()` and selector `[84, 15, 109, 236]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct AtAddressReturn(pub ethers_core::types::Address); - #[doc = "Container type for all return fields from the `fee` function with signature `fee(address,uint256)` and selector `[158, 110, 218, 24]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct FeeReturn(pub ethers_core::types::U256); - #[doc = "Container type for all return fields from the `getTokenAddress` function with signature `getTokenAddress(bytes32)` and selector `[177, 46, 68, 16]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct GetTokenAddressReturn(pub ethers_core::types::Address); - #[doc = "Container type for all return fields from the `getTokenConfig` function with signature `getTokenConfig(address)` and selector `[203, 103, 227, 177]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct GetTokenConfigReturn(pub TokenConfig); - #[doc = "Container type for all return fields from the `getTypehash` function with signature `getTypehash(address)` and selector `[230, 200, 40, 62]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct GetTypehashReturn(pub [u8; 32]); - #[doc = "Container type for all return fields from the `getWCKBAddress` function with signature `getWCKBAddress()` and selector `[32, 131, 210, 103]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct GetWCKBAddressReturn(pub ethers_core::types::Address); - #[doc = "Container type for all return fields from the `getWCKBMin` function with signature `getWCKBMin()` and selector `[25, 228, 217, 137]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct GetWCKBMinReturn(pub ethers_core::types::U256); - #[doc = "Container type for all return fields from the `isMirrorToken` function with signature `isMirrorToken(address)` and selector `[203, 110, 187, 155]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct IsMirrorTokenReturn(pub bool); - #[doc = "Container type for all return fields from the `isWhitelist` function with signature `isWhitelist(address)` and selector `[198, 131, 99, 13]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct IsWhitelistReturn(pub bool); - #[doc = "Container type for all return fields from the `limitTxes` function with signature `limitTxes()` and selector `[191, 86, 251, 208]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct LimitTxesReturn( - pub ::std::vec::Vec, - pub ::std::vec::Vec<[u8; 32]>, - ); - #[doc = "Container type for all return fields from the `mirrorTokens` function with signature `mirrorTokens()` and selector `[153, 56, 21, 93]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct MirrorTokensReturn(pub ::std::vec::Vec); - #[doc = "Container type for all return fields from the `whitelist` function with signature `whitelist()` and selector `[147, 229, 157, 193]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct WhitelistReturn(pub ::std::vec::Vec); - #[doc = "`AxonToCKBRecord(address,uint256,uint256,string,uint256)`"] - #[derive( - Clone, - Debug, - Default, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - )] - pub struct AxonToCKBRecord { - pub token_address: ethers_core::types::Address, - pub amount: ethers_core::types::U256, - pub min_wckb_amount: ethers_core::types::U256, - pub to: String, - pub limit_sign: ethers_core::types::U256, - } - #[doc = "`CkbtoAxonRecord(address,address,uint256,uint256,bytes32)`"] - #[derive( - Clone, - Debug, - Default, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - )] - pub struct CkbtoAxonRecord { - pub to: ethers_core::types::Address, - pub token_address: ethers_core::types::Address, - pub s_udt_amount: ethers_core::types::U256, - pub ckb_amount: ethers_core::types::U256, - pub tx_hash: [u8; 32], - } - #[doc = "`TokenConfig(uint256,uint256)`"] - #[derive( - Clone, - Debug, - Default, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - )] - pub struct TokenConfig { - pub fee_ratio: ethers_core::types::U256, - pub threshold: ethers_core::types::U256, - } -} diff --git a/core/cross-client/src/abi/mod.rs b/core/cross-client/src/abi/mod.rs deleted file mode 100644 index 110c12e6e..000000000 --- a/core/cross-client/src/abi/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod crosschain_abi; -pub mod wckb_abi; diff --git a/core/cross-client/src/abi/wckb_abi.rs b/core/cross-client/src/abi/wckb_abi.rs deleted file mode 100644 index 3fab2f73d..000000000 --- a/core/cross-client/src/abi/wckb_abi.rs +++ /dev/null @@ -1,1159 +0,0 @@ -pub use wckb::*; -#[allow(clippy::too_many_arguments, non_camel_case_types)] -pub mod wckb { - #![allow(clippy::enum_variant_names)] - #![allow(dead_code)] - #![allow(clippy::type_complexity)] - #![allow(unused_imports)] - use ethers_contract::{ - builders::{ContractCall, Event}, - Contract, Lazy, - }; - use ethers_core::{ - abi::{Abi, Detokenize, InvalidOutputType, Token, Tokenizable}, - types::*, - }; - use ethers_providers::Middleware; - #[doc = "wckb was auto-generated with ethers-rs Abigen. More information at: https://github.com/gakonst/ethers-rs"] - use std::sync::Arc; - # [rustfmt::skip] const __ABI : & str = "[\n {\n \"inputs\": [\n {\n \"internalType\": \"string\",\n \"name\": \"name\",\n \"type\": \"string\"\n },\n {\n \"internalType\": \"string\",\n \"name\": \"symbol\",\n \"type\": \"string\"\n },\n {\n \"internalType\": \"uint8\",\n \"name\": \"decimals_\",\n \"type\": \"uint8\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"constructor\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"owner\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"spender\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"Approval\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"previousOwner\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"newOwner\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"OwnershipTransferred\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"role\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"previousAdminRole\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"newAdminRole\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"RoleAdminChanged\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"role\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"account\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"sender\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"RoleGranted\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"bytes32\",\n \"name\": \"role\",\n \"type\": \"bytes32\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"account\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"sender\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"RoleRevoked\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"from\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"Transfer\",\n \"type\": \"event\"\n },\n {\n \"inputs\": [],\n \"name\": \"DEFAULT_ADMIN_ROLE\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"MANAGER_ROLE\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"owner\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"spender\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"allowance\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"spender\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"amount\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"approve\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"account\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"balanceOf\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"from\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"amount\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"burn\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"decimals\",\n \"outputs\": [\n {\n \"internalType\": \"uint8\",\n \"name\": \"\",\n \"type\": \"uint8\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"spender\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"subtractedValue\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"decreaseAllowance\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"role\",\n \"type\": \"bytes32\"\n }\n ],\n \"name\": \"getRoleAdmin\",\n \"outputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"role\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"account\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"grantRole\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"role\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"account\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"hasRole\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"spender\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"addedValue\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"increaseAllowance\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"amount\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"mint\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"name\",\n \"outputs\": [\n {\n \"internalType\": \"string\",\n \"name\": \"\",\n \"type\": \"string\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"owner\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"renounceOwnership\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"role\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"account\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"renounceRole\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"role\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"account\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"revokeRole\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes4\",\n \"name\": \"interfaceId\",\n \"type\": \"bytes4\"\n }\n ],\n \"name\": \"supportsInterface\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"symbol\",\n \"outputs\": [\n {\n \"internalType\": \"string\",\n \"name\": \"\",\n \"type\": \"string\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"totalSupply\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"amount\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"transfer\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"from\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"amount\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"transferFrom\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"newOwner\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"transferOwnership\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n }\n]\n" ; - #[doc = r" The parsed JSON-ABI of the contract."] - pub static WCKB_ABI: ethers_contract::Lazy = - ethers_contract::Lazy::new(|| { - ethers_core::utils::__serde_json::from_str(__ABI).expect("invalid abi") - }); - pub struct wckb(ethers_contract::Contract); - impl Clone for wckb { - fn clone(&self) -> Self { - wckb(self.0.clone()) - } - } - impl std::ops::Deref for wckb { - type Target = ethers_contract::Contract; - - fn deref(&self) -> &Self::Target { - &self.0 - } - } - impl std::fmt::Debug for wckb { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - f.debug_tuple(stringify!(wckb)) - .field(&self.address()) - .finish() - } - } - impl wckb { - #[doc = r" Creates a new contract instance with the specified `ethers`"] - #[doc = r" client at the given `Address`. The contract derefs to a `ethers::Contract`"] - #[doc = r" object"] - pub fn new>( - address: T, - client: ::std::sync::Arc, - ) -> Self { - ethers_contract::Contract::new(address.into(), WCKB_ABI.clone(), client).into() - } - - #[doc = "Calls the contract's `DEFAULT_ADMIN_ROLE` (0xa217fddf) function"] - pub fn default_admin_role(&self) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([162, 23, 253, 223], ()) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `MANAGER_ROLE` (0xec87621c) function"] - pub fn manager_role(&self) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([236, 135, 98, 28], ()) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `allowance` (0xdd62ed3e) function"] - pub fn allowance( - &self, - owner: ethers_core::types::Address, - spender: ethers_core::types::Address, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([221, 98, 237, 62], (owner, spender)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `approve` (0x095ea7b3) function"] - pub fn approve( - &self, - spender: ethers_core::types::Address, - amount: ethers_core::types::U256, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([9, 94, 167, 179], (spender, amount)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `balanceOf` (0x70a08231) function"] - pub fn balance_of( - &self, - account: ethers_core::types::Address, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([112, 160, 130, 49], account) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `burn` (0x9dc29fac) function"] - pub fn burn( - &self, - from: ethers_core::types::Address, - amount: ethers_core::types::U256, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([157, 194, 159, 172], (from, amount)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `decimals` (0x313ce567) function"] - pub fn decimals(&self) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([49, 60, 229, 103], ()) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `decreaseAllowance` (0xa457c2d7) function"] - pub fn decrease_allowance( - &self, - spender: ethers_core::types::Address, - subtracted_value: ethers_core::types::U256, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([164, 87, 194, 215], (spender, subtracted_value)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `getRoleAdmin` (0x248a9ca3) function"] - pub fn get_role_admin( - &self, - role: [u8; 32], - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([36, 138, 156, 163], role) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `grantRole` (0x2f2ff15d) function"] - pub fn grant_role( - &self, - role: [u8; 32], - account: ethers_core::types::Address, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([47, 47, 241, 93], (role, account)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `hasRole` (0x91d14854) function"] - pub fn has_role( - &self, - role: [u8; 32], - account: ethers_core::types::Address, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([145, 209, 72, 84], (role, account)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `increaseAllowance` (0x39509351) function"] - pub fn increase_allowance( - &self, - spender: ethers_core::types::Address, - added_value: ethers_core::types::U256, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([57, 80, 147, 81], (spender, added_value)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `mint` (0x40c10f19) function"] - pub fn mint( - &self, - to: ethers_core::types::Address, - amount: ethers_core::types::U256, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([64, 193, 15, 25], (to, amount)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `name` (0x06fdde03) function"] - pub fn name(&self) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([6, 253, 222, 3], ()) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `owner` (0x8da5cb5b) function"] - pub fn owner( - &self, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([141, 165, 203, 91], ()) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `renounceOwnership` (0x715018a6) function"] - pub fn renounce_ownership(&self) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([113, 80, 24, 166], ()) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `renounceRole` (0x36568abe) function"] - pub fn renounce_role( - &self, - role: [u8; 32], - account: ethers_core::types::Address, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([54, 86, 138, 190], (role, account)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `revokeRole` (0xd547741f) function"] - pub fn revoke_role( - &self, - role: [u8; 32], - account: ethers_core::types::Address, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([213, 71, 116, 31], (role, account)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `supportsInterface` (0x01ffc9a7) function"] - pub fn supports_interface( - &self, - interface_id: [u8; 4], - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([1, 255, 201, 167], interface_id) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `symbol` (0x95d89b41) function"] - pub fn symbol(&self) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([149, 216, 155, 65], ()) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `totalSupply` (0x18160ddd) function"] - pub fn total_supply( - &self, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([24, 22, 13, 221], ()) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `transfer` (0xa9059cbb) function"] - pub fn transfer( - &self, - to: ethers_core::types::Address, - amount: ethers_core::types::U256, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([169, 5, 156, 187], (to, amount)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `transferFrom` (0x23b872dd) function"] - pub fn transfer_from( - &self, - from: ethers_core::types::Address, - to: ethers_core::types::Address, - amount: ethers_core::types::U256, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([35, 184, 114, 221], (from, to, amount)) - .expect("method not found (this should never happen)") - } - - #[doc = "Calls the contract's `transferOwnership` (0xf2fde38b) function"] - pub fn transfer_ownership( - &self, - new_owner: ethers_core::types::Address, - ) -> ethers_contract::builders::ContractCall { - self.0 - .method_hash([242, 253, 227, 139], new_owner) - .expect("method not found (this should never happen)") - } - - #[doc = "Gets the contract's `Approval` event"] - pub fn approval_filter(&self) -> ethers_contract::builders::Event { - self.0.event() - } - - #[doc = "Gets the contract's `OwnershipTransferred` event"] - pub fn ownership_transferred_filter( - &self, - ) -> ethers_contract::builders::Event { - self.0.event() - } - - #[doc = "Gets the contract's `RoleAdminChanged` event"] - pub fn role_admin_changed_filter( - &self, - ) -> ethers_contract::builders::Event { - self.0.event() - } - - #[doc = "Gets the contract's `RoleGranted` event"] - pub fn role_granted_filter( - &self, - ) -> ethers_contract::builders::Event { - self.0.event() - } - - #[doc = "Gets the contract's `RoleRevoked` event"] - pub fn role_revoked_filter( - &self, - ) -> ethers_contract::builders::Event { - self.0.event() - } - - #[doc = "Gets the contract's `Transfer` event"] - pub fn transfer_filter(&self) -> ethers_contract::builders::Event { - self.0.event() - } - - #[doc = r" Returns an [`Event`](#ethers_contract::builders::Event) builder for all events of this contract"] - pub fn events(&self) -> ethers_contract::builders::Event { - self.0.event_with_filter(Default::default()) - } - } - impl From> for wckb { - fn from(contract: ethers_contract::Contract) -> Self { - Self(contract) - } - } - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthEvent, ethers_contract::EthDisplay, Default, - )] - #[ethevent(name = "Approval", abi = "Approval(address,address,uint256)")] - pub struct ApprovalFilter { - #[ethevent(indexed)] - pub owner: ethers_core::types::Address, - #[ethevent(indexed)] - pub spender: ethers_core::types::Address, - pub value: ethers_core::types::U256, - } - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthEvent, ethers_contract::EthDisplay, Default, - )] - #[ethevent( - name = "OwnershipTransferred", - abi = "OwnershipTransferred(address,address)" - )] - pub struct OwnershipTransferredFilter { - #[ethevent(indexed)] - pub previous_owner: ethers_core::types::Address, - #[ethevent(indexed)] - pub new_owner: ethers_core::types::Address, - } - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthEvent, ethers_contract::EthDisplay, Default, - )] - #[ethevent( - name = "RoleAdminChanged", - abi = "RoleAdminChanged(bytes32,bytes32,bytes32)" - )] - pub struct RoleAdminChangedFilter { - #[ethevent(indexed)] - pub role: [u8; 32], - #[ethevent(indexed)] - pub previous_admin_role: [u8; 32], - #[ethevent(indexed)] - pub new_admin_role: [u8; 32], - } - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthEvent, ethers_contract::EthDisplay, Default, - )] - #[ethevent(name = "RoleGranted", abi = "RoleGranted(bytes32,address,address)")] - pub struct RoleGrantedFilter { - #[ethevent(indexed)] - pub role: [u8; 32], - #[ethevent(indexed)] - pub account: ethers_core::types::Address, - #[ethevent(indexed)] - pub sender: ethers_core::types::Address, - } - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthEvent, ethers_contract::EthDisplay, Default, - )] - #[ethevent(name = "RoleRevoked", abi = "RoleRevoked(bytes32,address,address)")] - pub struct RoleRevokedFilter { - #[ethevent(indexed)] - pub role: [u8; 32], - #[ethevent(indexed)] - pub account: ethers_core::types::Address, - #[ethevent(indexed)] - pub sender: ethers_core::types::Address, - } - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthEvent, ethers_contract::EthDisplay, Default, - )] - #[ethevent(name = "Transfer", abi = "Transfer(address,address,uint256)")] - pub struct TransferFilter { - #[ethevent(indexed)] - pub from: ethers_core::types::Address, - #[ethevent(indexed)] - pub to: ethers_core::types::Address, - pub value: ethers_core::types::U256, - } - #[derive(Debug, Clone, PartialEq, Eq, ethers_contract::EthAbiType)] - pub enum wckbEvents { - ApprovalFilter(ApprovalFilter), - OwnershipTransferredFilter(OwnershipTransferredFilter), - RoleAdminChangedFilter(RoleAdminChangedFilter), - RoleGrantedFilter(RoleGrantedFilter), - RoleRevokedFilter(RoleRevokedFilter), - TransferFilter(TransferFilter), - } - impl ethers_contract::EthLogDecode for wckbEvents { - fn decode_log( - log: ðers_core::abi::RawLog, - ) -> ::std::result::Result - where - Self: Sized, - { - if let Ok(decoded) = ApprovalFilter::decode_log(log) { - return Ok(wckbEvents::ApprovalFilter(decoded)); - } - if let Ok(decoded) = OwnershipTransferredFilter::decode_log(log) { - return Ok(wckbEvents::OwnershipTransferredFilter(decoded)); - } - if let Ok(decoded) = RoleAdminChangedFilter::decode_log(log) { - return Ok(wckbEvents::RoleAdminChangedFilter(decoded)); - } - if let Ok(decoded) = RoleGrantedFilter::decode_log(log) { - return Ok(wckbEvents::RoleGrantedFilter(decoded)); - } - if let Ok(decoded) = RoleRevokedFilter::decode_log(log) { - return Ok(wckbEvents::RoleRevokedFilter(decoded)); - } - if let Ok(decoded) = TransferFilter::decode_log(log) { - return Ok(wckbEvents::TransferFilter(decoded)); - } - Err(ethers_core::abi::Error::InvalidData) - } - } - impl ::std::fmt::Display for wckbEvents { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match self { - wckbEvents::ApprovalFilter(element) => element.fmt(f), - wckbEvents::OwnershipTransferredFilter(element) => element.fmt(f), - wckbEvents::RoleAdminChangedFilter(element) => element.fmt(f), - wckbEvents::RoleGrantedFilter(element) => element.fmt(f), - wckbEvents::RoleRevokedFilter(element) => element.fmt(f), - wckbEvents::TransferFilter(element) => element.fmt(f), - } - } - } - #[doc = "Container type for all input parameters for the `DEFAULT_ADMIN_ROLE` function with signature `DEFAULT_ADMIN_ROLE()` and selector `[162, 23, 253, 223]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "DEFAULT_ADMIN_ROLE", abi = "DEFAULT_ADMIN_ROLE()")] - pub struct DefaultAdminRoleCall; - #[doc = "Container type for all input parameters for the `MANAGER_ROLE` function with signature `MANAGER_ROLE()` and selector `[236, 135, 98, 28]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "MANAGER_ROLE", abi = "MANAGER_ROLE()")] - pub struct ManagerRoleCall; - #[doc = "Container type for all input parameters for the `allowance` function with signature `allowance(address,address)` and selector `[221, 98, 237, 62]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "allowance", abi = "allowance(address,address)")] - pub struct AllowanceCall { - pub owner: ethers_core::types::Address, - pub spender: ethers_core::types::Address, - } - #[doc = "Container type for all input parameters for the `approve` function with signature `approve(address,uint256)` and selector `[9, 94, 167, 179]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "approve", abi = "approve(address,uint256)")] - pub struct ApproveCall { - pub spender: ethers_core::types::Address, - pub amount: ethers_core::types::U256, - } - #[doc = "Container type for all input parameters for the `balanceOf` function with signature `balanceOf(address)` and selector `[112, 160, 130, 49]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "balanceOf", abi = "balanceOf(address)")] - pub struct BalanceOfCall { - pub account: ethers_core::types::Address, - } - #[doc = "Container type for all input parameters for the `burn` function with signature `burn(address,uint256)` and selector `[157, 194, 159, 172]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "burn", abi = "burn(address,uint256)")] - pub struct BurnCall { - pub from: ethers_core::types::Address, - pub amount: ethers_core::types::U256, - } - #[doc = "Container type for all input parameters for the `decimals` function with signature `decimals()` and selector `[49, 60, 229, 103]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "decimals", abi = "decimals()")] - pub struct DecimalsCall; - #[doc = "Container type for all input parameters for the `decreaseAllowance` function with signature `decreaseAllowance(address,uint256)` and selector `[164, 87, 194, 215]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "decreaseAllowance", abi = "decreaseAllowance(address,uint256)")] - pub struct DecreaseAllowanceCall { - pub spender: ethers_core::types::Address, - pub subtracted_value: ethers_core::types::U256, - } - #[doc = "Container type for all input parameters for the `getRoleAdmin` function with signature `getRoleAdmin(bytes32)` and selector `[36, 138, 156, 163]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "getRoleAdmin", abi = "getRoleAdmin(bytes32)")] - pub struct GetRoleAdminCall { - pub role: [u8; 32], - } - #[doc = "Container type for all input parameters for the `grantRole` function with signature `grantRole(bytes32,address)` and selector `[47, 47, 241, 93]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "grantRole", abi = "grantRole(bytes32,address)")] - pub struct GrantRoleCall { - pub role: [u8; 32], - pub account: ethers_core::types::Address, - } - #[doc = "Container type for all input parameters for the `hasRole` function with signature `hasRole(bytes32,address)` and selector `[145, 209, 72, 84]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "hasRole", abi = "hasRole(bytes32,address)")] - pub struct HasRoleCall { - pub role: [u8; 32], - pub account: ethers_core::types::Address, - } - #[doc = "Container type for all input parameters for the `increaseAllowance` function with signature `increaseAllowance(address,uint256)` and selector `[57, 80, 147, 81]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "increaseAllowance", abi = "increaseAllowance(address,uint256)")] - pub struct IncreaseAllowanceCall { - pub spender: ethers_core::types::Address, - pub added_value: ethers_core::types::U256, - } - #[doc = "Container type for all input parameters for the `mint` function with signature `mint(address,uint256)` and selector `[64, 193, 15, 25]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "mint", abi = "mint(address,uint256)")] - pub struct MintCall { - pub to: ethers_core::types::Address, - pub amount: ethers_core::types::U256, - } - #[doc = "Container type for all input parameters for the `name` function with signature `name()` and selector `[6, 253, 222, 3]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "name", abi = "name()")] - pub struct NameCall; - #[doc = "Container type for all input parameters for the `owner` function with signature `owner()` and selector `[141, 165, 203, 91]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "owner", abi = "owner()")] - pub struct OwnerCall; - #[doc = "Container type for all input parameters for the `renounceOwnership` function with signature `renounceOwnership()` and selector `[113, 80, 24, 166]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "renounceOwnership", abi = "renounceOwnership()")] - pub struct RenounceOwnershipCall; - #[doc = "Container type for all input parameters for the `renounceRole` function with signature `renounceRole(bytes32,address)` and selector `[54, 86, 138, 190]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "renounceRole", abi = "renounceRole(bytes32,address)")] - pub struct RenounceRoleCall { - pub role: [u8; 32], - pub account: ethers_core::types::Address, - } - #[doc = "Container type for all input parameters for the `revokeRole` function with signature `revokeRole(bytes32,address)` and selector `[213, 71, 116, 31]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "revokeRole", abi = "revokeRole(bytes32,address)")] - pub struct RevokeRoleCall { - pub role: [u8; 32], - pub account: ethers_core::types::Address, - } - #[doc = "Container type for all input parameters for the `supportsInterface` function with signature `supportsInterface(bytes4)` and selector `[1, 255, 201, 167]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "supportsInterface", abi = "supportsInterface(bytes4)")] - pub struct SupportsInterfaceCall { - pub interface_id: [u8; 4], - } - #[doc = "Container type for all input parameters for the `symbol` function with signature `symbol()` and selector `[149, 216, 155, 65]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "symbol", abi = "symbol()")] - pub struct SymbolCall; - #[doc = "Container type for all input parameters for the `totalSupply` function with signature `totalSupply()` and selector `[24, 22, 13, 221]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "totalSupply", abi = "totalSupply()")] - pub struct TotalSupplyCall; - #[doc = "Container type for all input parameters for the `transfer` function with signature `transfer(address,uint256)` and selector `[169, 5, 156, 187]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "transfer", abi = "transfer(address,uint256)")] - pub struct TransferCall { - pub to: ethers_core::types::Address, - pub amount: ethers_core::types::U256, - } - #[doc = "Container type for all input parameters for the `transferFrom` function with signature `transferFrom(address,address,uint256)` and selector `[35, 184, 114, 221]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "transferFrom", abi = "transferFrom(address,address,uint256)")] - pub struct TransferFromCall { - pub from: ethers_core::types::Address, - pub to: ethers_core::types::Address, - pub amount: ethers_core::types::U256, - } - #[doc = "Container type for all input parameters for the `transferOwnership` function with signature `transferOwnership(address)` and selector `[242, 253, 227, 139]`"] - #[derive( - Clone, Debug, Eq, PartialEq, ethers_contract::EthCall, ethers_contract::EthDisplay, Default, - )] - #[ethcall(name = "transferOwnership", abi = "transferOwnership(address)")] - pub struct TransferOwnershipCall { - pub new_owner: ethers_core::types::Address, - } - #[derive(Debug, Clone, PartialEq, Eq, ethers_contract::EthAbiType)] - pub enum wckbCalls { - DefaultAdminRole(DefaultAdminRoleCall), - ManagerRole(ManagerRoleCall), - Allowance(AllowanceCall), - Approve(ApproveCall), - BalanceOf(BalanceOfCall), - Burn(BurnCall), - Decimals(DecimalsCall), - DecreaseAllowance(DecreaseAllowanceCall), - GetRoleAdmin(GetRoleAdminCall), - GrantRole(GrantRoleCall), - HasRole(HasRoleCall), - IncreaseAllowance(IncreaseAllowanceCall), - Mint(MintCall), - Name(NameCall), - Owner(OwnerCall), - RenounceOwnership(RenounceOwnershipCall), - RenounceRole(RenounceRoleCall), - RevokeRole(RevokeRoleCall), - SupportsInterface(SupportsInterfaceCall), - Symbol(SymbolCall), - TotalSupply(TotalSupplyCall), - Transfer(TransferCall), - TransferFrom(TransferFromCall), - TransferOwnership(TransferOwnershipCall), - } - impl ethers_core::abi::AbiDecode for wckbCalls { - fn decode( - data: impl AsRef<[u8]>, - ) -> ::std::result::Result { - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::DefaultAdminRole(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::ManagerRole(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::Allowance(decoded)); - } - if let Ok(decoded) = ::decode(data.as_ref()) - { - return Ok(wckbCalls::Approve(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::BalanceOf(decoded)); - } - if let Ok(decoded) = ::decode(data.as_ref()) { - return Ok(wckbCalls::Burn(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::Decimals(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::DecreaseAllowance(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::GetRoleAdmin(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::GrantRole(decoded)); - } - if let Ok(decoded) = ::decode(data.as_ref()) - { - return Ok(wckbCalls::HasRole(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::IncreaseAllowance(decoded)); - } - if let Ok(decoded) = ::decode(data.as_ref()) { - return Ok(wckbCalls::Mint(decoded)); - } - if let Ok(decoded) = ::decode(data.as_ref()) { - return Ok(wckbCalls::Name(decoded)); - } - if let Ok(decoded) = ::decode(data.as_ref()) { - return Ok(wckbCalls::Owner(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::RenounceOwnership(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::RenounceRole(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::RevokeRole(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::SupportsInterface(decoded)); - } - if let Ok(decoded) = ::decode(data.as_ref()) - { - return Ok(wckbCalls::Symbol(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::TotalSupply(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::Transfer(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::TransferFrom(decoded)); - } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(wckbCalls::TransferOwnership(decoded)); - } - Err(ethers_core::abi::Error::InvalidData.into()) - } - } - impl ethers_core::abi::AbiEncode for wckbCalls { - fn encode(self) -> Vec { - match self { - wckbCalls::DefaultAdminRole(element) => element.encode(), - wckbCalls::ManagerRole(element) => element.encode(), - wckbCalls::Allowance(element) => element.encode(), - wckbCalls::Approve(element) => element.encode(), - wckbCalls::BalanceOf(element) => element.encode(), - wckbCalls::Burn(element) => element.encode(), - wckbCalls::Decimals(element) => element.encode(), - wckbCalls::DecreaseAllowance(element) => element.encode(), - wckbCalls::GetRoleAdmin(element) => element.encode(), - wckbCalls::GrantRole(element) => element.encode(), - wckbCalls::HasRole(element) => element.encode(), - wckbCalls::IncreaseAllowance(element) => element.encode(), - wckbCalls::Mint(element) => element.encode(), - wckbCalls::Name(element) => element.encode(), - wckbCalls::Owner(element) => element.encode(), - wckbCalls::RenounceOwnership(element) => element.encode(), - wckbCalls::RenounceRole(element) => element.encode(), - wckbCalls::RevokeRole(element) => element.encode(), - wckbCalls::SupportsInterface(element) => element.encode(), - wckbCalls::Symbol(element) => element.encode(), - wckbCalls::TotalSupply(element) => element.encode(), - wckbCalls::Transfer(element) => element.encode(), - wckbCalls::TransferFrom(element) => element.encode(), - wckbCalls::TransferOwnership(element) => element.encode(), - } - } - } - impl ::std::fmt::Display for wckbCalls { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - match self { - wckbCalls::DefaultAdminRole(element) => element.fmt(f), - wckbCalls::ManagerRole(element) => element.fmt(f), - wckbCalls::Allowance(element) => element.fmt(f), - wckbCalls::Approve(element) => element.fmt(f), - wckbCalls::BalanceOf(element) => element.fmt(f), - wckbCalls::Burn(element) => element.fmt(f), - wckbCalls::Decimals(element) => element.fmt(f), - wckbCalls::DecreaseAllowance(element) => element.fmt(f), - wckbCalls::GetRoleAdmin(element) => element.fmt(f), - wckbCalls::GrantRole(element) => element.fmt(f), - wckbCalls::HasRole(element) => element.fmt(f), - wckbCalls::IncreaseAllowance(element) => element.fmt(f), - wckbCalls::Mint(element) => element.fmt(f), - wckbCalls::Name(element) => element.fmt(f), - wckbCalls::Owner(element) => element.fmt(f), - wckbCalls::RenounceOwnership(element) => element.fmt(f), - wckbCalls::RenounceRole(element) => element.fmt(f), - wckbCalls::RevokeRole(element) => element.fmt(f), - wckbCalls::SupportsInterface(element) => element.fmt(f), - wckbCalls::Symbol(element) => element.fmt(f), - wckbCalls::TotalSupply(element) => element.fmt(f), - wckbCalls::Transfer(element) => element.fmt(f), - wckbCalls::TransferFrom(element) => element.fmt(f), - wckbCalls::TransferOwnership(element) => element.fmt(f), - } - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: DefaultAdminRoleCall) -> Self { - wckbCalls::DefaultAdminRole(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: ManagerRoleCall) -> Self { - wckbCalls::ManagerRole(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: AllowanceCall) -> Self { - wckbCalls::Allowance(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: ApproveCall) -> Self { - wckbCalls::Approve(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: BalanceOfCall) -> Self { - wckbCalls::BalanceOf(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: BurnCall) -> Self { - wckbCalls::Burn(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: DecimalsCall) -> Self { - wckbCalls::Decimals(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: DecreaseAllowanceCall) -> Self { - wckbCalls::DecreaseAllowance(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: GetRoleAdminCall) -> Self { - wckbCalls::GetRoleAdmin(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: GrantRoleCall) -> Self { - wckbCalls::GrantRole(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: HasRoleCall) -> Self { - wckbCalls::HasRole(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: IncreaseAllowanceCall) -> Self { - wckbCalls::IncreaseAllowance(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: MintCall) -> Self { - wckbCalls::Mint(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: NameCall) -> Self { - wckbCalls::Name(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: OwnerCall) -> Self { - wckbCalls::Owner(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: RenounceOwnershipCall) -> Self { - wckbCalls::RenounceOwnership(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: RenounceRoleCall) -> Self { - wckbCalls::RenounceRole(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: RevokeRoleCall) -> Self { - wckbCalls::RevokeRole(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: SupportsInterfaceCall) -> Self { - wckbCalls::SupportsInterface(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: SymbolCall) -> Self { - wckbCalls::Symbol(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: TotalSupplyCall) -> Self { - wckbCalls::TotalSupply(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: TransferCall) -> Self { - wckbCalls::Transfer(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: TransferFromCall) -> Self { - wckbCalls::TransferFrom(var) - } - } - impl ::std::convert::From for wckbCalls { - fn from(var: TransferOwnershipCall) -> Self { - wckbCalls::TransferOwnership(var) - } - } - #[doc = "Container type for all return fields from the `DEFAULT_ADMIN_ROLE` function with signature `DEFAULT_ADMIN_ROLE()` and selector `[162, 23, 253, 223]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct DefaultAdminRoleReturn(pub [u8; 32]); - #[doc = "Container type for all return fields from the `MANAGER_ROLE` function with signature `MANAGER_ROLE()` and selector `[236, 135, 98, 28]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct ManagerRoleReturn(pub [u8; 32]); - #[doc = "Container type for all return fields from the `allowance` function with signature `allowance(address,address)` and selector `[221, 98, 237, 62]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct AllowanceReturn(pub ethers_core::types::U256); - #[doc = "Container type for all return fields from the `approve` function with signature `approve(address,uint256)` and selector `[9, 94, 167, 179]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct ApproveReturn(pub bool); - #[doc = "Container type for all return fields from the `balanceOf` function with signature `balanceOf(address)` and selector `[112, 160, 130, 49]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct BalanceOfReturn(pub ethers_core::types::U256); - #[doc = "Container type for all return fields from the `decimals` function with signature `decimals()` and selector `[49, 60, 229, 103]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct DecimalsReturn(pub u8); - #[doc = "Container type for all return fields from the `decreaseAllowance` function with signature `decreaseAllowance(address,uint256)` and selector `[164, 87, 194, 215]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct DecreaseAllowanceReturn(pub bool); - #[doc = "Container type for all return fields from the `getRoleAdmin` function with signature `getRoleAdmin(bytes32)` and selector `[36, 138, 156, 163]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct GetRoleAdminReturn(pub [u8; 32]); - #[doc = "Container type for all return fields from the `hasRole` function with signature `hasRole(bytes32,address)` and selector `[145, 209, 72, 84]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct HasRoleReturn(pub bool); - #[doc = "Container type for all return fields from the `increaseAllowance` function with signature `increaseAllowance(address,uint256)` and selector `[57, 80, 147, 81]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct IncreaseAllowanceReturn(pub bool); - #[doc = "Container type for all return fields from the `name` function with signature `name()` and selector `[6, 253, 222, 3]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct NameReturn(pub String); - #[doc = "Container type for all return fields from the `owner` function with signature `owner()` and selector `[141, 165, 203, 91]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct OwnerReturn(pub ethers_core::types::Address); - #[doc = "Container type for all return fields from the `supportsInterface` function with signature `supportsInterface(bytes4)` and selector `[1, 255, 201, 167]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct SupportsInterfaceReturn(pub bool); - #[doc = "Container type for all return fields from the `symbol` function with signature `symbol()` and selector `[149, 216, 155, 65]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct SymbolReturn(pub String); - #[doc = "Container type for all return fields from the `totalSupply` function with signature `totalSupply()` and selector `[24, 22, 13, 221]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct TotalSupplyReturn(pub ethers_core::types::U256); - #[doc = "Container type for all return fields from the `transfer` function with signature `transfer(address,uint256)` and selector `[169, 5, 156, 187]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct TransferReturn(pub bool); - #[doc = "Container type for all return fields from the `transferFrom` function with signature `transferFrom(address,address,uint256)` and selector `[35, 184, 114, 221]`"] - #[derive( - Clone, - Debug, - Eq, - PartialEq, - ethers_contract::EthAbiType, - ethers_contract::EthAbiCodec, - Default, - )] - pub struct TransferFromReturn(pub bool); -} diff --git a/core/cross-client/src/adapter/db.rs b/core/cross-client/src/adapter/db.rs deleted file mode 100644 index 893a70923..000000000 --- a/core/cross-client/src/adapter/db.rs +++ /dev/null @@ -1,60 +0,0 @@ -use std::{fs, path::Path, sync::Arc}; - -use sled::Db; - -use common_config_parser::types::ConfigRocksDB; -use protocol::ProtocolResult; - -use crate::{adapter::CrossChainDB, error::CrossChainError}; - -#[derive(Clone)] -pub struct CrossChainDBImpl { - db: Arc, -} - -impl CrossChainDB for CrossChainDBImpl { - fn get(&self, key: &[u8]) -> ProtocolResult>> { - Ok(self - .db - .get(key) - .map_err(CrossChainError::from)? - .map(|r| r.to_vec())) - } - - fn get_all(&self) -> ProtocolResult, Vec)>> { - let mut ret: Vec<(Vec, Vec)> = Vec::new(); - - for item in self.db.iter() { - let (key, val) = item.map_err(CrossChainError::from)?; - ret.push(((*key).to_vec(), (*val).to_vec())) - } - - Ok(ret) - } - - fn insert(&self, key: &[u8], val: &[u8]) -> ProtocolResult<()> { - self.db.insert(key, val).map_err(CrossChainError::from)?; - Ok(()) - } - - fn remove(&self, key: &[u8]) -> ProtocolResult<()> { - self.db.remove(key).map_err(CrossChainError::from)?; - Ok(()) - } -} - -impl CrossChainDBImpl { - pub fn new>(path: P, _config: ConfigRocksDB) -> ProtocolResult { - if !path.as_ref().is_dir() { - fs::create_dir_all(&path).map_err(|_| CrossChainError::CreateDB)?; - } - - Ok(CrossChainDBImpl { - db: Arc::new(sled::open(path).map_err(CrossChainError::from)?), - }) - } - - pub fn inner_db(&self) -> Arc { - Arc::clone(&self.db) - } -} diff --git a/core/cross-client/src/adapter/mod.rs b/core/cross-client/src/adapter/mod.rs deleted file mode 100644 index 601272aa0..000000000 --- a/core/cross-client/src/adapter/mod.rs +++ /dev/null @@ -1,222 +0,0 @@ -mod db; - -pub use db::CrossChainDBImpl; - -use std::sync::Arc; - -use ckb_jsonrpc_types::OutputsValidator; -use ckb_types::core::TransactionView; - -use common_crypto::{BlsPublicKey, BlsSignature}; -use core_executor::{AxonExecutor, AxonExecutorAdapter}; -use protocol::traits::{ - Backend, CkbClient, Context, CrossAdapter, Executor, MemPool, MessageTarget, MetadataControl, - Storage, TxAssembler, -}; -use protocol::types::{ - Metadata, RequestTxHashes, SignedTransaction, Transfer, TxResp, H160, H256, U256, -}; -use protocol::{async_trait, lazy::CURRENT_STATE_ROOT, trie, ProtocolResult}; - -pub trait CrossChainDB: Sync + Send { - fn get(&self, key: &[u8]) -> ProtocolResult>>; - - fn get_all(&self) -> ProtocolResult, Vec)>>; - - fn insert(&self, key: &[u8], val: &[u8]) -> ProtocolResult<()>; - - fn remove(&self, key: &[u8]) -> ProtocolResult<()>; -} - -pub struct DefaultCrossChainAdapter { - mempool: Arc, - metadata: Arc, - storage: Arc, - tx_assembler: Arc, - trie_db: Arc, - db: Arc, - ckb_rpc: Arc, -} - -#[async_trait] -impl CrossAdapter - for DefaultCrossChainAdapter -where - M: MemPool + 'static, - D: MetadataControl + 'static, - S: Storage + 'static, - A: TxAssembler + 'static, - TrieDB: trie::DB + 'static, - DB: CrossChainDB + 'static, - Rpc: CkbClient + 'static, -{ - async fn send_axon_tx(&self, ctx: Context, stx: SignedTransaction) -> ProtocolResult<()> { - self.mempool.insert(ctx, stx).await - } - - async fn send_ckb_tx( - &self, - ctx: Context, - tx: ckb_jsonrpc_types::TransactionView, - ) -> ProtocolResult<()> { - log::info!("[cross-chain]: send transaction to ckb {:?}", tx); - - let _hash = self - .ckb_rpc - .send_transaction(ctx, &tx.inner, Some(OutputsValidator::Passthrough)) - .await?; - Ok(()) - } - - async fn insert_in_process(&self, _ctx: Context, key: &[u8], val: &[u8]) -> ProtocolResult<()> { - self.db.insert(key, val) - } - - async fn get_in_process(&self, _ctx: Context, key: &[u8]) -> ProtocolResult>> { - self.db.get(key) - } - - async fn get_all_in_process(&self, _ctx: Context) -> ProtocolResult, Vec)>> { - self.db.get_all() - } - - async fn remove_in_process(&self, _ctx: Context, key: &[u8]) -> ProtocolResult<()> { - self.db.remove(key) - } - - async fn update_monitor_ckb_number(&self, ctx: Context, number: u64) -> ProtocolResult<()> { - self.storage.update_monitor_ckb_number(ctx, number).await - } - - async fn get_monitor_ckb_number(&self, ctx: Context) -> ProtocolResult { - self.storage.get_monitor_ckb_number(ctx).await - } - - async fn nonce(&self, _ctx: Context, address: H160) -> ProtocolResult { - Ok(self.evm_backend()?.basic(address).nonce) - } - - async fn call_evm(&self, ctx: Context, addr: H160, data: Vec) -> ProtocolResult { - let header = self.storage.get_latest_block_header(ctx).await?; - - let backend = AxonExecutorAdapter::from_root( - header.state_root, - Arc::clone(&self.trie_db), - Arc::clone(&self.storage), - (&header).into(), - )?; - - Ok(AxonExecutor::default().call( - &backend, - u64::MAX, - None, - Some(addr), - U256::default(), - data, - )) - } - - async fn insert_record( - &self, - ctx: Context, - reqs: RequestTxHashes, - relay_tx_hash: H256, - ) -> ProtocolResult<()> { - let dir = reqs.direction; - self.storage - .insert_crosschain_records(ctx, reqs, relay_tx_hash, dir) - .await - } - - async fn current_metadata(&self, ctx: Context) -> Metadata { - let number = self - .storage - .get_latest_block_header(ctx.clone()) - .await - .unwrap() - .number; - self.metadata.get_metadata_unchecked(ctx, number) - } - - async fn calc_to_ckb_tx( - &self, - ctx: Context, - transfers: &[Transfer], - ) -> ProtocolResult { - self.tx_assembler - .generate_crosschain_transaction_digest(ctx, transfers) - .await - } - - fn build_to_ckb_tx( - &self, - ctx: Context, - digest: H256, - bls_signature: &BlsSignature, - bls_pubkey_list: &[BlsPublicKey], - ) -> ProtocolResult { - self.tx_assembler.complete_crosschain_transaction( - ctx, - digest, - bls_signature, - bls_pubkey_list, - ) - } - - async fn transmit( - &self, - _ctx: Context, - _msg: Vec, - _end: &str, - _target: MessageTarget, - ) -> ProtocolResult<()> { - Ok(()) - } -} - -impl DefaultCrossChainAdapter -where - M: MemPool + 'static, - D: MetadataControl + 'static, - S: Storage + 'static, - A: TxAssembler + 'static, - TrieDB: trie::DB + 'static, - DB: CrossChainDB + 'static, - Rpc: CkbClient + 'static, -{ - pub async fn new( - mempool: Arc, - metadata: Arc, - storage: Arc, - tx_assembler: Arc, - trie_db: Arc, - db: Arc, - ckb_rpc: Arc, - ) -> Self { - DefaultCrossChainAdapter { - mempool, - metadata, - storage, - tx_assembler, - trie_db, - db, - ckb_rpc, - } - } - - fn evm_backend(&self) -> ProtocolResult> { - AxonExecutorAdapter::from_root( - **CURRENT_STATE_ROOT.load(), - Arc::clone(&self.trie_db), - Arc::clone(&self.storage), - Default::default(), - ) - } -} - -pub fn fixed_array(bytes: &[u8]) -> [u8; LEN] { - assert_eq!(bytes.len(), LEN); - let mut list = [0; LEN]; - list.copy_from_slice(bytes); - list -} diff --git a/core/cross-client/src/error.rs b/core/cross-client/src/error.rs deleted file mode 100644 index 2931dafb0..000000000 --- a/core/cross-client/src/error.rs +++ /dev/null @@ -1,39 +0,0 @@ -use protocol::{Display, ProtocolError, ProtocolErrorKind}; - -#[derive(Debug, Display)] -pub enum CrossChainError { - #[display(fmt = "Rocksdb error {}", _0)] - DB(sled::Error), - - #[display(fmt = "Adapter error {}", _0)] - Adapter(String), - - #[display(fmt = "Create cross chain db error")] - CreateDB, - - #[display(fmt = "Batch length mismatch")] - BatchLengthMismatch, - - #[display(fmt = "Invalid cross direction")] - InvalidDirection, - - #[display(fmt = "Sender error {}", _0)] - Sender(String), - - #[display(fmt = "Crypto error {}", _0)] - Crypto(String), -} - -impl std::error::Error for CrossChainError {} - -impl From for ProtocolError { - fn from(err: CrossChainError) -> ProtocolError { - ProtocolError::new(ProtocolErrorKind::CrossChain, Box::new(err)) - } -} - -impl From for CrossChainError { - fn from(err: sled::Error) -> Self { - CrossChainError::DB(err) - } -} diff --git a/core/cross-client/src/generated/axon.rs b/core/cross-client/src/generated/axon.rs deleted file mode 100644 index fac23dfa6..000000000 --- a/core/cross-client/src/generated/axon.rs +++ /dev/null @@ -1,7560 +0,0 @@ -// Generated by Molecule 0.7.2 - -use molecule::prelude::*; -#[derive(Clone)] -pub struct Byte4(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Byte4 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Byte4 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Byte4 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl ::core::default::Default for Byte4 { - fn default() -> Self { - let v: Vec = vec![0, 0, 0, 0]; - Byte4::new_unchecked(v.into()) - } -} -impl Byte4 { - pub const ITEM_COUNT: usize = 4; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 4; - - pub fn nth0(&self) -> Byte { - Byte::new_unchecked(self.0.slice(0..1)) - } - - pub fn nth1(&self) -> Byte { - Byte::new_unchecked(self.0.slice(1..2)) - } - - pub fn nth2(&self) -> Byte { - Byte::new_unchecked(self.0.slice(2..3)) - } - - pub fn nth3(&self) -> Byte { - Byte::new_unchecked(self.0.slice(3..4)) - } - - pub fn raw_data(&self) -> molecule::bytes::Bytes { - self.as_bytes() - } - - pub fn as_reader<'r>(&'r self) -> Byte4Reader<'r> { - Byte4Reader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Byte4 { - type Builder = Byte4Builder; - - const NAME: &'static str = "Byte4"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Byte4(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Byte4Reader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Byte4Reader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().set([self.nth0(), self.nth1(), self.nth2(), self.nth3()]) - } -} -#[derive(Clone, Copy)] -pub struct Byte4Reader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for Byte4Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for Byte4Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for Byte4Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl<'r> Byte4Reader<'r> { - pub const ITEM_COUNT: usize = 4; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 4; - - pub fn nth0(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[0..1]) - } - - pub fn nth1(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[1..2]) - } - - pub fn nth2(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[2..3]) - } - - pub fn nth3(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[3..4]) - } - - pub fn raw_data(&self) -> &'r [u8] { - self.as_slice() - } -} -impl<'r> molecule::prelude::Reader<'r> for Byte4Reader<'r> { - type Entity = Byte4; - - const NAME: &'static str = "Byte4Reader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - Byte4Reader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len != Self::TOTAL_SIZE { - return ve!(Self, TotalSizeNotMatch, Self::TOTAL_SIZE, slice_len); - } - Ok(()) - } -} -pub struct Byte4Builder(pub(crate) [Byte; 4]); -impl ::core::fmt::Debug for Byte4Builder { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:?})", Self::NAME, &self.0[..]) - } -} -impl ::core::default::Default for Byte4Builder { - fn default() -> Self { - Byte4Builder([ - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - ]) - } -} -impl Byte4Builder { - pub const ITEM_COUNT: usize = 4; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 4; - - pub fn set(mut self, v: [Byte; 4]) -> Self { - self.0 = v; - self - } - - pub fn nth0(mut self, v: Byte) -> Self { - self.0[0] = v; - self - } - - pub fn nth1(mut self, v: Byte) -> Self { - self.0[1] = v; - self - } - - pub fn nth2(mut self, v: Byte) -> Self { - self.0[2] = v; - self - } - - pub fn nth3(mut self, v: Byte) -> Self { - self.0[3] = v; - self - } -} -impl molecule::prelude::Builder for Byte4Builder { - type Entity = Byte4; - - const NAME: &'static str = "Byte4Builder"; - - fn expected_length(&self) -> usize { - Self::TOTAL_SIZE - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - writer.write_all(self.0[0].as_slice())?; - writer.write_all(self.0[1].as_slice())?; - writer.write_all(self.0[2].as_slice())?; - writer.write_all(self.0[3].as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Byte4::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct Byte8(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Byte8 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Byte8 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Byte8 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl ::core::default::Default for Byte8 { - fn default() -> Self { - let v: Vec = vec![0, 0, 0, 0, 0, 0, 0, 0]; - Byte8::new_unchecked(v.into()) - } -} -impl Byte8 { - pub const ITEM_COUNT: usize = 8; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 8; - - pub fn nth0(&self) -> Byte { - Byte::new_unchecked(self.0.slice(0..1)) - } - - pub fn nth1(&self) -> Byte { - Byte::new_unchecked(self.0.slice(1..2)) - } - - pub fn nth2(&self) -> Byte { - Byte::new_unchecked(self.0.slice(2..3)) - } - - pub fn nth3(&self) -> Byte { - Byte::new_unchecked(self.0.slice(3..4)) - } - - pub fn nth4(&self) -> Byte { - Byte::new_unchecked(self.0.slice(4..5)) - } - - pub fn nth5(&self) -> Byte { - Byte::new_unchecked(self.0.slice(5..6)) - } - - pub fn nth6(&self) -> Byte { - Byte::new_unchecked(self.0.slice(6..7)) - } - - pub fn nth7(&self) -> Byte { - Byte::new_unchecked(self.0.slice(7..8)) - } - - pub fn raw_data(&self) -> molecule::bytes::Bytes { - self.as_bytes() - } - - pub fn as_reader<'r>(&'r self) -> Byte8Reader<'r> { - Byte8Reader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Byte8 { - type Builder = Byte8Builder; - - const NAME: &'static str = "Byte8"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Byte8(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Byte8Reader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Byte8Reader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().set([ - self.nth0(), - self.nth1(), - self.nth2(), - self.nth3(), - self.nth4(), - self.nth5(), - self.nth6(), - self.nth7(), - ]) - } -} -#[derive(Clone, Copy)] -pub struct Byte8Reader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for Byte8Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for Byte8Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for Byte8Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl<'r> Byte8Reader<'r> { - pub const ITEM_COUNT: usize = 8; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 8; - - pub fn nth0(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[0..1]) - } - - pub fn nth1(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[1..2]) - } - - pub fn nth2(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[2..3]) - } - - pub fn nth3(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[3..4]) - } - - pub fn nth4(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[4..5]) - } - - pub fn nth5(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[5..6]) - } - - pub fn nth6(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[6..7]) - } - - pub fn nth7(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[7..8]) - } - - pub fn raw_data(&self) -> &'r [u8] { - self.as_slice() - } -} -impl<'r> molecule::prelude::Reader<'r> for Byte8Reader<'r> { - type Entity = Byte8; - - const NAME: &'static str = "Byte8Reader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - Byte8Reader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len != Self::TOTAL_SIZE { - return ve!(Self, TotalSizeNotMatch, Self::TOTAL_SIZE, slice_len); - } - Ok(()) - } -} -pub struct Byte8Builder(pub(crate) [Byte; 8]); -impl ::core::fmt::Debug for Byte8Builder { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:?})", Self::NAME, &self.0[..]) - } -} -impl ::core::default::Default for Byte8Builder { - fn default() -> Self { - Byte8Builder([ - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - ]) - } -} -impl Byte8Builder { - pub const ITEM_COUNT: usize = 8; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 8; - - pub fn set(mut self, v: [Byte; 8]) -> Self { - self.0 = v; - self - } - - pub fn nth0(mut self, v: Byte) -> Self { - self.0[0] = v; - self - } - - pub fn nth1(mut self, v: Byte) -> Self { - self.0[1] = v; - self - } - - pub fn nth2(mut self, v: Byte) -> Self { - self.0[2] = v; - self - } - - pub fn nth3(mut self, v: Byte) -> Self { - self.0[3] = v; - self - } - - pub fn nth4(mut self, v: Byte) -> Self { - self.0[4] = v; - self - } - - pub fn nth5(mut self, v: Byte) -> Self { - self.0[5] = v; - self - } - - pub fn nth6(mut self, v: Byte) -> Self { - self.0[6] = v; - self - } - - pub fn nth7(mut self, v: Byte) -> Self { - self.0[7] = v; - self - } -} -impl molecule::prelude::Builder for Byte8Builder { - type Entity = Byte8; - - const NAME: &'static str = "Byte8Builder"; - - fn expected_length(&self) -> usize { - Self::TOTAL_SIZE - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - writer.write_all(self.0[0].as_slice())?; - writer.write_all(self.0[1].as_slice())?; - writer.write_all(self.0[2].as_slice())?; - writer.write_all(self.0[3].as_slice())?; - writer.write_all(self.0[4].as_slice())?; - writer.write_all(self.0[5].as_slice())?; - writer.write_all(self.0[6].as_slice())?; - writer.write_all(self.0[7].as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Byte8::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct Byte10(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Byte10 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Byte10 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Byte10 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl ::core::default::Default for Byte10 { - fn default() -> Self { - let v: Vec = vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - Byte10::new_unchecked(v.into()) - } -} -impl Byte10 { - pub const ITEM_COUNT: usize = 10; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 10; - - pub fn nth0(&self) -> Byte { - Byte::new_unchecked(self.0.slice(0..1)) - } - - pub fn nth1(&self) -> Byte { - Byte::new_unchecked(self.0.slice(1..2)) - } - - pub fn nth2(&self) -> Byte { - Byte::new_unchecked(self.0.slice(2..3)) - } - - pub fn nth3(&self) -> Byte { - Byte::new_unchecked(self.0.slice(3..4)) - } - - pub fn nth4(&self) -> Byte { - Byte::new_unchecked(self.0.slice(4..5)) - } - - pub fn nth5(&self) -> Byte { - Byte::new_unchecked(self.0.slice(5..6)) - } - - pub fn nth6(&self) -> Byte { - Byte::new_unchecked(self.0.slice(6..7)) - } - - pub fn nth7(&self) -> Byte { - Byte::new_unchecked(self.0.slice(7..8)) - } - - pub fn nth8(&self) -> Byte { - Byte::new_unchecked(self.0.slice(8..9)) - } - - pub fn nth9(&self) -> Byte { - Byte::new_unchecked(self.0.slice(9..10)) - } - - pub fn raw_data(&self) -> molecule::bytes::Bytes { - self.as_bytes() - } - - pub fn as_reader<'r>(&'r self) -> Byte10Reader<'r> { - Byte10Reader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Byte10 { - type Builder = Byte10Builder; - - const NAME: &'static str = "Byte10"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Byte10(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Byte10Reader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Byte10Reader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().set([ - self.nth0(), - self.nth1(), - self.nth2(), - self.nth3(), - self.nth4(), - self.nth5(), - self.nth6(), - self.nth7(), - self.nth8(), - self.nth9(), - ]) - } -} -#[derive(Clone, Copy)] -pub struct Byte10Reader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for Byte10Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for Byte10Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for Byte10Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl<'r> Byte10Reader<'r> { - pub const ITEM_COUNT: usize = 10; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 10; - - pub fn nth0(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[0..1]) - } - - pub fn nth1(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[1..2]) - } - - pub fn nth2(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[2..3]) - } - - pub fn nth3(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[3..4]) - } - - pub fn nth4(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[4..5]) - } - - pub fn nth5(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[5..6]) - } - - pub fn nth6(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[6..7]) - } - - pub fn nth7(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[7..8]) - } - - pub fn nth8(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[8..9]) - } - - pub fn nth9(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[9..10]) - } - - pub fn raw_data(&self) -> &'r [u8] { - self.as_slice() - } -} -impl<'r> molecule::prelude::Reader<'r> for Byte10Reader<'r> { - type Entity = Byte10; - - const NAME: &'static str = "Byte10Reader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - Byte10Reader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len != Self::TOTAL_SIZE { - return ve!(Self, TotalSizeNotMatch, Self::TOTAL_SIZE, slice_len); - } - Ok(()) - } -} -pub struct Byte10Builder(pub(crate) [Byte; 10]); -impl ::core::fmt::Debug for Byte10Builder { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:?})", Self::NAME, &self.0[..]) - } -} -impl ::core::default::Default for Byte10Builder { - fn default() -> Self { - Byte10Builder([ - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - ]) - } -} -impl Byte10Builder { - pub const ITEM_COUNT: usize = 10; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 10; - - pub fn set(mut self, v: [Byte; 10]) -> Self { - self.0 = v; - self - } - - pub fn nth0(mut self, v: Byte) -> Self { - self.0[0] = v; - self - } - - pub fn nth1(mut self, v: Byte) -> Self { - self.0[1] = v; - self - } - - pub fn nth2(mut self, v: Byte) -> Self { - self.0[2] = v; - self - } - - pub fn nth3(mut self, v: Byte) -> Self { - self.0[3] = v; - self - } - - pub fn nth4(mut self, v: Byte) -> Self { - self.0[4] = v; - self - } - - pub fn nth5(mut self, v: Byte) -> Self { - self.0[5] = v; - self - } - - pub fn nth6(mut self, v: Byte) -> Self { - self.0[6] = v; - self - } - - pub fn nth7(mut self, v: Byte) -> Self { - self.0[7] = v; - self - } - - pub fn nth8(mut self, v: Byte) -> Self { - self.0[8] = v; - self - } - - pub fn nth9(mut self, v: Byte) -> Self { - self.0[9] = v; - self - } -} -impl molecule::prelude::Builder for Byte10Builder { - type Entity = Byte10; - - const NAME: &'static str = "Byte10Builder"; - - fn expected_length(&self) -> usize { - Self::TOTAL_SIZE - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - writer.write_all(self.0[0].as_slice())?; - writer.write_all(self.0[1].as_slice())?; - writer.write_all(self.0[2].as_slice())?; - writer.write_all(self.0[3].as_slice())?; - writer.write_all(self.0[4].as_slice())?; - writer.write_all(self.0[5].as_slice())?; - writer.write_all(self.0[6].as_slice())?; - writer.write_all(self.0[7].as_slice())?; - writer.write_all(self.0[8].as_slice())?; - writer.write_all(self.0[9].as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Byte10::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct Byte16(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Byte16 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Byte16 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Byte16 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl ::core::default::Default for Byte16 { - fn default() -> Self { - let v: Vec = vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - Byte16::new_unchecked(v.into()) - } -} -impl Byte16 { - pub const ITEM_COUNT: usize = 16; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 16; - - pub fn nth0(&self) -> Byte { - Byte::new_unchecked(self.0.slice(0..1)) - } - - pub fn nth1(&self) -> Byte { - Byte::new_unchecked(self.0.slice(1..2)) - } - - pub fn nth2(&self) -> Byte { - Byte::new_unchecked(self.0.slice(2..3)) - } - - pub fn nth3(&self) -> Byte { - Byte::new_unchecked(self.0.slice(3..4)) - } - - pub fn nth4(&self) -> Byte { - Byte::new_unchecked(self.0.slice(4..5)) - } - - pub fn nth5(&self) -> Byte { - Byte::new_unchecked(self.0.slice(5..6)) - } - - pub fn nth6(&self) -> Byte { - Byte::new_unchecked(self.0.slice(6..7)) - } - - pub fn nth7(&self) -> Byte { - Byte::new_unchecked(self.0.slice(7..8)) - } - - pub fn nth8(&self) -> Byte { - Byte::new_unchecked(self.0.slice(8..9)) - } - - pub fn nth9(&self) -> Byte { - Byte::new_unchecked(self.0.slice(9..10)) - } - - pub fn nth10(&self) -> Byte { - Byte::new_unchecked(self.0.slice(10..11)) - } - - pub fn nth11(&self) -> Byte { - Byte::new_unchecked(self.0.slice(11..12)) - } - - pub fn nth12(&self) -> Byte { - Byte::new_unchecked(self.0.slice(12..13)) - } - - pub fn nth13(&self) -> Byte { - Byte::new_unchecked(self.0.slice(13..14)) - } - - pub fn nth14(&self) -> Byte { - Byte::new_unchecked(self.0.slice(14..15)) - } - - pub fn nth15(&self) -> Byte { - Byte::new_unchecked(self.0.slice(15..16)) - } - - pub fn raw_data(&self) -> molecule::bytes::Bytes { - self.as_bytes() - } - - pub fn as_reader<'r>(&'r self) -> Byte16Reader<'r> { - Byte16Reader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Byte16 { - type Builder = Byte16Builder; - - const NAME: &'static str = "Byte16"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Byte16(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Byte16Reader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Byte16Reader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().set([ - self.nth0(), - self.nth1(), - self.nth2(), - self.nth3(), - self.nth4(), - self.nth5(), - self.nth6(), - self.nth7(), - self.nth8(), - self.nth9(), - self.nth10(), - self.nth11(), - self.nth12(), - self.nth13(), - self.nth14(), - self.nth15(), - ]) - } -} -#[derive(Clone, Copy)] -pub struct Byte16Reader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for Byte16Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for Byte16Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for Byte16Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl<'r> Byte16Reader<'r> { - pub const ITEM_COUNT: usize = 16; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 16; - - pub fn nth0(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[0..1]) - } - - pub fn nth1(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[1..2]) - } - - pub fn nth2(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[2..3]) - } - - pub fn nth3(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[3..4]) - } - - pub fn nth4(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[4..5]) - } - - pub fn nth5(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[5..6]) - } - - pub fn nth6(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[6..7]) - } - - pub fn nth7(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[7..8]) - } - - pub fn nth8(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[8..9]) - } - - pub fn nth9(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[9..10]) - } - - pub fn nth10(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[10..11]) - } - - pub fn nth11(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[11..12]) - } - - pub fn nth12(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[12..13]) - } - - pub fn nth13(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[13..14]) - } - - pub fn nth14(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[14..15]) - } - - pub fn nth15(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[15..16]) - } - - pub fn raw_data(&self) -> &'r [u8] { - self.as_slice() - } -} -impl<'r> molecule::prelude::Reader<'r> for Byte16Reader<'r> { - type Entity = Byte16; - - const NAME: &'static str = "Byte16Reader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - Byte16Reader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len != Self::TOTAL_SIZE { - return ve!(Self, TotalSizeNotMatch, Self::TOTAL_SIZE, slice_len); - } - Ok(()) - } -} -pub struct Byte16Builder(pub(crate) [Byte; 16]); -impl ::core::fmt::Debug for Byte16Builder { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:?})", Self::NAME, &self.0[..]) - } -} -impl ::core::default::Default for Byte16Builder { - fn default() -> Self { - Byte16Builder([ - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - ]) - } -} -impl Byte16Builder { - pub const ITEM_COUNT: usize = 16; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 16; - - pub fn set(mut self, v: [Byte; 16]) -> Self { - self.0 = v; - self - } - - pub fn nth0(mut self, v: Byte) -> Self { - self.0[0] = v; - self - } - - pub fn nth1(mut self, v: Byte) -> Self { - self.0[1] = v; - self - } - - pub fn nth2(mut self, v: Byte) -> Self { - self.0[2] = v; - self - } - - pub fn nth3(mut self, v: Byte) -> Self { - self.0[3] = v; - self - } - - pub fn nth4(mut self, v: Byte) -> Self { - self.0[4] = v; - self - } - - pub fn nth5(mut self, v: Byte) -> Self { - self.0[5] = v; - self - } - - pub fn nth6(mut self, v: Byte) -> Self { - self.0[6] = v; - self - } - - pub fn nth7(mut self, v: Byte) -> Self { - self.0[7] = v; - self - } - - pub fn nth8(mut self, v: Byte) -> Self { - self.0[8] = v; - self - } - - pub fn nth9(mut self, v: Byte) -> Self { - self.0[9] = v; - self - } - - pub fn nth10(mut self, v: Byte) -> Self { - self.0[10] = v; - self - } - - pub fn nth11(mut self, v: Byte) -> Self { - self.0[11] = v; - self - } - - pub fn nth12(mut self, v: Byte) -> Self { - self.0[12] = v; - self - } - - pub fn nth13(mut self, v: Byte) -> Self { - self.0[13] = v; - self - } - - pub fn nth14(mut self, v: Byte) -> Self { - self.0[14] = v; - self - } - - pub fn nth15(mut self, v: Byte) -> Self { - self.0[15] = v; - self - } -} -impl molecule::prelude::Builder for Byte16Builder { - type Entity = Byte16; - - const NAME: &'static str = "Byte16Builder"; - - fn expected_length(&self) -> usize { - Self::TOTAL_SIZE - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - writer.write_all(self.0[0].as_slice())?; - writer.write_all(self.0[1].as_slice())?; - writer.write_all(self.0[2].as_slice())?; - writer.write_all(self.0[3].as_slice())?; - writer.write_all(self.0[4].as_slice())?; - writer.write_all(self.0[5].as_slice())?; - writer.write_all(self.0[6].as_slice())?; - writer.write_all(self.0[7].as_slice())?; - writer.write_all(self.0[8].as_slice())?; - writer.write_all(self.0[9].as_slice())?; - writer.write_all(self.0[10].as_slice())?; - writer.write_all(self.0[11].as_slice())?; - writer.write_all(self.0[12].as_slice())?; - writer.write_all(self.0[13].as_slice())?; - writer.write_all(self.0[14].as_slice())?; - writer.write_all(self.0[15].as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Byte16::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct Byte20(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Byte20 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Byte20 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Byte20 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl ::core::default::Default for Byte20 { - fn default() -> Self { - let v: Vec = vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - Byte20::new_unchecked(v.into()) - } -} -impl Byte20 { - pub const ITEM_COUNT: usize = 20; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 20; - - pub fn nth0(&self) -> Byte { - Byte::new_unchecked(self.0.slice(0..1)) - } - - pub fn nth1(&self) -> Byte { - Byte::new_unchecked(self.0.slice(1..2)) - } - - pub fn nth2(&self) -> Byte { - Byte::new_unchecked(self.0.slice(2..3)) - } - - pub fn nth3(&self) -> Byte { - Byte::new_unchecked(self.0.slice(3..4)) - } - - pub fn nth4(&self) -> Byte { - Byte::new_unchecked(self.0.slice(4..5)) - } - - pub fn nth5(&self) -> Byte { - Byte::new_unchecked(self.0.slice(5..6)) - } - - pub fn nth6(&self) -> Byte { - Byte::new_unchecked(self.0.slice(6..7)) - } - - pub fn nth7(&self) -> Byte { - Byte::new_unchecked(self.0.slice(7..8)) - } - - pub fn nth8(&self) -> Byte { - Byte::new_unchecked(self.0.slice(8..9)) - } - - pub fn nth9(&self) -> Byte { - Byte::new_unchecked(self.0.slice(9..10)) - } - - pub fn nth10(&self) -> Byte { - Byte::new_unchecked(self.0.slice(10..11)) - } - - pub fn nth11(&self) -> Byte { - Byte::new_unchecked(self.0.slice(11..12)) - } - - pub fn nth12(&self) -> Byte { - Byte::new_unchecked(self.0.slice(12..13)) - } - - pub fn nth13(&self) -> Byte { - Byte::new_unchecked(self.0.slice(13..14)) - } - - pub fn nth14(&self) -> Byte { - Byte::new_unchecked(self.0.slice(14..15)) - } - - pub fn nth15(&self) -> Byte { - Byte::new_unchecked(self.0.slice(15..16)) - } - - pub fn nth16(&self) -> Byte { - Byte::new_unchecked(self.0.slice(16..17)) - } - - pub fn nth17(&self) -> Byte { - Byte::new_unchecked(self.0.slice(17..18)) - } - - pub fn nth18(&self) -> Byte { - Byte::new_unchecked(self.0.slice(18..19)) - } - - pub fn nth19(&self) -> Byte { - Byte::new_unchecked(self.0.slice(19..20)) - } - - pub fn raw_data(&self) -> molecule::bytes::Bytes { - self.as_bytes() - } - - pub fn as_reader<'r>(&'r self) -> Byte20Reader<'r> { - Byte20Reader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Byte20 { - type Builder = Byte20Builder; - - const NAME: &'static str = "Byte20"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Byte20(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Byte20Reader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Byte20Reader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().set([ - self.nth0(), - self.nth1(), - self.nth2(), - self.nth3(), - self.nth4(), - self.nth5(), - self.nth6(), - self.nth7(), - self.nth8(), - self.nth9(), - self.nth10(), - self.nth11(), - self.nth12(), - self.nth13(), - self.nth14(), - self.nth15(), - self.nth16(), - self.nth17(), - self.nth18(), - self.nth19(), - ]) - } -} -#[derive(Clone, Copy)] -pub struct Byte20Reader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for Byte20Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for Byte20Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for Byte20Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl<'r> Byte20Reader<'r> { - pub const ITEM_COUNT: usize = 20; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 20; - - pub fn nth0(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[0..1]) - } - - pub fn nth1(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[1..2]) - } - - pub fn nth2(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[2..3]) - } - - pub fn nth3(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[3..4]) - } - - pub fn nth4(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[4..5]) - } - - pub fn nth5(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[5..6]) - } - - pub fn nth6(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[6..7]) - } - - pub fn nth7(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[7..8]) - } - - pub fn nth8(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[8..9]) - } - - pub fn nth9(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[9..10]) - } - - pub fn nth10(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[10..11]) - } - - pub fn nth11(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[11..12]) - } - - pub fn nth12(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[12..13]) - } - - pub fn nth13(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[13..14]) - } - - pub fn nth14(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[14..15]) - } - - pub fn nth15(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[15..16]) - } - - pub fn nth16(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[16..17]) - } - - pub fn nth17(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[17..18]) - } - - pub fn nth18(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[18..19]) - } - - pub fn nth19(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[19..20]) - } - - pub fn raw_data(&self) -> &'r [u8] { - self.as_slice() - } -} -impl<'r> molecule::prelude::Reader<'r> for Byte20Reader<'r> { - type Entity = Byte20; - - const NAME: &'static str = "Byte20Reader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - Byte20Reader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len != Self::TOTAL_SIZE { - return ve!(Self, TotalSizeNotMatch, Self::TOTAL_SIZE, slice_len); - } - Ok(()) - } -} -pub struct Byte20Builder(pub(crate) [Byte; 20]); -impl ::core::fmt::Debug for Byte20Builder { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:?})", Self::NAME, &self.0[..]) - } -} -impl ::core::default::Default for Byte20Builder { - fn default() -> Self { - Byte20Builder([ - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - ]) - } -} -impl Byte20Builder { - pub const ITEM_COUNT: usize = 20; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 20; - - pub fn set(mut self, v: [Byte; 20]) -> Self { - self.0 = v; - self - } - - pub fn nth0(mut self, v: Byte) -> Self { - self.0[0] = v; - self - } - - pub fn nth1(mut self, v: Byte) -> Self { - self.0[1] = v; - self - } - - pub fn nth2(mut self, v: Byte) -> Self { - self.0[2] = v; - self - } - - pub fn nth3(mut self, v: Byte) -> Self { - self.0[3] = v; - self - } - - pub fn nth4(mut self, v: Byte) -> Self { - self.0[4] = v; - self - } - - pub fn nth5(mut self, v: Byte) -> Self { - self.0[5] = v; - self - } - - pub fn nth6(mut self, v: Byte) -> Self { - self.0[6] = v; - self - } - - pub fn nth7(mut self, v: Byte) -> Self { - self.0[7] = v; - self - } - - pub fn nth8(mut self, v: Byte) -> Self { - self.0[8] = v; - self - } - - pub fn nth9(mut self, v: Byte) -> Self { - self.0[9] = v; - self - } - - pub fn nth10(mut self, v: Byte) -> Self { - self.0[10] = v; - self - } - - pub fn nth11(mut self, v: Byte) -> Self { - self.0[11] = v; - self - } - - pub fn nth12(mut self, v: Byte) -> Self { - self.0[12] = v; - self - } - - pub fn nth13(mut self, v: Byte) -> Self { - self.0[13] = v; - self - } - - pub fn nth14(mut self, v: Byte) -> Self { - self.0[14] = v; - self - } - - pub fn nth15(mut self, v: Byte) -> Self { - self.0[15] = v; - self - } - - pub fn nth16(mut self, v: Byte) -> Self { - self.0[16] = v; - self - } - - pub fn nth17(mut self, v: Byte) -> Self { - self.0[17] = v; - self - } - - pub fn nth18(mut self, v: Byte) -> Self { - self.0[18] = v; - self - } - - pub fn nth19(mut self, v: Byte) -> Self { - self.0[19] = v; - self - } -} -impl molecule::prelude::Builder for Byte20Builder { - type Entity = Byte20; - - const NAME: &'static str = "Byte20Builder"; - - fn expected_length(&self) -> usize { - Self::TOTAL_SIZE - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - writer.write_all(self.0[0].as_slice())?; - writer.write_all(self.0[1].as_slice())?; - writer.write_all(self.0[2].as_slice())?; - writer.write_all(self.0[3].as_slice())?; - writer.write_all(self.0[4].as_slice())?; - writer.write_all(self.0[5].as_slice())?; - writer.write_all(self.0[6].as_slice())?; - writer.write_all(self.0[7].as_slice())?; - writer.write_all(self.0[8].as_slice())?; - writer.write_all(self.0[9].as_slice())?; - writer.write_all(self.0[10].as_slice())?; - writer.write_all(self.0[11].as_slice())?; - writer.write_all(self.0[12].as_slice())?; - writer.write_all(self.0[13].as_slice())?; - writer.write_all(self.0[14].as_slice())?; - writer.write_all(self.0[15].as_slice())?; - writer.write_all(self.0[16].as_slice())?; - writer.write_all(self.0[17].as_slice())?; - writer.write_all(self.0[18].as_slice())?; - writer.write_all(self.0[19].as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Byte20::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct Byte32(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Byte32 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Byte32 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Byte32 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl ::core::default::Default for Byte32 { - fn default() -> Self { - let v: Vec = vec![ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, - ]; - Byte32::new_unchecked(v.into()) - } -} -impl Byte32 { - pub const ITEM_COUNT: usize = 32; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 32; - - pub fn nth0(&self) -> Byte { - Byte::new_unchecked(self.0.slice(0..1)) - } - - pub fn nth1(&self) -> Byte { - Byte::new_unchecked(self.0.slice(1..2)) - } - - pub fn nth2(&self) -> Byte { - Byte::new_unchecked(self.0.slice(2..3)) - } - - pub fn nth3(&self) -> Byte { - Byte::new_unchecked(self.0.slice(3..4)) - } - - pub fn nth4(&self) -> Byte { - Byte::new_unchecked(self.0.slice(4..5)) - } - - pub fn nth5(&self) -> Byte { - Byte::new_unchecked(self.0.slice(5..6)) - } - - pub fn nth6(&self) -> Byte { - Byte::new_unchecked(self.0.slice(6..7)) - } - - pub fn nth7(&self) -> Byte { - Byte::new_unchecked(self.0.slice(7..8)) - } - - pub fn nth8(&self) -> Byte { - Byte::new_unchecked(self.0.slice(8..9)) - } - - pub fn nth9(&self) -> Byte { - Byte::new_unchecked(self.0.slice(9..10)) - } - - pub fn nth10(&self) -> Byte { - Byte::new_unchecked(self.0.slice(10..11)) - } - - pub fn nth11(&self) -> Byte { - Byte::new_unchecked(self.0.slice(11..12)) - } - - pub fn nth12(&self) -> Byte { - Byte::new_unchecked(self.0.slice(12..13)) - } - - pub fn nth13(&self) -> Byte { - Byte::new_unchecked(self.0.slice(13..14)) - } - - pub fn nth14(&self) -> Byte { - Byte::new_unchecked(self.0.slice(14..15)) - } - - pub fn nth15(&self) -> Byte { - Byte::new_unchecked(self.0.slice(15..16)) - } - - pub fn nth16(&self) -> Byte { - Byte::new_unchecked(self.0.slice(16..17)) - } - - pub fn nth17(&self) -> Byte { - Byte::new_unchecked(self.0.slice(17..18)) - } - - pub fn nth18(&self) -> Byte { - Byte::new_unchecked(self.0.slice(18..19)) - } - - pub fn nth19(&self) -> Byte { - Byte::new_unchecked(self.0.slice(19..20)) - } - - pub fn nth20(&self) -> Byte { - Byte::new_unchecked(self.0.slice(20..21)) - } - - pub fn nth21(&self) -> Byte { - Byte::new_unchecked(self.0.slice(21..22)) - } - - pub fn nth22(&self) -> Byte { - Byte::new_unchecked(self.0.slice(22..23)) - } - - pub fn nth23(&self) -> Byte { - Byte::new_unchecked(self.0.slice(23..24)) - } - - pub fn nth24(&self) -> Byte { - Byte::new_unchecked(self.0.slice(24..25)) - } - - pub fn nth25(&self) -> Byte { - Byte::new_unchecked(self.0.slice(25..26)) - } - - pub fn nth26(&self) -> Byte { - Byte::new_unchecked(self.0.slice(26..27)) - } - - pub fn nth27(&self) -> Byte { - Byte::new_unchecked(self.0.slice(27..28)) - } - - pub fn nth28(&self) -> Byte { - Byte::new_unchecked(self.0.slice(28..29)) - } - - pub fn nth29(&self) -> Byte { - Byte::new_unchecked(self.0.slice(29..30)) - } - - pub fn nth30(&self) -> Byte { - Byte::new_unchecked(self.0.slice(30..31)) - } - - pub fn nth31(&self) -> Byte { - Byte::new_unchecked(self.0.slice(31..32)) - } - - pub fn raw_data(&self) -> molecule::bytes::Bytes { - self.as_bytes() - } - - pub fn as_reader<'r>(&'r self) -> Byte32Reader<'r> { - Byte32Reader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Byte32 { - type Builder = Byte32Builder; - - const NAME: &'static str = "Byte32"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Byte32(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Byte32Reader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Byte32Reader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().set([ - self.nth0(), - self.nth1(), - self.nth2(), - self.nth3(), - self.nth4(), - self.nth5(), - self.nth6(), - self.nth7(), - self.nth8(), - self.nth9(), - self.nth10(), - self.nth11(), - self.nth12(), - self.nth13(), - self.nth14(), - self.nth15(), - self.nth16(), - self.nth17(), - self.nth18(), - self.nth19(), - self.nth20(), - self.nth21(), - self.nth22(), - self.nth23(), - self.nth24(), - self.nth25(), - self.nth26(), - self.nth27(), - self.nth28(), - self.nth29(), - self.nth30(), - self.nth31(), - ]) - } -} -#[derive(Clone, Copy)] -pub struct Byte32Reader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for Byte32Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for Byte32Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for Byte32Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl<'r> Byte32Reader<'r> { - pub const ITEM_COUNT: usize = 32; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 32; - - pub fn nth0(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[0..1]) - } - - pub fn nth1(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[1..2]) - } - - pub fn nth2(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[2..3]) - } - - pub fn nth3(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[3..4]) - } - - pub fn nth4(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[4..5]) - } - - pub fn nth5(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[5..6]) - } - - pub fn nth6(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[6..7]) - } - - pub fn nth7(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[7..8]) - } - - pub fn nth8(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[8..9]) - } - - pub fn nth9(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[9..10]) - } - - pub fn nth10(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[10..11]) - } - - pub fn nth11(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[11..12]) - } - - pub fn nth12(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[12..13]) - } - - pub fn nth13(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[13..14]) - } - - pub fn nth14(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[14..15]) - } - - pub fn nth15(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[15..16]) - } - - pub fn nth16(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[16..17]) - } - - pub fn nth17(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[17..18]) - } - - pub fn nth18(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[18..19]) - } - - pub fn nth19(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[19..20]) - } - - pub fn nth20(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[20..21]) - } - - pub fn nth21(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[21..22]) - } - - pub fn nth22(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[22..23]) - } - - pub fn nth23(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[23..24]) - } - - pub fn nth24(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[24..25]) - } - - pub fn nth25(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[25..26]) - } - - pub fn nth26(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[26..27]) - } - - pub fn nth27(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[27..28]) - } - - pub fn nth28(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[28..29]) - } - - pub fn nth29(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[29..30]) - } - - pub fn nth30(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[30..31]) - } - - pub fn nth31(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[31..32]) - } - - pub fn raw_data(&self) -> &'r [u8] { - self.as_slice() - } -} -impl<'r> molecule::prelude::Reader<'r> for Byte32Reader<'r> { - type Entity = Byte32; - - const NAME: &'static str = "Byte32Reader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - Byte32Reader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len != Self::TOTAL_SIZE { - return ve!(Self, TotalSizeNotMatch, Self::TOTAL_SIZE, slice_len); - } - Ok(()) - } -} -pub struct Byte32Builder(pub(crate) [Byte; 32]); -impl ::core::fmt::Debug for Byte32Builder { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:?})", Self::NAME, &self.0[..]) - } -} -impl ::core::default::Default for Byte32Builder { - fn default() -> Self { - Byte32Builder([ - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - ]) - } -} -impl Byte32Builder { - pub const ITEM_COUNT: usize = 32; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 32; - - pub fn set(mut self, v: [Byte; 32]) -> Self { - self.0 = v; - self - } - - pub fn nth0(mut self, v: Byte) -> Self { - self.0[0] = v; - self - } - - pub fn nth1(mut self, v: Byte) -> Self { - self.0[1] = v; - self - } - - pub fn nth2(mut self, v: Byte) -> Self { - self.0[2] = v; - self - } - - pub fn nth3(mut self, v: Byte) -> Self { - self.0[3] = v; - self - } - - pub fn nth4(mut self, v: Byte) -> Self { - self.0[4] = v; - self - } - - pub fn nth5(mut self, v: Byte) -> Self { - self.0[5] = v; - self - } - - pub fn nth6(mut self, v: Byte) -> Self { - self.0[6] = v; - self - } - - pub fn nth7(mut self, v: Byte) -> Self { - self.0[7] = v; - self - } - - pub fn nth8(mut self, v: Byte) -> Self { - self.0[8] = v; - self - } - - pub fn nth9(mut self, v: Byte) -> Self { - self.0[9] = v; - self - } - - pub fn nth10(mut self, v: Byte) -> Self { - self.0[10] = v; - self - } - - pub fn nth11(mut self, v: Byte) -> Self { - self.0[11] = v; - self - } - - pub fn nth12(mut self, v: Byte) -> Self { - self.0[12] = v; - self - } - - pub fn nth13(mut self, v: Byte) -> Self { - self.0[13] = v; - self - } - - pub fn nth14(mut self, v: Byte) -> Self { - self.0[14] = v; - self - } - - pub fn nth15(mut self, v: Byte) -> Self { - self.0[15] = v; - self - } - - pub fn nth16(mut self, v: Byte) -> Self { - self.0[16] = v; - self - } - - pub fn nth17(mut self, v: Byte) -> Self { - self.0[17] = v; - self - } - - pub fn nth18(mut self, v: Byte) -> Self { - self.0[18] = v; - self - } - - pub fn nth19(mut self, v: Byte) -> Self { - self.0[19] = v; - self - } - - pub fn nth20(mut self, v: Byte) -> Self { - self.0[20] = v; - self - } - - pub fn nth21(mut self, v: Byte) -> Self { - self.0[21] = v; - self - } - - pub fn nth22(mut self, v: Byte) -> Self { - self.0[22] = v; - self - } - - pub fn nth23(mut self, v: Byte) -> Self { - self.0[23] = v; - self - } - - pub fn nth24(mut self, v: Byte) -> Self { - self.0[24] = v; - self - } - - pub fn nth25(mut self, v: Byte) -> Self { - self.0[25] = v; - self - } - - pub fn nth26(mut self, v: Byte) -> Self { - self.0[26] = v; - self - } - - pub fn nth27(mut self, v: Byte) -> Self { - self.0[27] = v; - self - } - - pub fn nth28(mut self, v: Byte) -> Self { - self.0[28] = v; - self - } - - pub fn nth29(mut self, v: Byte) -> Self { - self.0[29] = v; - self - } - - pub fn nth30(mut self, v: Byte) -> Self { - self.0[30] = v; - self - } - - pub fn nth31(mut self, v: Byte) -> Self { - self.0[31] = v; - self - } -} -impl molecule::prelude::Builder for Byte32Builder { - type Entity = Byte32; - - const NAME: &'static str = "Byte32Builder"; - - fn expected_length(&self) -> usize { - Self::TOTAL_SIZE - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - writer.write_all(self.0[0].as_slice())?; - writer.write_all(self.0[1].as_slice())?; - writer.write_all(self.0[2].as_slice())?; - writer.write_all(self.0[3].as_slice())?; - writer.write_all(self.0[4].as_slice())?; - writer.write_all(self.0[5].as_slice())?; - writer.write_all(self.0[6].as_slice())?; - writer.write_all(self.0[7].as_slice())?; - writer.write_all(self.0[8].as_slice())?; - writer.write_all(self.0[9].as_slice())?; - writer.write_all(self.0[10].as_slice())?; - writer.write_all(self.0[11].as_slice())?; - writer.write_all(self.0[12].as_slice())?; - writer.write_all(self.0[13].as_slice())?; - writer.write_all(self.0[14].as_slice())?; - writer.write_all(self.0[15].as_slice())?; - writer.write_all(self.0[16].as_slice())?; - writer.write_all(self.0[17].as_slice())?; - writer.write_all(self.0[18].as_slice())?; - writer.write_all(self.0[19].as_slice())?; - writer.write_all(self.0[20].as_slice())?; - writer.write_all(self.0[21].as_slice())?; - writer.write_all(self.0[22].as_slice())?; - writer.write_all(self.0[23].as_slice())?; - writer.write_all(self.0[24].as_slice())?; - writer.write_all(self.0[25].as_slice())?; - writer.write_all(self.0[26].as_slice())?; - writer.write_all(self.0[27].as_slice())?; - writer.write_all(self.0[28].as_slice())?; - writer.write_all(self.0[29].as_slice())?; - writer.write_all(self.0[30].as_slice())?; - writer.write_all(self.0[31].as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Byte32::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct Byte48(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Byte48 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Byte48 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Byte48 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl ::core::default::Default for Byte48 { - fn default() -> Self { - let v: Vec = vec![ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - Byte48::new_unchecked(v.into()) - } -} -impl Byte48 { - pub const ITEM_COUNT: usize = 48; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 48; - - pub fn nth0(&self) -> Byte { - Byte::new_unchecked(self.0.slice(0..1)) - } - - pub fn nth1(&self) -> Byte { - Byte::new_unchecked(self.0.slice(1..2)) - } - - pub fn nth2(&self) -> Byte { - Byte::new_unchecked(self.0.slice(2..3)) - } - - pub fn nth3(&self) -> Byte { - Byte::new_unchecked(self.0.slice(3..4)) - } - - pub fn nth4(&self) -> Byte { - Byte::new_unchecked(self.0.slice(4..5)) - } - - pub fn nth5(&self) -> Byte { - Byte::new_unchecked(self.0.slice(5..6)) - } - - pub fn nth6(&self) -> Byte { - Byte::new_unchecked(self.0.slice(6..7)) - } - - pub fn nth7(&self) -> Byte { - Byte::new_unchecked(self.0.slice(7..8)) - } - - pub fn nth8(&self) -> Byte { - Byte::new_unchecked(self.0.slice(8..9)) - } - - pub fn nth9(&self) -> Byte { - Byte::new_unchecked(self.0.slice(9..10)) - } - - pub fn nth10(&self) -> Byte { - Byte::new_unchecked(self.0.slice(10..11)) - } - - pub fn nth11(&self) -> Byte { - Byte::new_unchecked(self.0.slice(11..12)) - } - - pub fn nth12(&self) -> Byte { - Byte::new_unchecked(self.0.slice(12..13)) - } - - pub fn nth13(&self) -> Byte { - Byte::new_unchecked(self.0.slice(13..14)) - } - - pub fn nth14(&self) -> Byte { - Byte::new_unchecked(self.0.slice(14..15)) - } - - pub fn nth15(&self) -> Byte { - Byte::new_unchecked(self.0.slice(15..16)) - } - - pub fn nth16(&self) -> Byte { - Byte::new_unchecked(self.0.slice(16..17)) - } - - pub fn nth17(&self) -> Byte { - Byte::new_unchecked(self.0.slice(17..18)) - } - - pub fn nth18(&self) -> Byte { - Byte::new_unchecked(self.0.slice(18..19)) - } - - pub fn nth19(&self) -> Byte { - Byte::new_unchecked(self.0.slice(19..20)) - } - - pub fn nth20(&self) -> Byte { - Byte::new_unchecked(self.0.slice(20..21)) - } - - pub fn nth21(&self) -> Byte { - Byte::new_unchecked(self.0.slice(21..22)) - } - - pub fn nth22(&self) -> Byte { - Byte::new_unchecked(self.0.slice(22..23)) - } - - pub fn nth23(&self) -> Byte { - Byte::new_unchecked(self.0.slice(23..24)) - } - - pub fn nth24(&self) -> Byte { - Byte::new_unchecked(self.0.slice(24..25)) - } - - pub fn nth25(&self) -> Byte { - Byte::new_unchecked(self.0.slice(25..26)) - } - - pub fn nth26(&self) -> Byte { - Byte::new_unchecked(self.0.slice(26..27)) - } - - pub fn nth27(&self) -> Byte { - Byte::new_unchecked(self.0.slice(27..28)) - } - - pub fn nth28(&self) -> Byte { - Byte::new_unchecked(self.0.slice(28..29)) - } - - pub fn nth29(&self) -> Byte { - Byte::new_unchecked(self.0.slice(29..30)) - } - - pub fn nth30(&self) -> Byte { - Byte::new_unchecked(self.0.slice(30..31)) - } - - pub fn nth31(&self) -> Byte { - Byte::new_unchecked(self.0.slice(31..32)) - } - - pub fn nth32(&self) -> Byte { - Byte::new_unchecked(self.0.slice(32..33)) - } - - pub fn nth33(&self) -> Byte { - Byte::new_unchecked(self.0.slice(33..34)) - } - - pub fn nth34(&self) -> Byte { - Byte::new_unchecked(self.0.slice(34..35)) - } - - pub fn nth35(&self) -> Byte { - Byte::new_unchecked(self.0.slice(35..36)) - } - - pub fn nth36(&self) -> Byte { - Byte::new_unchecked(self.0.slice(36..37)) - } - - pub fn nth37(&self) -> Byte { - Byte::new_unchecked(self.0.slice(37..38)) - } - - pub fn nth38(&self) -> Byte { - Byte::new_unchecked(self.0.slice(38..39)) - } - - pub fn nth39(&self) -> Byte { - Byte::new_unchecked(self.0.slice(39..40)) - } - - pub fn nth40(&self) -> Byte { - Byte::new_unchecked(self.0.slice(40..41)) - } - - pub fn nth41(&self) -> Byte { - Byte::new_unchecked(self.0.slice(41..42)) - } - - pub fn nth42(&self) -> Byte { - Byte::new_unchecked(self.0.slice(42..43)) - } - - pub fn nth43(&self) -> Byte { - Byte::new_unchecked(self.0.slice(43..44)) - } - - pub fn nth44(&self) -> Byte { - Byte::new_unchecked(self.0.slice(44..45)) - } - - pub fn nth45(&self) -> Byte { - Byte::new_unchecked(self.0.slice(45..46)) - } - - pub fn nth46(&self) -> Byte { - Byte::new_unchecked(self.0.slice(46..47)) - } - - pub fn nth47(&self) -> Byte { - Byte::new_unchecked(self.0.slice(47..48)) - } - - pub fn raw_data(&self) -> molecule::bytes::Bytes { - self.as_bytes() - } - - pub fn as_reader<'r>(&'r self) -> Byte48Reader<'r> { - Byte48Reader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Byte48 { - type Builder = Byte48Builder; - - const NAME: &'static str = "Byte48"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Byte48(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Byte48Reader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Byte48Reader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().set([ - self.nth0(), - self.nth1(), - self.nth2(), - self.nth3(), - self.nth4(), - self.nth5(), - self.nth6(), - self.nth7(), - self.nth8(), - self.nth9(), - self.nth10(), - self.nth11(), - self.nth12(), - self.nth13(), - self.nth14(), - self.nth15(), - self.nth16(), - self.nth17(), - self.nth18(), - self.nth19(), - self.nth20(), - self.nth21(), - self.nth22(), - self.nth23(), - self.nth24(), - self.nth25(), - self.nth26(), - self.nth27(), - self.nth28(), - self.nth29(), - self.nth30(), - self.nth31(), - self.nth32(), - self.nth33(), - self.nth34(), - self.nth35(), - self.nth36(), - self.nth37(), - self.nth38(), - self.nth39(), - self.nth40(), - self.nth41(), - self.nth42(), - self.nth43(), - self.nth44(), - self.nth45(), - self.nth46(), - self.nth47(), - ]) - } -} -#[derive(Clone, Copy)] -pub struct Byte48Reader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for Byte48Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for Byte48Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for Byte48Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl<'r> Byte48Reader<'r> { - pub const ITEM_COUNT: usize = 48; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 48; - - pub fn nth0(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[0..1]) - } - - pub fn nth1(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[1..2]) - } - - pub fn nth2(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[2..3]) - } - - pub fn nth3(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[3..4]) - } - - pub fn nth4(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[4..5]) - } - - pub fn nth5(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[5..6]) - } - - pub fn nth6(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[6..7]) - } - - pub fn nth7(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[7..8]) - } - - pub fn nth8(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[8..9]) - } - - pub fn nth9(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[9..10]) - } - - pub fn nth10(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[10..11]) - } - - pub fn nth11(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[11..12]) - } - - pub fn nth12(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[12..13]) - } - - pub fn nth13(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[13..14]) - } - - pub fn nth14(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[14..15]) - } - - pub fn nth15(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[15..16]) - } - - pub fn nth16(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[16..17]) - } - - pub fn nth17(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[17..18]) - } - - pub fn nth18(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[18..19]) - } - - pub fn nth19(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[19..20]) - } - - pub fn nth20(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[20..21]) - } - - pub fn nth21(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[21..22]) - } - - pub fn nth22(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[22..23]) - } - - pub fn nth23(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[23..24]) - } - - pub fn nth24(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[24..25]) - } - - pub fn nth25(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[25..26]) - } - - pub fn nth26(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[26..27]) - } - - pub fn nth27(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[27..28]) - } - - pub fn nth28(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[28..29]) - } - - pub fn nth29(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[29..30]) - } - - pub fn nth30(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[30..31]) - } - - pub fn nth31(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[31..32]) - } - - pub fn nth32(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[32..33]) - } - - pub fn nth33(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[33..34]) - } - - pub fn nth34(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[34..35]) - } - - pub fn nth35(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[35..36]) - } - - pub fn nth36(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[36..37]) - } - - pub fn nth37(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[37..38]) - } - - pub fn nth38(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[38..39]) - } - - pub fn nth39(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[39..40]) - } - - pub fn nth40(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[40..41]) - } - - pub fn nth41(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[41..42]) - } - - pub fn nth42(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[42..43]) - } - - pub fn nth43(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[43..44]) - } - - pub fn nth44(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[44..45]) - } - - pub fn nth45(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[45..46]) - } - - pub fn nth46(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[46..47]) - } - - pub fn nth47(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[47..48]) - } - - pub fn raw_data(&self) -> &'r [u8] { - self.as_slice() - } -} -impl<'r> molecule::prelude::Reader<'r> for Byte48Reader<'r> { - type Entity = Byte48; - - const NAME: &'static str = "Byte48Reader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - Byte48Reader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len != Self::TOTAL_SIZE { - return ve!(Self, TotalSizeNotMatch, Self::TOTAL_SIZE, slice_len); - } - Ok(()) - } -} -pub struct Byte48Builder(pub(crate) [Byte; 48]); -impl ::core::fmt::Debug for Byte48Builder { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:?})", Self::NAME, &self.0[..]) - } -} -impl ::core::default::Default for Byte48Builder { - fn default() -> Self { - Byte48Builder([ - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - ]) - } -} -impl Byte48Builder { - pub const ITEM_COUNT: usize = 48; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 48; - - pub fn set(mut self, v: [Byte; 48]) -> Self { - self.0 = v; - self - } - - pub fn nth0(mut self, v: Byte) -> Self { - self.0[0] = v; - self - } - - pub fn nth1(mut self, v: Byte) -> Self { - self.0[1] = v; - self - } - - pub fn nth2(mut self, v: Byte) -> Self { - self.0[2] = v; - self - } - - pub fn nth3(mut self, v: Byte) -> Self { - self.0[3] = v; - self - } - - pub fn nth4(mut self, v: Byte) -> Self { - self.0[4] = v; - self - } - - pub fn nth5(mut self, v: Byte) -> Self { - self.0[5] = v; - self - } - - pub fn nth6(mut self, v: Byte) -> Self { - self.0[6] = v; - self - } - - pub fn nth7(mut self, v: Byte) -> Self { - self.0[7] = v; - self - } - - pub fn nth8(mut self, v: Byte) -> Self { - self.0[8] = v; - self - } - - pub fn nth9(mut self, v: Byte) -> Self { - self.0[9] = v; - self - } - - pub fn nth10(mut self, v: Byte) -> Self { - self.0[10] = v; - self - } - - pub fn nth11(mut self, v: Byte) -> Self { - self.0[11] = v; - self - } - - pub fn nth12(mut self, v: Byte) -> Self { - self.0[12] = v; - self - } - - pub fn nth13(mut self, v: Byte) -> Self { - self.0[13] = v; - self - } - - pub fn nth14(mut self, v: Byte) -> Self { - self.0[14] = v; - self - } - - pub fn nth15(mut self, v: Byte) -> Self { - self.0[15] = v; - self - } - - pub fn nth16(mut self, v: Byte) -> Self { - self.0[16] = v; - self - } - - pub fn nth17(mut self, v: Byte) -> Self { - self.0[17] = v; - self - } - - pub fn nth18(mut self, v: Byte) -> Self { - self.0[18] = v; - self - } - - pub fn nth19(mut self, v: Byte) -> Self { - self.0[19] = v; - self - } - - pub fn nth20(mut self, v: Byte) -> Self { - self.0[20] = v; - self - } - - pub fn nth21(mut self, v: Byte) -> Self { - self.0[21] = v; - self - } - - pub fn nth22(mut self, v: Byte) -> Self { - self.0[22] = v; - self - } - - pub fn nth23(mut self, v: Byte) -> Self { - self.0[23] = v; - self - } - - pub fn nth24(mut self, v: Byte) -> Self { - self.0[24] = v; - self - } - - pub fn nth25(mut self, v: Byte) -> Self { - self.0[25] = v; - self - } - - pub fn nth26(mut self, v: Byte) -> Self { - self.0[26] = v; - self - } - - pub fn nth27(mut self, v: Byte) -> Self { - self.0[27] = v; - self - } - - pub fn nth28(mut self, v: Byte) -> Self { - self.0[28] = v; - self - } - - pub fn nth29(mut self, v: Byte) -> Self { - self.0[29] = v; - self - } - - pub fn nth30(mut self, v: Byte) -> Self { - self.0[30] = v; - self - } - - pub fn nth31(mut self, v: Byte) -> Self { - self.0[31] = v; - self - } - - pub fn nth32(mut self, v: Byte) -> Self { - self.0[32] = v; - self - } - - pub fn nth33(mut self, v: Byte) -> Self { - self.0[33] = v; - self - } - - pub fn nth34(mut self, v: Byte) -> Self { - self.0[34] = v; - self - } - - pub fn nth35(mut self, v: Byte) -> Self { - self.0[35] = v; - self - } - - pub fn nth36(mut self, v: Byte) -> Self { - self.0[36] = v; - self - } - - pub fn nth37(mut self, v: Byte) -> Self { - self.0[37] = v; - self - } - - pub fn nth38(mut self, v: Byte) -> Self { - self.0[38] = v; - self - } - - pub fn nth39(mut self, v: Byte) -> Self { - self.0[39] = v; - self - } - - pub fn nth40(mut self, v: Byte) -> Self { - self.0[40] = v; - self - } - - pub fn nth41(mut self, v: Byte) -> Self { - self.0[41] = v; - self - } - - pub fn nth42(mut self, v: Byte) -> Self { - self.0[42] = v; - self - } - - pub fn nth43(mut self, v: Byte) -> Self { - self.0[43] = v; - self - } - - pub fn nth44(mut self, v: Byte) -> Self { - self.0[44] = v; - self - } - - pub fn nth45(mut self, v: Byte) -> Self { - self.0[45] = v; - self - } - - pub fn nth46(mut self, v: Byte) -> Self { - self.0[46] = v; - self - } - - pub fn nth47(mut self, v: Byte) -> Self { - self.0[47] = v; - self - } -} -impl molecule::prelude::Builder for Byte48Builder { - type Entity = Byte48; - - const NAME: &'static str = "Byte48Builder"; - - fn expected_length(&self) -> usize { - Self::TOTAL_SIZE - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - writer.write_all(self.0[0].as_slice())?; - writer.write_all(self.0[1].as_slice())?; - writer.write_all(self.0[2].as_slice())?; - writer.write_all(self.0[3].as_slice())?; - writer.write_all(self.0[4].as_slice())?; - writer.write_all(self.0[5].as_slice())?; - writer.write_all(self.0[6].as_slice())?; - writer.write_all(self.0[7].as_slice())?; - writer.write_all(self.0[8].as_slice())?; - writer.write_all(self.0[9].as_slice())?; - writer.write_all(self.0[10].as_slice())?; - writer.write_all(self.0[11].as_slice())?; - writer.write_all(self.0[12].as_slice())?; - writer.write_all(self.0[13].as_slice())?; - writer.write_all(self.0[14].as_slice())?; - writer.write_all(self.0[15].as_slice())?; - writer.write_all(self.0[16].as_slice())?; - writer.write_all(self.0[17].as_slice())?; - writer.write_all(self.0[18].as_slice())?; - writer.write_all(self.0[19].as_slice())?; - writer.write_all(self.0[20].as_slice())?; - writer.write_all(self.0[21].as_slice())?; - writer.write_all(self.0[22].as_slice())?; - writer.write_all(self.0[23].as_slice())?; - writer.write_all(self.0[24].as_slice())?; - writer.write_all(self.0[25].as_slice())?; - writer.write_all(self.0[26].as_slice())?; - writer.write_all(self.0[27].as_slice())?; - writer.write_all(self.0[28].as_slice())?; - writer.write_all(self.0[29].as_slice())?; - writer.write_all(self.0[30].as_slice())?; - writer.write_all(self.0[31].as_slice())?; - writer.write_all(self.0[32].as_slice())?; - writer.write_all(self.0[33].as_slice())?; - writer.write_all(self.0[34].as_slice())?; - writer.write_all(self.0[35].as_slice())?; - writer.write_all(self.0[36].as_slice())?; - writer.write_all(self.0[37].as_slice())?; - writer.write_all(self.0[38].as_slice())?; - writer.write_all(self.0[39].as_slice())?; - writer.write_all(self.0[40].as_slice())?; - writer.write_all(self.0[41].as_slice())?; - writer.write_all(self.0[42].as_slice())?; - writer.write_all(self.0[43].as_slice())?; - writer.write_all(self.0[44].as_slice())?; - writer.write_all(self.0[45].as_slice())?; - writer.write_all(self.0[46].as_slice())?; - writer.write_all(self.0[47].as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Byte48::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct Identity(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Identity { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Identity { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Identity { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "flag", self.flag())?; - write!(f, ", {}: {}", "content", self.content())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl ::core::default::Default for Identity { - fn default() -> Self { - let v: Vec = vec![ - 33, 0, 0, 0, 12, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - ]; - Identity::new_unchecked(v.into()) - } -} -impl Identity { - pub const FIELD_COUNT: usize = 2; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn flag(&self) -> Byte { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - Byte::new_unchecked(self.0.slice(start..end)) - } - - pub fn content(&self) -> Byte20 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[12..]) as usize; - Byte20::new_unchecked(self.0.slice(start..end)) - } else { - Byte20::new_unchecked(self.0.slice(start..)) - } - } - - pub fn as_reader<'r>(&'r self) -> IdentityReader<'r> { - IdentityReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Identity { - type Builder = IdentityBuilder; - - const NAME: &'static str = "Identity"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Identity(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - IdentityReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - IdentityReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder() - .flag(self.flag()) - .content(self.content()) - } -} -#[derive(Clone, Copy)] -pub struct IdentityReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for IdentityReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for IdentityReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for IdentityReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "flag", self.flag())?; - write!(f, ", {}: {}", "content", self.content())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl<'r> IdentityReader<'r> { - pub const FIELD_COUNT: usize = 2; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn flag(&self) -> ByteReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - ByteReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn content(&self) -> Byte20Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[12..]) as usize; - Byte20Reader::new_unchecked(&self.as_slice()[start..end]) - } else { - Byte20Reader::new_unchecked(&self.as_slice()[start..]) - } - } -} -impl<'r> molecule::prelude::Reader<'r> for IdentityReader<'r> { - type Entity = Identity; - - const NAME: &'static str = "IdentityReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - IdentityReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let total_size = molecule::unpack_number(slice) as usize; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { - return Ok(()); - } - if slice_len < molecule::NUMBER_SIZE * 2 { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); - } - let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { - return ve!(Self, OffsetsNotMatch); - } - if slice_len < offset_first { - return ve!(Self, HeaderIsBroken, offset_first, slice_len); - } - let field_count = offset_first / molecule::NUMBER_SIZE - 1; - if field_count < Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - } else if !compatible && field_count > Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - }; - let mut offsets: Vec = slice[molecule::NUMBER_SIZE..offset_first] - .chunks_exact(molecule::NUMBER_SIZE) - .map(|x| molecule::unpack_number(x) as usize) - .collect(); - offsets.push(total_size); - if offsets.windows(2).any(|i| i[0] > i[1]) { - return ve!(Self, OffsetsNotMatch); - } - ByteReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; - Byte20Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?; - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct IdentityBuilder { - pub(crate) flag: Byte, - pub(crate) content: Byte20, -} -impl IdentityBuilder { - pub const FIELD_COUNT: usize = 2; - - pub fn flag(mut self, v: Byte) -> Self { - self.flag = v; - self - } - - pub fn content(mut self, v: Byte20) -> Self { - self.content = v; - self - } -} -impl molecule::prelude::Builder for IdentityBuilder { - type Entity = Identity; - - const NAME: &'static str = "IdentityBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) - + self.flag.as_slice().len() - + self.content.as_slice().len() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); - let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); - offsets.push(total_size); - total_size += self.flag.as_slice().len(); - offsets.push(total_size); - total_size += self.content.as_slice().len(); - writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; - for offset in offsets.into_iter() { - writer.write_all(&molecule::pack_number(offset as molecule::Number))?; - } - writer.write_all(self.flag.as_slice())?; - writer.write_all(self.content.as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Identity::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct StakeInfo(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for StakeInfo { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for StakeInfo { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for StakeInfo { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "identity", self.identity())?; - write!(f, ", {}: {}", "l2_address", self.l2_address())?; - write!(f, ", {}: {}", "bls_pub_key", self.bls_pub_key())?; - write!(f, ", {}: {}", "stake_amount", self.stake_amount())?; - write!(f, ", {}: {}", "inauguration_era", self.inauguration_era())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl ::core::default::Default for StakeInfo { - fn default() -> Self { - let v: Vec = vec![ - 149, 0, 0, 0, 24, 0, 0, 0, 57, 0, 0, 0, 77, 0, 0, 0, 125, 0, 0, 0, 141, 0, 0, 0, 33, 0, - 0, 0, 12, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - ]; - StakeInfo::new_unchecked(v.into()) - } -} -impl StakeInfo { - pub const FIELD_COUNT: usize = 5; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn identity(&self) -> Identity { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - Identity::new_unchecked(self.0.slice(start..end)) - } - - pub fn l2_address(&self) -> Byte20 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - let end = molecule::unpack_number(&slice[12..]) as usize; - Byte20::new_unchecked(self.0.slice(start..end)) - } - - pub fn bls_pub_key(&self) -> Byte48 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[12..]) as usize; - let end = molecule::unpack_number(&slice[16..]) as usize; - Byte48::new_unchecked(self.0.slice(start..end)) - } - - pub fn stake_amount(&self) -> Byte16 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[16..]) as usize; - let end = molecule::unpack_number(&slice[20..]) as usize; - Byte16::new_unchecked(self.0.slice(start..end)) - } - - pub fn inauguration_era(&self) -> Byte8 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[20..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[24..]) as usize; - Byte8::new_unchecked(self.0.slice(start..end)) - } else { - Byte8::new_unchecked(self.0.slice(start..)) - } - } - - pub fn as_reader<'r>(&'r self) -> StakeInfoReader<'r> { - StakeInfoReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for StakeInfo { - type Builder = StakeInfoBuilder; - - const NAME: &'static str = "StakeInfo"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - StakeInfo(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - StakeInfoReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - StakeInfoReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder() - .identity(self.identity()) - .l2_address(self.l2_address()) - .bls_pub_key(self.bls_pub_key()) - .stake_amount(self.stake_amount()) - .inauguration_era(self.inauguration_era()) - } -} -#[derive(Clone, Copy)] -pub struct StakeInfoReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for StakeInfoReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for StakeInfoReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for StakeInfoReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "identity", self.identity())?; - write!(f, ", {}: {}", "l2_address", self.l2_address())?; - write!(f, ", {}: {}", "bls_pub_key", self.bls_pub_key())?; - write!(f, ", {}: {}", "stake_amount", self.stake_amount())?; - write!(f, ", {}: {}", "inauguration_era", self.inauguration_era())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl<'r> StakeInfoReader<'r> { - pub const FIELD_COUNT: usize = 5; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn identity(&self) -> IdentityReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - IdentityReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn l2_address(&self) -> Byte20Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - let end = molecule::unpack_number(&slice[12..]) as usize; - Byte20Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn bls_pub_key(&self) -> Byte48Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[12..]) as usize; - let end = molecule::unpack_number(&slice[16..]) as usize; - Byte48Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn stake_amount(&self) -> Byte16Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[16..]) as usize; - let end = molecule::unpack_number(&slice[20..]) as usize; - Byte16Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn inauguration_era(&self) -> Byte8Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[20..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[24..]) as usize; - Byte8Reader::new_unchecked(&self.as_slice()[start..end]) - } else { - Byte8Reader::new_unchecked(&self.as_slice()[start..]) - } - } -} -impl<'r> molecule::prelude::Reader<'r> for StakeInfoReader<'r> { - type Entity = StakeInfo; - - const NAME: &'static str = "StakeInfoReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - StakeInfoReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let total_size = molecule::unpack_number(slice) as usize; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { - return Ok(()); - } - if slice_len < molecule::NUMBER_SIZE * 2 { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); - } - let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { - return ve!(Self, OffsetsNotMatch); - } - if slice_len < offset_first { - return ve!(Self, HeaderIsBroken, offset_first, slice_len); - } - let field_count = offset_first / molecule::NUMBER_SIZE - 1; - if field_count < Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - } else if !compatible && field_count > Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - }; - let mut offsets: Vec = slice[molecule::NUMBER_SIZE..offset_first] - .chunks_exact(molecule::NUMBER_SIZE) - .map(|x| molecule::unpack_number(x) as usize) - .collect(); - offsets.push(total_size); - if offsets.windows(2).any(|i| i[0] > i[1]) { - return ve!(Self, OffsetsNotMatch); - } - IdentityReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; - Byte20Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?; - Byte48Reader::verify(&slice[offsets[2]..offsets[3]], compatible)?; - Byte16Reader::verify(&slice[offsets[3]..offsets[4]], compatible)?; - Byte8Reader::verify(&slice[offsets[4]..offsets[5]], compatible)?; - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct StakeInfoBuilder { - pub(crate) identity: Identity, - pub(crate) l2_address: Byte20, - pub(crate) bls_pub_key: Byte48, - pub(crate) stake_amount: Byte16, - pub(crate) inauguration_era: Byte8, -} -impl StakeInfoBuilder { - pub const FIELD_COUNT: usize = 5; - - pub fn identity(mut self, v: Identity) -> Self { - self.identity = v; - self - } - - pub fn l2_address(mut self, v: Byte20) -> Self { - self.l2_address = v; - self - } - - pub fn bls_pub_key(mut self, v: Byte48) -> Self { - self.bls_pub_key = v; - self - } - - pub fn stake_amount(mut self, v: Byte16) -> Self { - self.stake_amount = v; - self - } - - pub fn inauguration_era(mut self, v: Byte8) -> Self { - self.inauguration_era = v; - self - } -} -impl molecule::prelude::Builder for StakeInfoBuilder { - type Entity = StakeInfo; - - const NAME: &'static str = "StakeInfoBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) - + self.identity.as_slice().len() - + self.l2_address.as_slice().len() - + self.bls_pub_key.as_slice().len() - + self.stake_amount.as_slice().len() - + self.inauguration_era.as_slice().len() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); - let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); - offsets.push(total_size); - total_size += self.identity.as_slice().len(); - offsets.push(total_size); - total_size += self.l2_address.as_slice().len(); - offsets.push(total_size); - total_size += self.bls_pub_key.as_slice().len(); - offsets.push(total_size); - total_size += self.stake_amount.as_slice().len(); - offsets.push(total_size); - total_size += self.inauguration_era.as_slice().len(); - writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; - for offset in offsets.into_iter() { - writer.write_all(&molecule::pack_number(offset as molecule::Number))?; - } - writer.write_all(self.identity.as_slice())?; - writer.write_all(self.l2_address.as_slice())?; - writer.write_all(self.bls_pub_key.as_slice())?; - writer.write_all(self.stake_amount.as_slice())?; - writer.write_all(self.inauguration_era.as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - StakeInfo::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct Bytes(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Bytes { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Bytes { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Bytes { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl ::core::default::Default for Bytes { - fn default() -> Self { - let v: Vec = vec![0, 0, 0, 0]; - Bytes::new_unchecked(v.into()) - } -} -impl Bytes { - pub const ITEM_SIZE: usize = 1; - - pub fn total_size(&self) -> usize { - molecule::NUMBER_SIZE + Self::ITEM_SIZE * self.item_count() - } - - pub fn item_count(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn len(&self) -> usize { - self.item_count() - } - - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - pub fn get(&self, idx: usize) -> Option { - if idx >= self.len() { - None - } else { - Some(self.get_unchecked(idx)) - } - } - - pub fn get_unchecked(&self, idx: usize) -> Byte { - let start = molecule::NUMBER_SIZE + Self::ITEM_SIZE * idx; - let end = start + Self::ITEM_SIZE; - Byte::new_unchecked(self.0.slice(start..end)) - } - - pub fn raw_data(&self) -> molecule::bytes::Bytes { - self.0.slice(molecule::NUMBER_SIZE..) - } - - pub fn as_reader<'r>(&'r self) -> BytesReader<'r> { - BytesReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Bytes { - type Builder = BytesBuilder; - - const NAME: &'static str = "Bytes"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Bytes(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - BytesReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - BytesReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().extend(self.into_iter()) - } -} -#[derive(Clone, Copy)] -pub struct BytesReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for BytesReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for BytesReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for BytesReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl<'r> BytesReader<'r> { - pub const ITEM_SIZE: usize = 1; - - pub fn total_size(&self) -> usize { - molecule::NUMBER_SIZE + Self::ITEM_SIZE * self.item_count() - } - - pub fn item_count(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn len(&self) -> usize { - self.item_count() - } - - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - pub fn get(&self, idx: usize) -> Option> { - if idx >= self.len() { - None - } else { - Some(self.get_unchecked(idx)) - } - } - - pub fn get_unchecked(&self, idx: usize) -> ByteReader<'r> { - let start = molecule::NUMBER_SIZE + Self::ITEM_SIZE * idx; - let end = start + Self::ITEM_SIZE; - ByteReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn raw_data(&self) -> &'r [u8] { - &self.as_slice()[molecule::NUMBER_SIZE..] - } -} -impl<'r> molecule::prelude::Reader<'r> for BytesReader<'r> { - type Entity = Bytes; - - const NAME: &'static str = "BytesReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - BytesReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let item_count = molecule::unpack_number(slice) as usize; - if item_count == 0 { - if slice_len != molecule::NUMBER_SIZE { - return ve!(Self, TotalSizeNotMatch, molecule::NUMBER_SIZE, slice_len); - } - return Ok(()); - } - let total_size = molecule::NUMBER_SIZE + Self::ITEM_SIZE * item_count; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct BytesBuilder(pub(crate) Vec); -impl BytesBuilder { - pub const ITEM_SIZE: usize = 1; - - pub fn set(mut self, v: Vec) -> Self { - self.0 = v; - self - } - - pub fn push(mut self, v: Byte) -> Self { - self.0.push(v); - self - } - - pub fn extend>(mut self, iter: T) -> Self { - for elem in iter { - self.0.push(elem); - } - self - } -} -impl molecule::prelude::Builder for BytesBuilder { - type Entity = Bytes; - - const NAME: &'static str = "BytesBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE + Self::ITEM_SIZE * self.0.len() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - writer.write_all(&molecule::pack_number(self.0.len() as molecule::Number))?; - for inner in &self.0[..] { - writer.write_all(inner.as_slice())?; - } - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Bytes::new_unchecked(inner.into()) - } -} -pub struct BytesIterator(Bytes, usize, usize); -impl ::core::iter::Iterator for BytesIterator { - type Item = Byte; - - fn next(&mut self) -> Option { - if self.1 >= self.2 { - None - } else { - let ret = self.0.get_unchecked(self.1); - self.1 += 1; - Some(ret) - } - } -} -impl ::core::iter::ExactSizeIterator for BytesIterator { - fn len(&self) -> usize { - self.2 - self.1 - } -} -impl ::core::iter::IntoIterator for Bytes { - type IntoIter = BytesIterator; - type Item = Byte; - - fn into_iter(self) -> Self::IntoIter { - let len = self.len(); - BytesIterator(self, 0, len) - } -} -#[derive(Clone)] -pub struct StakeInfoVec(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for StakeInfoVec { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for StakeInfoVec { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for StakeInfoVec { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} [", Self::NAME)?; - for i in 0..self.len() { - if i == 0 { - write!(f, "{}", self.get_unchecked(i))?; - } else { - write!(f, ", {}", self.get_unchecked(i))?; - } - } - write!(f, "]") - } -} -impl ::core::default::Default for StakeInfoVec { - fn default() -> Self { - let v: Vec = vec![4, 0, 0, 0]; - StakeInfoVec::new_unchecked(v.into()) - } -} -impl StakeInfoVec { - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn item_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn len(&self) -> usize { - self.item_count() - } - - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - pub fn get(&self, idx: usize) -> Option { - if idx >= self.len() { - None - } else { - Some(self.get_unchecked(idx)) - } - } - - pub fn get_unchecked(&self, idx: usize) -> StakeInfo { - let slice = self.as_slice(); - let start_idx = molecule::NUMBER_SIZE * (1 + idx); - let start = molecule::unpack_number(&slice[start_idx..]) as usize; - if idx == self.len() - 1 { - StakeInfo::new_unchecked(self.0.slice(start..)) - } else { - let end_idx = start_idx + molecule::NUMBER_SIZE; - let end = molecule::unpack_number(&slice[end_idx..]) as usize; - StakeInfo::new_unchecked(self.0.slice(start..end)) - } - } - - pub fn as_reader<'r>(&'r self) -> StakeInfoVecReader<'r> { - StakeInfoVecReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for StakeInfoVec { - type Builder = StakeInfoVecBuilder; - - const NAME: &'static str = "StakeInfoVec"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - StakeInfoVec(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - StakeInfoVecReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - StakeInfoVecReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().extend(self.into_iter()) - } -} -#[derive(Clone, Copy)] -pub struct StakeInfoVecReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for StakeInfoVecReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for StakeInfoVecReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for StakeInfoVecReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} [", Self::NAME)?; - for i in 0..self.len() { - if i == 0 { - write!(f, "{}", self.get_unchecked(i))?; - } else { - write!(f, ", {}", self.get_unchecked(i))?; - } - } - write!(f, "]") - } -} -impl<'r> StakeInfoVecReader<'r> { - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn item_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn len(&self) -> usize { - self.item_count() - } - - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - pub fn get(&self, idx: usize) -> Option> { - if idx >= self.len() { - None - } else { - Some(self.get_unchecked(idx)) - } - } - - pub fn get_unchecked(&self, idx: usize) -> StakeInfoReader<'r> { - let slice = self.as_slice(); - let start_idx = molecule::NUMBER_SIZE * (1 + idx); - let start = molecule::unpack_number(&slice[start_idx..]) as usize; - if idx == self.len() - 1 { - StakeInfoReader::new_unchecked(&self.as_slice()[start..]) - } else { - let end_idx = start_idx + molecule::NUMBER_SIZE; - let end = molecule::unpack_number(&slice[end_idx..]) as usize; - StakeInfoReader::new_unchecked(&self.as_slice()[start..end]) - } - } -} -impl<'r> molecule::prelude::Reader<'r> for StakeInfoVecReader<'r> { - type Entity = StakeInfoVec; - - const NAME: &'static str = "StakeInfoVecReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - StakeInfoVecReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let total_size = molecule::unpack_number(slice) as usize; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - if slice_len == molecule::NUMBER_SIZE { - return Ok(()); - } - if slice_len < molecule::NUMBER_SIZE * 2 { - return ve!( - Self, - TotalSizeNotMatch, - molecule::NUMBER_SIZE * 2, - slice_len - ); - } - let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { - return ve!(Self, OffsetsNotMatch); - } - if slice_len < offset_first { - return ve!(Self, HeaderIsBroken, offset_first, slice_len); - } - let mut offsets: Vec = slice[molecule::NUMBER_SIZE..offset_first] - .chunks_exact(molecule::NUMBER_SIZE) - .map(|x| molecule::unpack_number(x) as usize) - .collect(); - offsets.push(total_size); - if offsets.windows(2).any(|i| i[0] > i[1]) { - return ve!(Self, OffsetsNotMatch); - } - for pair in offsets.windows(2) { - let start = pair[0]; - let end = pair[1]; - StakeInfoReader::verify(&slice[start..end], compatible)?; - } - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct StakeInfoVecBuilder(pub(crate) Vec); -impl StakeInfoVecBuilder { - pub fn set(mut self, v: Vec) -> Self { - self.0 = v; - self - } - - pub fn push(mut self, v: StakeInfo) -> Self { - self.0.push(v); - self - } - - pub fn extend>(mut self, iter: T) -> Self { - for elem in iter { - self.0.push(elem); - } - self - } -} -impl molecule::prelude::Builder for StakeInfoVecBuilder { - type Entity = StakeInfoVec; - - const NAME: &'static str = "StakeInfoVecBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE * (self.0.len() + 1) - + self - .0 - .iter() - .map(|inner| inner.as_slice().len()) - .sum::() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - let item_count = self.0.len(); - if item_count == 0 { - writer.write_all(&molecule::pack_number( - molecule::NUMBER_SIZE as molecule::Number, - ))?; - } else { - let (total_size, offsets) = self.0.iter().fold( - ( - molecule::NUMBER_SIZE * (item_count + 1), - Vec::with_capacity(item_count), - ), - |(start, mut offsets), inner| { - offsets.push(start); - (start + inner.as_slice().len(), offsets) - }, - ); - writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; - for offset in offsets.into_iter() { - writer.write_all(&molecule::pack_number(offset as molecule::Number))?; - } - for inner in self.0.iter() { - writer.write_all(inner.as_slice())?; - } - } - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - StakeInfoVec::new_unchecked(inner.into()) - } -} -pub struct StakeInfoVecIterator(StakeInfoVec, usize, usize); -impl ::core::iter::Iterator for StakeInfoVecIterator { - type Item = StakeInfo; - - fn next(&mut self) -> Option { - if self.1 >= self.2 { - None - } else { - let ret = self.0.get_unchecked(self.1); - self.1 += 1; - Some(ret) - } - } -} -impl ::core::iter::ExactSizeIterator for StakeInfoVecIterator { - fn len(&self) -> usize { - self.2 - self.1 - } -} -impl ::core::iter::IntoIterator for StakeInfoVec { - type IntoIter = StakeInfoVecIterator; - type Item = StakeInfo; - - fn into_iter(self) -> Self::IntoIter { - let len = self.len(); - StakeInfoVecIterator(self, 0, len) - } -} -impl<'r> StakeInfoVecReader<'r> { - pub fn iter<'t>(&'t self) -> StakeInfoVecReaderIterator<'t, 'r> { - StakeInfoVecReaderIterator(&self, 0, self.len()) - } -} -pub struct StakeInfoVecReaderIterator<'t, 'r>(&'t StakeInfoVecReader<'r>, usize, usize); -impl<'t: 'r, 'r> ::core::iter::Iterator for StakeInfoVecReaderIterator<'t, 'r> { - type Item = StakeInfoReader<'t>; - - fn next(&mut self) -> Option { - if self.1 >= self.2 { - None - } else { - let ret = self.0.get_unchecked(self.1); - self.1 += 1; - Some(ret) - } - } -} -impl<'t: 'r, 'r> ::core::iter::ExactSizeIterator for StakeInfoVecReaderIterator<'t, 'r> { - fn len(&self) -> usize { - self.2 - self.1 - } -} -#[derive(Clone)] -pub struct IdentityOpt(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for IdentityOpt { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for IdentityOpt { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for IdentityOpt { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(v) = self.to_opt() { - write!(f, "{}(Some({}))", Self::NAME, v) - } else { - write!(f, "{}(None)", Self::NAME) - } - } -} -impl ::core::default::Default for IdentityOpt { - fn default() -> Self { - let v: Vec = vec![]; - IdentityOpt::new_unchecked(v.into()) - } -} -impl IdentityOpt { - pub fn is_none(&self) -> bool { - self.0.is_empty() - } - - pub fn is_some(&self) -> bool { - !self.0.is_empty() - } - - pub fn to_opt(&self) -> Option { - if self.is_none() { - None - } else { - Some(Identity::new_unchecked(self.0.clone())) - } - } - - pub fn as_reader<'r>(&'r self) -> IdentityOptReader<'r> { - IdentityOptReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for IdentityOpt { - type Builder = IdentityOptBuilder; - - const NAME: &'static str = "IdentityOpt"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - IdentityOpt(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - IdentityOptReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - IdentityOptReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().set(self.to_opt()) - } -} -#[derive(Clone, Copy)] -pub struct IdentityOptReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for IdentityOptReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for IdentityOptReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for IdentityOptReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - if let Some(v) = self.to_opt() { - write!(f, "{}(Some({}))", Self::NAME, v) - } else { - write!(f, "{}(None)", Self::NAME) - } - } -} -impl<'r> IdentityOptReader<'r> { - pub fn is_none(&self) -> bool { - self.0.is_empty() - } - - pub fn is_some(&self) -> bool { - !self.0.is_empty() - } - - pub fn to_opt(&self) -> Option> { - if self.is_none() { - None - } else { - Some(IdentityReader::new_unchecked(self.as_slice())) - } - } -} -impl<'r> molecule::prelude::Reader<'r> for IdentityOptReader<'r> { - type Entity = IdentityOpt; - - const NAME: &'static str = "IdentityOptReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - IdentityOptReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { - if !slice.is_empty() { - IdentityReader::verify(&slice[..], compatible)?; - } - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct IdentityOptBuilder(pub(crate) Option); -impl IdentityOptBuilder { - pub fn set(mut self, v: Option) -> Self { - self.0 = v; - self - } -} -impl molecule::prelude::Builder for IdentityOptBuilder { - type Entity = IdentityOpt; - - const NAME: &'static str = "IdentityOptBuilder"; - - fn expected_length(&self) -> usize { - self.0 - .as_ref() - .map(|ref inner| inner.as_slice().len()) - .unwrap_or(0) - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - self.0 - .as_ref() - .map(|ref inner| writer.write_all(inner.as_slice())) - .unwrap_or(Ok(())) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - IdentityOpt::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct SelectionLockArgs(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for SelectionLockArgs { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for SelectionLockArgs { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for SelectionLockArgs { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "omni_lock_hash", self.omni_lock_hash())?; - write!( - f, - ", {}: {}", - "checkpoint_lock_hash", - self.checkpoint_lock_hash() - )?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl ::core::default::Default for SelectionLockArgs { - fn default() -> Self { - let v: Vec = vec![ - 76, 0, 0, 0, 12, 0, 0, 0, 44, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - SelectionLockArgs::new_unchecked(v.into()) - } -} -impl SelectionLockArgs { - pub const FIELD_COUNT: usize = 2; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn omni_lock_hash(&self) -> Byte32 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - Byte32::new_unchecked(self.0.slice(start..end)) - } - - pub fn checkpoint_lock_hash(&self) -> Byte32 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[12..]) as usize; - Byte32::new_unchecked(self.0.slice(start..end)) - } else { - Byte32::new_unchecked(self.0.slice(start..)) - } - } - - pub fn as_reader<'r>(&'r self) -> SelectionLockArgsReader<'r> { - SelectionLockArgsReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for SelectionLockArgs { - type Builder = SelectionLockArgsBuilder; - - const NAME: &'static str = "SelectionLockArgs"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - SelectionLockArgs(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - SelectionLockArgsReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - SelectionLockArgsReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder() - .omni_lock_hash(self.omni_lock_hash()) - .checkpoint_lock_hash(self.checkpoint_lock_hash()) - } -} -#[derive(Clone, Copy)] -pub struct SelectionLockArgsReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for SelectionLockArgsReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for SelectionLockArgsReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for SelectionLockArgsReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "omni_lock_hash", self.omni_lock_hash())?; - write!( - f, - ", {}: {}", - "checkpoint_lock_hash", - self.checkpoint_lock_hash() - )?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl<'r> SelectionLockArgsReader<'r> { - pub const FIELD_COUNT: usize = 2; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn omni_lock_hash(&self) -> Byte32Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - Byte32Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn checkpoint_lock_hash(&self) -> Byte32Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[12..]) as usize; - Byte32Reader::new_unchecked(&self.as_slice()[start..end]) - } else { - Byte32Reader::new_unchecked(&self.as_slice()[start..]) - } - } -} -impl<'r> molecule::prelude::Reader<'r> for SelectionLockArgsReader<'r> { - type Entity = SelectionLockArgs; - - const NAME: &'static str = "SelectionLockArgsReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - SelectionLockArgsReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let total_size = molecule::unpack_number(slice) as usize; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { - return Ok(()); - } - if slice_len < molecule::NUMBER_SIZE * 2 { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); - } - let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { - return ve!(Self, OffsetsNotMatch); - } - if slice_len < offset_first { - return ve!(Self, HeaderIsBroken, offset_first, slice_len); - } - let field_count = offset_first / molecule::NUMBER_SIZE - 1; - if field_count < Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - } else if !compatible && field_count > Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - }; - let mut offsets: Vec = slice[molecule::NUMBER_SIZE..offset_first] - .chunks_exact(molecule::NUMBER_SIZE) - .map(|x| molecule::unpack_number(x) as usize) - .collect(); - offsets.push(total_size); - if offsets.windows(2).any(|i| i[0] > i[1]) { - return ve!(Self, OffsetsNotMatch); - } - Byte32Reader::verify(&slice[offsets[0]..offsets[1]], compatible)?; - Byte32Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?; - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct SelectionLockArgsBuilder { - pub(crate) omni_lock_hash: Byte32, - pub(crate) checkpoint_lock_hash: Byte32, -} -impl SelectionLockArgsBuilder { - pub const FIELD_COUNT: usize = 2; - - pub fn omni_lock_hash(mut self, v: Byte32) -> Self { - self.omni_lock_hash = v; - self - } - - pub fn checkpoint_lock_hash(mut self, v: Byte32) -> Self { - self.checkpoint_lock_hash = v; - self - } -} -impl molecule::prelude::Builder for SelectionLockArgsBuilder { - type Entity = SelectionLockArgs; - - const NAME: &'static str = "SelectionLockArgsBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) - + self.omni_lock_hash.as_slice().len() - + self.checkpoint_lock_hash.as_slice().len() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); - let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); - offsets.push(total_size); - total_size += self.omni_lock_hash.as_slice().len(); - offsets.push(total_size); - total_size += self.checkpoint_lock_hash.as_slice().len(); - writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; - for offset in offsets.into_iter() { - writer.write_all(&molecule::pack_number(offset as molecule::Number))?; - } - writer.write_all(self.omni_lock_hash.as_slice())?; - writer.write_all(self.checkpoint_lock_hash.as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - SelectionLockArgs::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct StakeLockArgs(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for StakeLockArgs { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for StakeLockArgs { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for StakeLockArgs { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "admin_identity", self.admin_identity())?; - write!(f, ", {}: {}", "type_id_hash", self.type_id_hash())?; - write!(f, ", {}: {}", "node_identity", self.node_identity())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl ::core::default::Default for StakeLockArgs { - fn default() -> Self { - let v: Vec = vec![ - 81, 0, 0, 0, 16, 0, 0, 0, 49, 0, 0, 0, 81, 0, 0, 0, 33, 0, 0, 0, 12, 0, 0, 0, 13, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - StakeLockArgs::new_unchecked(v.into()) - } -} -impl StakeLockArgs { - pub const FIELD_COUNT: usize = 3; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn admin_identity(&self) -> Identity { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - Identity::new_unchecked(self.0.slice(start..end)) - } - - pub fn type_id_hash(&self) -> Byte32 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - let end = molecule::unpack_number(&slice[12..]) as usize; - Byte32::new_unchecked(self.0.slice(start..end)) - } - - pub fn node_identity(&self) -> IdentityOpt { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[12..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[16..]) as usize; - IdentityOpt::new_unchecked(self.0.slice(start..end)) - } else { - IdentityOpt::new_unchecked(self.0.slice(start..)) - } - } - - pub fn as_reader<'r>(&'r self) -> StakeLockArgsReader<'r> { - StakeLockArgsReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for StakeLockArgs { - type Builder = StakeLockArgsBuilder; - - const NAME: &'static str = "StakeLockArgs"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - StakeLockArgs(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - StakeLockArgsReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - StakeLockArgsReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder() - .admin_identity(self.admin_identity()) - .type_id_hash(self.type_id_hash()) - .node_identity(self.node_identity()) - } -} -#[derive(Clone, Copy)] -pub struct StakeLockArgsReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for StakeLockArgsReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for StakeLockArgsReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for StakeLockArgsReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "admin_identity", self.admin_identity())?; - write!(f, ", {}: {}", "type_id_hash", self.type_id_hash())?; - write!(f, ", {}: {}", "node_identity", self.node_identity())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl<'r> StakeLockArgsReader<'r> { - pub const FIELD_COUNT: usize = 3; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn admin_identity(&self) -> IdentityReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - IdentityReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn type_id_hash(&self) -> Byte32Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - let end = molecule::unpack_number(&slice[12..]) as usize; - Byte32Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn node_identity(&self) -> IdentityOptReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[12..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[16..]) as usize; - IdentityOptReader::new_unchecked(&self.as_slice()[start..end]) - } else { - IdentityOptReader::new_unchecked(&self.as_slice()[start..]) - } - } -} -impl<'r> molecule::prelude::Reader<'r> for StakeLockArgsReader<'r> { - type Entity = StakeLockArgs; - - const NAME: &'static str = "StakeLockArgsReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - StakeLockArgsReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let total_size = molecule::unpack_number(slice) as usize; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { - return Ok(()); - } - if slice_len < molecule::NUMBER_SIZE * 2 { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); - } - let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { - return ve!(Self, OffsetsNotMatch); - } - if slice_len < offset_first { - return ve!(Self, HeaderIsBroken, offset_first, slice_len); - } - let field_count = offset_first / molecule::NUMBER_SIZE - 1; - if field_count < Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - } else if !compatible && field_count > Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - }; - let mut offsets: Vec = slice[molecule::NUMBER_SIZE..offset_first] - .chunks_exact(molecule::NUMBER_SIZE) - .map(|x| molecule::unpack_number(x) as usize) - .collect(); - offsets.push(total_size); - if offsets.windows(2).any(|i| i[0] > i[1]) { - return ve!(Self, OffsetsNotMatch); - } - IdentityReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; - Byte32Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?; - IdentityOptReader::verify(&slice[offsets[2]..offsets[3]], compatible)?; - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct StakeLockArgsBuilder { - pub(crate) admin_identity: Identity, - pub(crate) type_id_hash: Byte32, - pub(crate) node_identity: IdentityOpt, -} -impl StakeLockArgsBuilder { - pub const FIELD_COUNT: usize = 3; - - pub fn admin_identity(mut self, v: Identity) -> Self { - self.admin_identity = v; - self - } - - pub fn type_id_hash(mut self, v: Byte32) -> Self { - self.type_id_hash = v; - self - } - - pub fn node_identity(mut self, v: IdentityOpt) -> Self { - self.node_identity = v; - self - } -} -impl molecule::prelude::Builder for StakeLockArgsBuilder { - type Entity = StakeLockArgs; - - const NAME: &'static str = "StakeLockArgsBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) - + self.admin_identity.as_slice().len() - + self.type_id_hash.as_slice().len() - + self.node_identity.as_slice().len() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); - let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); - offsets.push(total_size); - total_size += self.admin_identity.as_slice().len(); - offsets.push(total_size); - total_size += self.type_id_hash.as_slice().len(); - offsets.push(total_size); - total_size += self.node_identity.as_slice().len(); - writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; - for offset in offsets.into_iter() { - writer.write_all(&molecule::pack_number(offset as molecule::Number))?; - } - writer.write_all(self.admin_identity.as_slice())?; - writer.write_all(self.type_id_hash.as_slice())?; - writer.write_all(self.node_identity.as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - StakeLockArgs::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct StakeLockCellData(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for StakeLockCellData { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for StakeLockCellData { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for StakeLockCellData { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "version", self.version())?; - write!(f, ", {}: {}", "stake_infos", self.stake_infos())?; - write!( - f, - ", {}: {}", - "checkpoint_type_hash", - self.checkpoint_type_hash() - )?; - write!(f, ", {}: {}", "sudt_type_hash", self.sudt_type_hash())?; - write!(f, ", {}: {}", "quorum_size", self.quorum_size())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl ::core::default::Default for StakeLockCellData { - fn default() -> Self { - let v: Vec = vec![ - 94, 0, 0, 0, 24, 0, 0, 0, 25, 0, 0, 0, 29, 0, 0, 0, 61, 0, 0, 0, 93, 0, 0, 0, 0, 4, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - StakeLockCellData::new_unchecked(v.into()) - } -} -impl StakeLockCellData { - pub const FIELD_COUNT: usize = 5; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn version(&self) -> Byte { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - Byte::new_unchecked(self.0.slice(start..end)) - } - - pub fn stake_infos(&self) -> StakeInfoVec { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - let end = molecule::unpack_number(&slice[12..]) as usize; - StakeInfoVec::new_unchecked(self.0.slice(start..end)) - } - - pub fn checkpoint_type_hash(&self) -> Byte32 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[12..]) as usize; - let end = molecule::unpack_number(&slice[16..]) as usize; - Byte32::new_unchecked(self.0.slice(start..end)) - } - - pub fn sudt_type_hash(&self) -> Byte32 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[16..]) as usize; - let end = molecule::unpack_number(&slice[20..]) as usize; - Byte32::new_unchecked(self.0.slice(start..end)) - } - - pub fn quorum_size(&self) -> Byte { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[20..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[24..]) as usize; - Byte::new_unchecked(self.0.slice(start..end)) - } else { - Byte::new_unchecked(self.0.slice(start..)) - } - } - - pub fn as_reader<'r>(&'r self) -> StakeLockCellDataReader<'r> { - StakeLockCellDataReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for StakeLockCellData { - type Builder = StakeLockCellDataBuilder; - - const NAME: &'static str = "StakeLockCellData"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - StakeLockCellData(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - StakeLockCellDataReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - StakeLockCellDataReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder() - .version(self.version()) - .stake_infos(self.stake_infos()) - .checkpoint_type_hash(self.checkpoint_type_hash()) - .sudt_type_hash(self.sudt_type_hash()) - .quorum_size(self.quorum_size()) - } -} -#[derive(Clone, Copy)] -pub struct StakeLockCellDataReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for StakeLockCellDataReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for StakeLockCellDataReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for StakeLockCellDataReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "version", self.version())?; - write!(f, ", {}: {}", "stake_infos", self.stake_infos())?; - write!( - f, - ", {}: {}", - "checkpoint_type_hash", - self.checkpoint_type_hash() - )?; - write!(f, ", {}: {}", "sudt_type_hash", self.sudt_type_hash())?; - write!(f, ", {}: {}", "quorum_size", self.quorum_size())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl<'r> StakeLockCellDataReader<'r> { - pub const FIELD_COUNT: usize = 5; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn version(&self) -> ByteReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - ByteReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn stake_infos(&self) -> StakeInfoVecReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - let end = molecule::unpack_number(&slice[12..]) as usize; - StakeInfoVecReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn checkpoint_type_hash(&self) -> Byte32Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[12..]) as usize; - let end = molecule::unpack_number(&slice[16..]) as usize; - Byte32Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn sudt_type_hash(&self) -> Byte32Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[16..]) as usize; - let end = molecule::unpack_number(&slice[20..]) as usize; - Byte32Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn quorum_size(&self) -> ByteReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[20..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[24..]) as usize; - ByteReader::new_unchecked(&self.as_slice()[start..end]) - } else { - ByteReader::new_unchecked(&self.as_slice()[start..]) - } - } -} -impl<'r> molecule::prelude::Reader<'r> for StakeLockCellDataReader<'r> { - type Entity = StakeLockCellData; - - const NAME: &'static str = "StakeLockCellDataReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - StakeLockCellDataReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let total_size = molecule::unpack_number(slice) as usize; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { - return Ok(()); - } - if slice_len < molecule::NUMBER_SIZE * 2 { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); - } - let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { - return ve!(Self, OffsetsNotMatch); - } - if slice_len < offset_first { - return ve!(Self, HeaderIsBroken, offset_first, slice_len); - } - let field_count = offset_first / molecule::NUMBER_SIZE - 1; - if field_count < Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - } else if !compatible && field_count > Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - }; - let mut offsets: Vec = slice[molecule::NUMBER_SIZE..offset_first] - .chunks_exact(molecule::NUMBER_SIZE) - .map(|x| molecule::unpack_number(x) as usize) - .collect(); - offsets.push(total_size); - if offsets.windows(2).any(|i| i[0] > i[1]) { - return ve!(Self, OffsetsNotMatch); - } - ByteReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; - StakeInfoVecReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; - Byte32Reader::verify(&slice[offsets[2]..offsets[3]], compatible)?; - Byte32Reader::verify(&slice[offsets[3]..offsets[4]], compatible)?; - ByteReader::verify(&slice[offsets[4]..offsets[5]], compatible)?; - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct StakeLockCellDataBuilder { - pub(crate) version: Byte, - pub(crate) stake_infos: StakeInfoVec, - pub(crate) checkpoint_type_hash: Byte32, - pub(crate) sudt_type_hash: Byte32, - pub(crate) quorum_size: Byte, -} -impl StakeLockCellDataBuilder { - pub const FIELD_COUNT: usize = 5; - - pub fn version(mut self, v: Byte) -> Self { - self.version = v; - self - } - - pub fn stake_infos(mut self, v: StakeInfoVec) -> Self { - self.stake_infos = v; - self - } - - pub fn checkpoint_type_hash(mut self, v: Byte32) -> Self { - self.checkpoint_type_hash = v; - self - } - - pub fn sudt_type_hash(mut self, v: Byte32) -> Self { - self.sudt_type_hash = v; - self - } - - pub fn quorum_size(mut self, v: Byte) -> Self { - self.quorum_size = v; - self - } -} -impl molecule::prelude::Builder for StakeLockCellDataBuilder { - type Entity = StakeLockCellData; - - const NAME: &'static str = "StakeLockCellDataBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) - + self.version.as_slice().len() - + self.stake_infos.as_slice().len() - + self.checkpoint_type_hash.as_slice().len() - + self.sudt_type_hash.as_slice().len() - + self.quorum_size.as_slice().len() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); - let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); - offsets.push(total_size); - total_size += self.version.as_slice().len(); - offsets.push(total_size); - total_size += self.stake_infos.as_slice().len(); - offsets.push(total_size); - total_size += self.checkpoint_type_hash.as_slice().len(); - offsets.push(total_size); - total_size += self.sudt_type_hash.as_slice().len(); - offsets.push(total_size); - total_size += self.quorum_size.as_slice().len(); - writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; - for offset in offsets.into_iter() { - writer.write_all(&molecule::pack_number(offset as molecule::Number))?; - } - writer.write_all(self.version.as_slice())?; - writer.write_all(self.stake_infos.as_slice())?; - writer.write_all(self.checkpoint_type_hash.as_slice())?; - writer.write_all(self.sudt_type_hash.as_slice())?; - writer.write_all(self.quorum_size.as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - StakeLockCellData::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct CheckpointLockArgs(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for CheckpointLockArgs { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for CheckpointLockArgs { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for CheckpointLockArgs { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "admin_identity", self.admin_identity())?; - write!(f, ", {}: {}", "type_id_hash", self.type_id_hash())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl ::core::default::Default for CheckpointLockArgs { - fn default() -> Self { - let v: Vec = vec![ - 77, 0, 0, 0, 12, 0, 0, 0, 45, 0, 0, 0, 33, 0, 0, 0, 12, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - CheckpointLockArgs::new_unchecked(v.into()) - } -} -impl CheckpointLockArgs { - pub const FIELD_COUNT: usize = 2; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn admin_identity(&self) -> Identity { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - Identity::new_unchecked(self.0.slice(start..end)) - } - - pub fn type_id_hash(&self) -> Byte32 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[12..]) as usize; - Byte32::new_unchecked(self.0.slice(start..end)) - } else { - Byte32::new_unchecked(self.0.slice(start..)) - } - } - - pub fn as_reader<'r>(&'r self) -> CheckpointLockArgsReader<'r> { - CheckpointLockArgsReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for CheckpointLockArgs { - type Builder = CheckpointLockArgsBuilder; - - const NAME: &'static str = "CheckpointLockArgs"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - CheckpointLockArgs(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - CheckpointLockArgsReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - CheckpointLockArgsReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder() - .admin_identity(self.admin_identity()) - .type_id_hash(self.type_id_hash()) - } -} -#[derive(Clone, Copy)] -pub struct CheckpointLockArgsReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for CheckpointLockArgsReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for CheckpointLockArgsReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for CheckpointLockArgsReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "admin_identity", self.admin_identity())?; - write!(f, ", {}: {}", "type_id_hash", self.type_id_hash())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl<'r> CheckpointLockArgsReader<'r> { - pub const FIELD_COUNT: usize = 2; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn admin_identity(&self) -> IdentityReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - IdentityReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn type_id_hash(&self) -> Byte32Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[12..]) as usize; - Byte32Reader::new_unchecked(&self.as_slice()[start..end]) - } else { - Byte32Reader::new_unchecked(&self.as_slice()[start..]) - } - } -} -impl<'r> molecule::prelude::Reader<'r> for CheckpointLockArgsReader<'r> { - type Entity = CheckpointLockArgs; - - const NAME: &'static str = "CheckpointLockArgsReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - CheckpointLockArgsReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let total_size = molecule::unpack_number(slice) as usize; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { - return Ok(()); - } - if slice_len < molecule::NUMBER_SIZE * 2 { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); - } - let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { - return ve!(Self, OffsetsNotMatch); - } - if slice_len < offset_first { - return ve!(Self, HeaderIsBroken, offset_first, slice_len); - } - let field_count = offset_first / molecule::NUMBER_SIZE - 1; - if field_count < Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - } else if !compatible && field_count > Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - }; - let mut offsets: Vec = slice[molecule::NUMBER_SIZE..offset_first] - .chunks_exact(molecule::NUMBER_SIZE) - .map(|x| molecule::unpack_number(x) as usize) - .collect(); - offsets.push(total_size); - if offsets.windows(2).any(|i| i[0] > i[1]) { - return ve!(Self, OffsetsNotMatch); - } - IdentityReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; - Byte32Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?; - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct CheckpointLockArgsBuilder { - pub(crate) admin_identity: Identity, - pub(crate) type_id_hash: Byte32, -} -impl CheckpointLockArgsBuilder { - pub const FIELD_COUNT: usize = 2; - - pub fn admin_identity(mut self, v: Identity) -> Self { - self.admin_identity = v; - self - } - - pub fn type_id_hash(mut self, v: Byte32) -> Self { - self.type_id_hash = v; - self - } -} -impl molecule::prelude::Builder for CheckpointLockArgsBuilder { - type Entity = CheckpointLockArgs; - - const NAME: &'static str = "CheckpointLockArgsBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) - + self.admin_identity.as_slice().len() - + self.type_id_hash.as_slice().len() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); - let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); - offsets.push(total_size); - total_size += self.admin_identity.as_slice().len(); - offsets.push(total_size); - total_size += self.type_id_hash.as_slice().len(); - writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; - for offset in offsets.into_iter() { - writer.write_all(&molecule::pack_number(offset as molecule::Number))?; - } - writer.write_all(self.admin_identity.as_slice())?; - writer.write_all(self.type_id_hash.as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - CheckpointLockArgs::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct CheckpointLockCellData(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for CheckpointLockCellData { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for CheckpointLockCellData { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for CheckpointLockCellData { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "version", self.version())?; - write!(f, ", {}: {}", "state", self.state())?; - write!(f, ", {}: {}", "period", self.period())?; - write!(f, ", {}: {}", "era", self.era())?; - write!(f, ", {}: {}", "block_hash", self.block_hash())?; - write!(f, ", {}: {}", "period_interval", self.period_interval())?; - write!(f, ", {}: {}", "era_period", self.era_period())?; - write!(f, ", {}: {}", "unlock_period", self.unlock_period())?; - write!(f, ", {}: {}", "base_reward", self.base_reward())?; - write!(f, ", {}: {}", "half_period", self.half_period())?; - write!(f, ", {}: {}", "common_ref", self.common_ref())?; - write!(f, ", {}: {}", "sudt_type_hash", self.sudt_type_hash())?; - write!(f, ", {}: {}", "stake_type_hash", self.stake_type_hash())?; - write!( - f, - ", {}: {}", - "withdrawal_lock_code_hash", - self.withdrawal_lock_code_hash() - )?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl ::core::default::Default for CheckpointLockCellData { - fn default() -> Self { - let v: Vec = vec![ - 252, 0, 0, 0, 60, 0, 0, 0, 61, 0, 0, 0, 62, 0, 0, 0, 70, 0, 0, 0, 78, 0, 0, 0, 110, 0, - 0, 0, 114, 0, 0, 0, 118, 0, 0, 0, 122, 0, 0, 0, 138, 0, 0, 0, 146, 0, 0, 0, 156, 0, 0, - 0, 188, 0, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - CheckpointLockCellData::new_unchecked(v.into()) - } -} -impl CheckpointLockCellData { - pub const FIELD_COUNT: usize = 14; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn version(&self) -> Byte { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - Byte::new_unchecked(self.0.slice(start..end)) - } - - pub fn state(&self) -> Byte { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - let end = molecule::unpack_number(&slice[12..]) as usize; - Byte::new_unchecked(self.0.slice(start..end)) - } - - pub fn period(&self) -> Byte8 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[12..]) as usize; - let end = molecule::unpack_number(&slice[16..]) as usize; - Byte8::new_unchecked(self.0.slice(start..end)) - } - - pub fn era(&self) -> Byte8 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[16..]) as usize; - let end = molecule::unpack_number(&slice[20..]) as usize; - Byte8::new_unchecked(self.0.slice(start..end)) - } - - pub fn block_hash(&self) -> Byte32 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[20..]) as usize; - let end = molecule::unpack_number(&slice[24..]) as usize; - Byte32::new_unchecked(self.0.slice(start..end)) - } - - pub fn period_interval(&self) -> Byte4 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[24..]) as usize; - let end = molecule::unpack_number(&slice[28..]) as usize; - Byte4::new_unchecked(self.0.slice(start..end)) - } - - pub fn era_period(&self) -> Byte4 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[28..]) as usize; - let end = molecule::unpack_number(&slice[32..]) as usize; - Byte4::new_unchecked(self.0.slice(start..end)) - } - - pub fn unlock_period(&self) -> Byte4 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[32..]) as usize; - let end = molecule::unpack_number(&slice[36..]) as usize; - Byte4::new_unchecked(self.0.slice(start..end)) - } - - pub fn base_reward(&self) -> Byte16 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[36..]) as usize; - let end = molecule::unpack_number(&slice[40..]) as usize; - Byte16::new_unchecked(self.0.slice(start..end)) - } - - pub fn half_period(&self) -> Byte8 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[40..]) as usize; - let end = molecule::unpack_number(&slice[44..]) as usize; - Byte8::new_unchecked(self.0.slice(start..end)) - } - - pub fn common_ref(&self) -> Byte10 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[44..]) as usize; - let end = molecule::unpack_number(&slice[48..]) as usize; - Byte10::new_unchecked(self.0.slice(start..end)) - } - - pub fn sudt_type_hash(&self) -> Byte32 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[48..]) as usize; - let end = molecule::unpack_number(&slice[52..]) as usize; - Byte32::new_unchecked(self.0.slice(start..end)) - } - - pub fn stake_type_hash(&self) -> Byte32 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[52..]) as usize; - let end = molecule::unpack_number(&slice[56..]) as usize; - Byte32::new_unchecked(self.0.slice(start..end)) - } - - pub fn withdrawal_lock_code_hash(&self) -> Byte32 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[56..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[60..]) as usize; - Byte32::new_unchecked(self.0.slice(start..end)) - } else { - Byte32::new_unchecked(self.0.slice(start..)) - } - } - - pub fn as_reader<'r>(&'r self) -> CheckpointLockCellDataReader<'r> { - CheckpointLockCellDataReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for CheckpointLockCellData { - type Builder = CheckpointLockCellDataBuilder; - - const NAME: &'static str = "CheckpointLockCellData"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - CheckpointLockCellData(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - CheckpointLockCellDataReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - CheckpointLockCellDataReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder() - .version(self.version()) - .state(self.state()) - .period(self.period()) - .era(self.era()) - .block_hash(self.block_hash()) - .period_interval(self.period_interval()) - .era_period(self.era_period()) - .unlock_period(self.unlock_period()) - .base_reward(self.base_reward()) - .half_period(self.half_period()) - .common_ref(self.common_ref()) - .sudt_type_hash(self.sudt_type_hash()) - .stake_type_hash(self.stake_type_hash()) - .withdrawal_lock_code_hash(self.withdrawal_lock_code_hash()) - } -} -#[derive(Clone, Copy)] -pub struct CheckpointLockCellDataReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for CheckpointLockCellDataReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for CheckpointLockCellDataReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for CheckpointLockCellDataReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "version", self.version())?; - write!(f, ", {}: {}", "state", self.state())?; - write!(f, ", {}: {}", "period", self.period())?; - write!(f, ", {}: {}", "era", self.era())?; - write!(f, ", {}: {}", "block_hash", self.block_hash())?; - write!(f, ", {}: {}", "period_interval", self.period_interval())?; - write!(f, ", {}: {}", "era_period", self.era_period())?; - write!(f, ", {}: {}", "unlock_period", self.unlock_period())?; - write!(f, ", {}: {}", "base_reward", self.base_reward())?; - write!(f, ", {}: {}", "half_period", self.half_period())?; - write!(f, ", {}: {}", "common_ref", self.common_ref())?; - write!(f, ", {}: {}", "sudt_type_hash", self.sudt_type_hash())?; - write!(f, ", {}: {}", "stake_type_hash", self.stake_type_hash())?; - write!( - f, - ", {}: {}", - "withdrawal_lock_code_hash", - self.withdrawal_lock_code_hash() - )?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl<'r> CheckpointLockCellDataReader<'r> { - pub const FIELD_COUNT: usize = 14; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn version(&self) -> ByteReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - ByteReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn state(&self) -> ByteReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - let end = molecule::unpack_number(&slice[12..]) as usize; - ByteReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn period(&self) -> Byte8Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[12..]) as usize; - let end = molecule::unpack_number(&slice[16..]) as usize; - Byte8Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn era(&self) -> Byte8Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[16..]) as usize; - let end = molecule::unpack_number(&slice[20..]) as usize; - Byte8Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn block_hash(&self) -> Byte32Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[20..]) as usize; - let end = molecule::unpack_number(&slice[24..]) as usize; - Byte32Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn period_interval(&self) -> Byte4Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[24..]) as usize; - let end = molecule::unpack_number(&slice[28..]) as usize; - Byte4Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn era_period(&self) -> Byte4Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[28..]) as usize; - let end = molecule::unpack_number(&slice[32..]) as usize; - Byte4Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn unlock_period(&self) -> Byte4Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[32..]) as usize; - let end = molecule::unpack_number(&slice[36..]) as usize; - Byte4Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn base_reward(&self) -> Byte16Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[36..]) as usize; - let end = molecule::unpack_number(&slice[40..]) as usize; - Byte16Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn half_period(&self) -> Byte8Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[40..]) as usize; - let end = molecule::unpack_number(&slice[44..]) as usize; - Byte8Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn common_ref(&self) -> Byte10Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[44..]) as usize; - let end = molecule::unpack_number(&slice[48..]) as usize; - Byte10Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn sudt_type_hash(&self) -> Byte32Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[48..]) as usize; - let end = molecule::unpack_number(&slice[52..]) as usize; - Byte32Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn stake_type_hash(&self) -> Byte32Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[52..]) as usize; - let end = molecule::unpack_number(&slice[56..]) as usize; - Byte32Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn withdrawal_lock_code_hash(&self) -> Byte32Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[56..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[60..]) as usize; - Byte32Reader::new_unchecked(&self.as_slice()[start..end]) - } else { - Byte32Reader::new_unchecked(&self.as_slice()[start..]) - } - } -} -impl<'r> molecule::prelude::Reader<'r> for CheckpointLockCellDataReader<'r> { - type Entity = CheckpointLockCellData; - - const NAME: &'static str = "CheckpointLockCellDataReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - CheckpointLockCellDataReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let total_size = molecule::unpack_number(slice) as usize; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { - return Ok(()); - } - if slice_len < molecule::NUMBER_SIZE * 2 { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); - } - let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { - return ve!(Self, OffsetsNotMatch); - } - if slice_len < offset_first { - return ve!(Self, HeaderIsBroken, offset_first, slice_len); - } - let field_count = offset_first / molecule::NUMBER_SIZE - 1; - if field_count < Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - } else if !compatible && field_count > Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - }; - let mut offsets: Vec = slice[molecule::NUMBER_SIZE..offset_first] - .chunks_exact(molecule::NUMBER_SIZE) - .map(|x| molecule::unpack_number(x) as usize) - .collect(); - offsets.push(total_size); - if offsets.windows(2).any(|i| i[0] > i[1]) { - return ve!(Self, OffsetsNotMatch); - } - ByteReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; - ByteReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; - Byte8Reader::verify(&slice[offsets[2]..offsets[3]], compatible)?; - Byte8Reader::verify(&slice[offsets[3]..offsets[4]], compatible)?; - Byte32Reader::verify(&slice[offsets[4]..offsets[5]], compatible)?; - Byte4Reader::verify(&slice[offsets[5]..offsets[6]], compatible)?; - Byte4Reader::verify(&slice[offsets[6]..offsets[7]], compatible)?; - Byte4Reader::verify(&slice[offsets[7]..offsets[8]], compatible)?; - Byte16Reader::verify(&slice[offsets[8]..offsets[9]], compatible)?; - Byte8Reader::verify(&slice[offsets[9]..offsets[10]], compatible)?; - Byte10Reader::verify(&slice[offsets[10]..offsets[11]], compatible)?; - Byte32Reader::verify(&slice[offsets[11]..offsets[12]], compatible)?; - Byte32Reader::verify(&slice[offsets[12]..offsets[13]], compatible)?; - Byte32Reader::verify(&slice[offsets[13]..offsets[14]], compatible)?; - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct CheckpointLockCellDataBuilder { - pub(crate) version: Byte, - pub(crate) state: Byte, - pub(crate) period: Byte8, - pub(crate) era: Byte8, - pub(crate) block_hash: Byte32, - pub(crate) period_interval: Byte4, - pub(crate) era_period: Byte4, - pub(crate) unlock_period: Byte4, - pub(crate) base_reward: Byte16, - pub(crate) half_period: Byte8, - pub(crate) common_ref: Byte10, - pub(crate) sudt_type_hash: Byte32, - pub(crate) stake_type_hash: Byte32, - pub(crate) withdrawal_lock_code_hash: Byte32, -} -impl CheckpointLockCellDataBuilder { - pub const FIELD_COUNT: usize = 14; - - pub fn version(mut self, v: Byte) -> Self { - self.version = v; - self - } - - pub fn state(mut self, v: Byte) -> Self { - self.state = v; - self - } - - pub fn period(mut self, v: Byte8) -> Self { - self.period = v; - self - } - - pub fn era(mut self, v: Byte8) -> Self { - self.era = v; - self - } - - pub fn block_hash(mut self, v: Byte32) -> Self { - self.block_hash = v; - self - } - - pub fn period_interval(mut self, v: Byte4) -> Self { - self.period_interval = v; - self - } - - pub fn era_period(mut self, v: Byte4) -> Self { - self.era_period = v; - self - } - - pub fn unlock_period(mut self, v: Byte4) -> Self { - self.unlock_period = v; - self - } - - pub fn base_reward(mut self, v: Byte16) -> Self { - self.base_reward = v; - self - } - - pub fn half_period(mut self, v: Byte8) -> Self { - self.half_period = v; - self - } - - pub fn common_ref(mut self, v: Byte10) -> Self { - self.common_ref = v; - self - } - - pub fn sudt_type_hash(mut self, v: Byte32) -> Self { - self.sudt_type_hash = v; - self - } - - pub fn stake_type_hash(mut self, v: Byte32) -> Self { - self.stake_type_hash = v; - self - } - - pub fn withdrawal_lock_code_hash(mut self, v: Byte32) -> Self { - self.withdrawal_lock_code_hash = v; - self - } -} -impl molecule::prelude::Builder for CheckpointLockCellDataBuilder { - type Entity = CheckpointLockCellData; - - const NAME: &'static str = "CheckpointLockCellDataBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) - + self.version.as_slice().len() - + self.state.as_slice().len() - + self.period.as_slice().len() - + self.era.as_slice().len() - + self.block_hash.as_slice().len() - + self.period_interval.as_slice().len() - + self.era_period.as_slice().len() - + self.unlock_period.as_slice().len() - + self.base_reward.as_slice().len() - + self.half_period.as_slice().len() - + self.common_ref.as_slice().len() - + self.sudt_type_hash.as_slice().len() - + self.stake_type_hash.as_slice().len() - + self.withdrawal_lock_code_hash.as_slice().len() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); - let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); - offsets.push(total_size); - total_size += self.version.as_slice().len(); - offsets.push(total_size); - total_size += self.state.as_slice().len(); - offsets.push(total_size); - total_size += self.period.as_slice().len(); - offsets.push(total_size); - total_size += self.era.as_slice().len(); - offsets.push(total_size); - total_size += self.block_hash.as_slice().len(); - offsets.push(total_size); - total_size += self.period_interval.as_slice().len(); - offsets.push(total_size); - total_size += self.era_period.as_slice().len(); - offsets.push(total_size); - total_size += self.unlock_period.as_slice().len(); - offsets.push(total_size); - total_size += self.base_reward.as_slice().len(); - offsets.push(total_size); - total_size += self.half_period.as_slice().len(); - offsets.push(total_size); - total_size += self.common_ref.as_slice().len(); - offsets.push(total_size); - total_size += self.sudt_type_hash.as_slice().len(); - offsets.push(total_size); - total_size += self.stake_type_hash.as_slice().len(); - offsets.push(total_size); - total_size += self.withdrawal_lock_code_hash.as_slice().len(); - writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; - for offset in offsets.into_iter() { - writer.write_all(&molecule::pack_number(offset as molecule::Number))?; - } - writer.write_all(self.version.as_slice())?; - writer.write_all(self.state.as_slice())?; - writer.write_all(self.period.as_slice())?; - writer.write_all(self.era.as_slice())?; - writer.write_all(self.block_hash.as_slice())?; - writer.write_all(self.period_interval.as_slice())?; - writer.write_all(self.era_period.as_slice())?; - writer.write_all(self.unlock_period.as_slice())?; - writer.write_all(self.base_reward.as_slice())?; - writer.write_all(self.half_period.as_slice())?; - writer.write_all(self.common_ref.as_slice())?; - writer.write_all(self.sudt_type_hash.as_slice())?; - writer.write_all(self.stake_type_hash.as_slice())?; - writer.write_all(self.withdrawal_lock_code_hash.as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - CheckpointLockCellData::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct CheckpointLockWitnessLock(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for CheckpointLockWitnessLock { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for CheckpointLockWitnessLock { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for CheckpointLockWitnessLock { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "proposal", self.proposal())?; - write!(f, ", {}: {}", "proof", self.proof())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl ::core::default::Default for CheckpointLockWitnessLock { - fn default() -> Self { - let v: Vec = vec![ - 20, 0, 0, 0, 12, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - CheckpointLockWitnessLock::new_unchecked(v.into()) - } -} -impl CheckpointLockWitnessLock { - pub const FIELD_COUNT: usize = 2; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn proposal(&self) -> Bytes { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - Bytes::new_unchecked(self.0.slice(start..end)) - } - - pub fn proof(&self) -> Bytes { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[12..]) as usize; - Bytes::new_unchecked(self.0.slice(start..end)) - } else { - Bytes::new_unchecked(self.0.slice(start..)) - } - } - - pub fn as_reader<'r>(&'r self) -> CheckpointLockWitnessLockReader<'r> { - CheckpointLockWitnessLockReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for CheckpointLockWitnessLock { - type Builder = CheckpointLockWitnessLockBuilder; - - const NAME: &'static str = "CheckpointLockWitnessLock"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - CheckpointLockWitnessLock(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - CheckpointLockWitnessLockReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - CheckpointLockWitnessLockReader::from_compatible_slice(slice) - .map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder() - .proposal(self.proposal()) - .proof(self.proof()) - } -} -#[derive(Clone, Copy)] -pub struct CheckpointLockWitnessLockReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for CheckpointLockWitnessLockReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for CheckpointLockWitnessLockReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for CheckpointLockWitnessLockReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "proposal", self.proposal())?; - write!(f, ", {}: {}", "proof", self.proof())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl<'r> CheckpointLockWitnessLockReader<'r> { - pub const FIELD_COUNT: usize = 2; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn proposal(&self) -> BytesReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - BytesReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn proof(&self) -> BytesReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[12..]) as usize; - BytesReader::new_unchecked(&self.as_slice()[start..end]) - } else { - BytesReader::new_unchecked(&self.as_slice()[start..]) - } - } -} -impl<'r> molecule::prelude::Reader<'r> for CheckpointLockWitnessLockReader<'r> { - type Entity = CheckpointLockWitnessLock; - - const NAME: &'static str = "CheckpointLockWitnessLockReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - CheckpointLockWitnessLockReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let total_size = molecule::unpack_number(slice) as usize; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { - return Ok(()); - } - if slice_len < molecule::NUMBER_SIZE * 2 { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); - } - let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { - return ve!(Self, OffsetsNotMatch); - } - if slice_len < offset_first { - return ve!(Self, HeaderIsBroken, offset_first, slice_len); - } - let field_count = offset_first / molecule::NUMBER_SIZE - 1; - if field_count < Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - } else if !compatible && field_count > Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - }; - let mut offsets: Vec = slice[molecule::NUMBER_SIZE..offset_first] - .chunks_exact(molecule::NUMBER_SIZE) - .map(|x| molecule::unpack_number(x) as usize) - .collect(); - offsets.push(total_size); - if offsets.windows(2).any(|i| i[0] > i[1]) { - return ve!(Self, OffsetsNotMatch); - } - BytesReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; - BytesReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct CheckpointLockWitnessLockBuilder { - pub(crate) proposal: Bytes, - pub(crate) proof: Bytes, -} -impl CheckpointLockWitnessLockBuilder { - pub const FIELD_COUNT: usize = 2; - - pub fn proposal(mut self, v: Bytes) -> Self { - self.proposal = v; - self - } - - pub fn proof(mut self, v: Bytes) -> Self { - self.proof = v; - self - } -} -impl molecule::prelude::Builder for CheckpointLockWitnessLockBuilder { - type Entity = CheckpointLockWitnessLock; - - const NAME: &'static str = "CheckpointLockWitnessLockBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) - + self.proposal.as_slice().len() - + self.proof.as_slice().len() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); - let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); - offsets.push(total_size); - total_size += self.proposal.as_slice().len(); - offsets.push(total_size); - total_size += self.proof.as_slice().len(); - writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; - for offset in offsets.into_iter() { - writer.write_all(&molecule::pack_number(offset as molecule::Number))?; - } - writer.write_all(self.proposal.as_slice())?; - writer.write_all(self.proof.as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - CheckpointLockWitnessLock::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct WithdrawalLockArgs(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for WithdrawalLockArgs { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for WithdrawalLockArgs { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for WithdrawalLockArgs { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "admin_identity", self.admin_identity())?; - write!( - f, - ", {}: {}", - "checkpoint_cell_type_hash", - self.checkpoint_cell_type_hash() - )?; - write!(f, ", {}: {}", "node_identity", self.node_identity())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl ::core::default::Default for WithdrawalLockArgs { - fn default() -> Self { - let v: Vec = vec![ - 81, 0, 0, 0, 16, 0, 0, 0, 49, 0, 0, 0, 81, 0, 0, 0, 33, 0, 0, 0, 12, 0, 0, 0, 13, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - WithdrawalLockArgs::new_unchecked(v.into()) - } -} -impl WithdrawalLockArgs { - pub const FIELD_COUNT: usize = 3; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn admin_identity(&self) -> Identity { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - Identity::new_unchecked(self.0.slice(start..end)) - } - - pub fn checkpoint_cell_type_hash(&self) -> Byte32 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - let end = molecule::unpack_number(&slice[12..]) as usize; - Byte32::new_unchecked(self.0.slice(start..end)) - } - - pub fn node_identity(&self) -> IdentityOpt { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[12..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[16..]) as usize; - IdentityOpt::new_unchecked(self.0.slice(start..end)) - } else { - IdentityOpt::new_unchecked(self.0.slice(start..)) - } - } - - pub fn as_reader<'r>(&'r self) -> WithdrawalLockArgsReader<'r> { - WithdrawalLockArgsReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for WithdrawalLockArgs { - type Builder = WithdrawalLockArgsBuilder; - - const NAME: &'static str = "WithdrawalLockArgs"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - WithdrawalLockArgs(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - WithdrawalLockArgsReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - WithdrawalLockArgsReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder() - .admin_identity(self.admin_identity()) - .checkpoint_cell_type_hash(self.checkpoint_cell_type_hash()) - .node_identity(self.node_identity()) - } -} -#[derive(Clone, Copy)] -pub struct WithdrawalLockArgsReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for WithdrawalLockArgsReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for WithdrawalLockArgsReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for WithdrawalLockArgsReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "admin_identity", self.admin_identity())?; - write!( - f, - ", {}: {}", - "checkpoint_cell_type_hash", - self.checkpoint_cell_type_hash() - )?; - write!(f, ", {}: {}", "node_identity", self.node_identity())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl<'r> WithdrawalLockArgsReader<'r> { - pub const FIELD_COUNT: usize = 3; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn admin_identity(&self) -> IdentityReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - IdentityReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn checkpoint_cell_type_hash(&self) -> Byte32Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - let end = molecule::unpack_number(&slice[12..]) as usize; - Byte32Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn node_identity(&self) -> IdentityOptReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[12..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[16..]) as usize; - IdentityOptReader::new_unchecked(&self.as_slice()[start..end]) - } else { - IdentityOptReader::new_unchecked(&self.as_slice()[start..]) - } - } -} -impl<'r> molecule::prelude::Reader<'r> for WithdrawalLockArgsReader<'r> { - type Entity = WithdrawalLockArgs; - - const NAME: &'static str = "WithdrawalLockArgsReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - WithdrawalLockArgsReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let total_size = molecule::unpack_number(slice) as usize; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { - return Ok(()); - } - if slice_len < molecule::NUMBER_SIZE * 2 { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); - } - let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { - return ve!(Self, OffsetsNotMatch); - } - if slice_len < offset_first { - return ve!(Self, HeaderIsBroken, offset_first, slice_len); - } - let field_count = offset_first / molecule::NUMBER_SIZE - 1; - if field_count < Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - } else if !compatible && field_count > Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - }; - let mut offsets: Vec = slice[molecule::NUMBER_SIZE..offset_first] - .chunks_exact(molecule::NUMBER_SIZE) - .map(|x| molecule::unpack_number(x) as usize) - .collect(); - offsets.push(total_size); - if offsets.windows(2).any(|i| i[0] > i[1]) { - return ve!(Self, OffsetsNotMatch); - } - IdentityReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; - Byte32Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?; - IdentityOptReader::verify(&slice[offsets[2]..offsets[3]], compatible)?; - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct WithdrawalLockArgsBuilder { - pub(crate) admin_identity: Identity, - pub(crate) checkpoint_cell_type_hash: Byte32, - pub(crate) node_identity: IdentityOpt, -} -impl WithdrawalLockArgsBuilder { - pub const FIELD_COUNT: usize = 3; - - pub fn admin_identity(mut self, v: Identity) -> Self { - self.admin_identity = v; - self - } - - pub fn checkpoint_cell_type_hash(mut self, v: Byte32) -> Self { - self.checkpoint_cell_type_hash = v; - self - } - - pub fn node_identity(mut self, v: IdentityOpt) -> Self { - self.node_identity = v; - self - } -} -impl molecule::prelude::Builder for WithdrawalLockArgsBuilder { - type Entity = WithdrawalLockArgs; - - const NAME: &'static str = "WithdrawalLockArgsBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) - + self.admin_identity.as_slice().len() - + self.checkpoint_cell_type_hash.as_slice().len() - + self.node_identity.as_slice().len() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); - let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); - offsets.push(total_size); - total_size += self.admin_identity.as_slice().len(); - offsets.push(total_size); - total_size += self.checkpoint_cell_type_hash.as_slice().len(); - offsets.push(total_size); - total_size += self.node_identity.as_slice().len(); - writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; - for offset in offsets.into_iter() { - writer.write_all(&molecule::pack_number(offset as molecule::Number))?; - } - writer.write_all(self.admin_identity.as_slice())?; - writer.write_all(self.checkpoint_cell_type_hash.as_slice())?; - writer.write_all(self.node_identity.as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - WithdrawalLockArgs::new_unchecked(inner.into()) - } -} diff --git a/core/cross-client/src/generated/crosschain.rs b/core/cross-client/src/generated/crosschain.rs deleted file mode 100644 index 4dd784606..000000000 --- a/core/cross-client/src/generated/crosschain.rs +++ /dev/null @@ -1,6329 +0,0 @@ -// Generated by Molecule 0.7.2 - -use molecule::prelude::*; -#[derive(Clone)] -pub struct Uint32(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Uint32 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Uint32 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Uint32 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl ::core::default::Default for Uint32 { - fn default() -> Self { - let v: Vec = vec![0, 0, 0, 0]; - Uint32::new_unchecked(v.into()) - } -} -impl Uint32 { - pub const ITEM_COUNT: usize = 4; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 4; - - pub fn nth0(&self) -> Byte { - Byte::new_unchecked(self.0.slice(0..1)) - } - - pub fn nth1(&self) -> Byte { - Byte::new_unchecked(self.0.slice(1..2)) - } - - pub fn nth2(&self) -> Byte { - Byte::new_unchecked(self.0.slice(2..3)) - } - - pub fn nth3(&self) -> Byte { - Byte::new_unchecked(self.0.slice(3..4)) - } - - pub fn raw_data(&self) -> molecule::bytes::Bytes { - self.as_bytes() - } - - pub fn as_reader<'r>(&'r self) -> Uint32Reader<'r> { - Uint32Reader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Uint32 { - type Builder = Uint32Builder; - - const NAME: &'static str = "Uint32"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Uint32(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Uint32Reader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Uint32Reader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().set([self.nth0(), self.nth1(), self.nth2(), self.nth3()]) - } -} -#[derive(Clone, Copy)] -pub struct Uint32Reader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for Uint32Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for Uint32Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for Uint32Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl<'r> Uint32Reader<'r> { - pub const ITEM_COUNT: usize = 4; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 4; - - pub fn nth0(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[0..1]) - } - - pub fn nth1(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[1..2]) - } - - pub fn nth2(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[2..3]) - } - - pub fn nth3(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[3..4]) - } - - pub fn raw_data(&self) -> &'r [u8] { - self.as_slice() - } -} -impl<'r> molecule::prelude::Reader<'r> for Uint32Reader<'r> { - type Entity = Uint32; - - const NAME: &'static str = "Uint32Reader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - Uint32Reader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len != Self::TOTAL_SIZE { - return ve!(Self, TotalSizeNotMatch, Self::TOTAL_SIZE, slice_len); - } - Ok(()) - } -} -pub struct Uint32Builder(pub(crate) [Byte; 4]); -impl ::core::fmt::Debug for Uint32Builder { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:?})", Self::NAME, &self.0[..]) - } -} -impl ::core::default::Default for Uint32Builder { - fn default() -> Self { - Uint32Builder([ - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - ]) - } -} -impl Uint32Builder { - pub const ITEM_COUNT: usize = 4; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 4; - - pub fn set(mut self, v: [Byte; 4]) -> Self { - self.0 = v; - self - } - - pub fn nth0(mut self, v: Byte) -> Self { - self.0[0] = v; - self - } - - pub fn nth1(mut self, v: Byte) -> Self { - self.0[1] = v; - self - } - - pub fn nth2(mut self, v: Byte) -> Self { - self.0[2] = v; - self - } - - pub fn nth3(mut self, v: Byte) -> Self { - self.0[3] = v; - self - } -} -impl molecule::prelude::Builder for Uint32Builder { - type Entity = Uint32; - - const NAME: &'static str = "Uint32Builder"; - - fn expected_length(&self) -> usize { - Self::TOTAL_SIZE - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - writer.write_all(self.0[0].as_slice())?; - writer.write_all(self.0[1].as_slice())?; - writer.write_all(self.0[2].as_slice())?; - writer.write_all(self.0[3].as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Uint32::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct Uint64(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Uint64 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Uint64 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Uint64 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl ::core::default::Default for Uint64 { - fn default() -> Self { - let v: Vec = vec![0, 0, 0, 0, 0, 0, 0, 0]; - Uint64::new_unchecked(v.into()) - } -} -impl Uint64 { - pub const ITEM_COUNT: usize = 8; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 8; - - pub fn nth0(&self) -> Byte { - Byte::new_unchecked(self.0.slice(0..1)) - } - - pub fn nth1(&self) -> Byte { - Byte::new_unchecked(self.0.slice(1..2)) - } - - pub fn nth2(&self) -> Byte { - Byte::new_unchecked(self.0.slice(2..3)) - } - - pub fn nth3(&self) -> Byte { - Byte::new_unchecked(self.0.slice(3..4)) - } - - pub fn nth4(&self) -> Byte { - Byte::new_unchecked(self.0.slice(4..5)) - } - - pub fn nth5(&self) -> Byte { - Byte::new_unchecked(self.0.slice(5..6)) - } - - pub fn nth6(&self) -> Byte { - Byte::new_unchecked(self.0.slice(6..7)) - } - - pub fn nth7(&self) -> Byte { - Byte::new_unchecked(self.0.slice(7..8)) - } - - pub fn raw_data(&self) -> molecule::bytes::Bytes { - self.as_bytes() - } - - pub fn as_reader<'r>(&'r self) -> Uint64Reader<'r> { - Uint64Reader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Uint64 { - type Builder = Uint64Builder; - - const NAME: &'static str = "Uint64"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Uint64(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Uint64Reader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Uint64Reader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().set([ - self.nth0(), - self.nth1(), - self.nth2(), - self.nth3(), - self.nth4(), - self.nth5(), - self.nth6(), - self.nth7(), - ]) - } -} -#[derive(Clone, Copy)] -pub struct Uint64Reader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for Uint64Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for Uint64Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for Uint64Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl<'r> Uint64Reader<'r> { - pub const ITEM_COUNT: usize = 8; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 8; - - pub fn nth0(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[0..1]) - } - - pub fn nth1(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[1..2]) - } - - pub fn nth2(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[2..3]) - } - - pub fn nth3(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[3..4]) - } - - pub fn nth4(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[4..5]) - } - - pub fn nth5(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[5..6]) - } - - pub fn nth6(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[6..7]) - } - - pub fn nth7(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[7..8]) - } - - pub fn raw_data(&self) -> &'r [u8] { - self.as_slice() - } -} -impl<'r> molecule::prelude::Reader<'r> for Uint64Reader<'r> { - type Entity = Uint64; - - const NAME: &'static str = "Uint64Reader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - Uint64Reader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len != Self::TOTAL_SIZE { - return ve!(Self, TotalSizeNotMatch, Self::TOTAL_SIZE, slice_len); - } - Ok(()) - } -} -pub struct Uint64Builder(pub(crate) [Byte; 8]); -impl ::core::fmt::Debug for Uint64Builder { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:?})", Self::NAME, &self.0[..]) - } -} -impl ::core::default::Default for Uint64Builder { - fn default() -> Self { - Uint64Builder([ - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - ]) - } -} -impl Uint64Builder { - pub const ITEM_COUNT: usize = 8; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 8; - - pub fn set(mut self, v: [Byte; 8]) -> Self { - self.0 = v; - self - } - - pub fn nth0(mut self, v: Byte) -> Self { - self.0[0] = v; - self - } - - pub fn nth1(mut self, v: Byte) -> Self { - self.0[1] = v; - self - } - - pub fn nth2(mut self, v: Byte) -> Self { - self.0[2] = v; - self - } - - pub fn nth3(mut self, v: Byte) -> Self { - self.0[3] = v; - self - } - - pub fn nth4(mut self, v: Byte) -> Self { - self.0[4] = v; - self - } - - pub fn nth5(mut self, v: Byte) -> Self { - self.0[5] = v; - self - } - - pub fn nth6(mut self, v: Byte) -> Self { - self.0[6] = v; - self - } - - pub fn nth7(mut self, v: Byte) -> Self { - self.0[7] = v; - self - } -} -impl molecule::prelude::Builder for Uint64Builder { - type Entity = Uint64; - - const NAME: &'static str = "Uint64Builder"; - - fn expected_length(&self) -> usize { - Self::TOTAL_SIZE - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - writer.write_all(self.0[0].as_slice())?; - writer.write_all(self.0[1].as_slice())?; - writer.write_all(self.0[2].as_slice())?; - writer.write_all(self.0[3].as_slice())?; - writer.write_all(self.0[4].as_slice())?; - writer.write_all(self.0[5].as_slice())?; - writer.write_all(self.0[6].as_slice())?; - writer.write_all(self.0[7].as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Uint64::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct Uint128(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Uint128 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Uint128 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Uint128 { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl ::core::default::Default for Uint128 { - fn default() -> Self { - let v: Vec = vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - Uint128::new_unchecked(v.into()) - } -} -impl Uint128 { - pub const ITEM_COUNT: usize = 16; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 16; - - pub fn nth0(&self) -> Byte { - Byte::new_unchecked(self.0.slice(0..1)) - } - - pub fn nth1(&self) -> Byte { - Byte::new_unchecked(self.0.slice(1..2)) - } - - pub fn nth2(&self) -> Byte { - Byte::new_unchecked(self.0.slice(2..3)) - } - - pub fn nth3(&self) -> Byte { - Byte::new_unchecked(self.0.slice(3..4)) - } - - pub fn nth4(&self) -> Byte { - Byte::new_unchecked(self.0.slice(4..5)) - } - - pub fn nth5(&self) -> Byte { - Byte::new_unchecked(self.0.slice(5..6)) - } - - pub fn nth6(&self) -> Byte { - Byte::new_unchecked(self.0.slice(6..7)) - } - - pub fn nth7(&self) -> Byte { - Byte::new_unchecked(self.0.slice(7..8)) - } - - pub fn nth8(&self) -> Byte { - Byte::new_unchecked(self.0.slice(8..9)) - } - - pub fn nth9(&self) -> Byte { - Byte::new_unchecked(self.0.slice(9..10)) - } - - pub fn nth10(&self) -> Byte { - Byte::new_unchecked(self.0.slice(10..11)) - } - - pub fn nth11(&self) -> Byte { - Byte::new_unchecked(self.0.slice(11..12)) - } - - pub fn nth12(&self) -> Byte { - Byte::new_unchecked(self.0.slice(12..13)) - } - - pub fn nth13(&self) -> Byte { - Byte::new_unchecked(self.0.slice(13..14)) - } - - pub fn nth14(&self) -> Byte { - Byte::new_unchecked(self.0.slice(14..15)) - } - - pub fn nth15(&self) -> Byte { - Byte::new_unchecked(self.0.slice(15..16)) - } - - pub fn raw_data(&self) -> molecule::bytes::Bytes { - self.as_bytes() - } - - pub fn as_reader<'r>(&'r self) -> Uint128Reader<'r> { - Uint128Reader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Uint128 { - type Builder = Uint128Builder; - - const NAME: &'static str = "Uint128"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Uint128(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Uint128Reader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - Uint128Reader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().set([ - self.nth0(), - self.nth1(), - self.nth2(), - self.nth3(), - self.nth4(), - self.nth5(), - self.nth6(), - self.nth7(), - self.nth8(), - self.nth9(), - self.nth10(), - self.nth11(), - self.nth12(), - self.nth13(), - self.nth14(), - self.nth15(), - ]) - } -} -#[derive(Clone, Copy)] -pub struct Uint128Reader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for Uint128Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for Uint128Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for Uint128Reader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl<'r> Uint128Reader<'r> { - pub const ITEM_COUNT: usize = 16; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 16; - - pub fn nth0(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[0..1]) - } - - pub fn nth1(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[1..2]) - } - - pub fn nth2(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[2..3]) - } - - pub fn nth3(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[3..4]) - } - - pub fn nth4(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[4..5]) - } - - pub fn nth5(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[5..6]) - } - - pub fn nth6(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[6..7]) - } - - pub fn nth7(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[7..8]) - } - - pub fn nth8(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[8..9]) - } - - pub fn nth9(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[9..10]) - } - - pub fn nth10(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[10..11]) - } - - pub fn nth11(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[11..12]) - } - - pub fn nth12(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[12..13]) - } - - pub fn nth13(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[13..14]) - } - - pub fn nth14(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[14..15]) - } - - pub fn nth15(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[15..16]) - } - - pub fn raw_data(&self) -> &'r [u8] { - self.as_slice() - } -} -impl<'r> molecule::prelude::Reader<'r> for Uint128Reader<'r> { - type Entity = Uint128; - - const NAME: &'static str = "Uint128Reader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - Uint128Reader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len != Self::TOTAL_SIZE { - return ve!(Self, TotalSizeNotMatch, Self::TOTAL_SIZE, slice_len); - } - Ok(()) - } -} -pub struct Uint128Builder(pub(crate) [Byte; 16]); -impl ::core::fmt::Debug for Uint128Builder { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:?})", Self::NAME, &self.0[..]) - } -} -impl ::core::default::Default for Uint128Builder { - fn default() -> Self { - Uint128Builder([ - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - ]) - } -} -impl Uint128Builder { - pub const ITEM_COUNT: usize = 16; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 16; - - pub fn set(mut self, v: [Byte; 16]) -> Self { - self.0 = v; - self - } - - pub fn nth0(mut self, v: Byte) -> Self { - self.0[0] = v; - self - } - - pub fn nth1(mut self, v: Byte) -> Self { - self.0[1] = v; - self - } - - pub fn nth2(mut self, v: Byte) -> Self { - self.0[2] = v; - self - } - - pub fn nth3(mut self, v: Byte) -> Self { - self.0[3] = v; - self - } - - pub fn nth4(mut self, v: Byte) -> Self { - self.0[4] = v; - self - } - - pub fn nth5(mut self, v: Byte) -> Self { - self.0[5] = v; - self - } - - pub fn nth6(mut self, v: Byte) -> Self { - self.0[6] = v; - self - } - - pub fn nth7(mut self, v: Byte) -> Self { - self.0[7] = v; - self - } - - pub fn nth8(mut self, v: Byte) -> Self { - self.0[8] = v; - self - } - - pub fn nth9(mut self, v: Byte) -> Self { - self.0[9] = v; - self - } - - pub fn nth10(mut self, v: Byte) -> Self { - self.0[10] = v; - self - } - - pub fn nth11(mut self, v: Byte) -> Self { - self.0[11] = v; - self - } - - pub fn nth12(mut self, v: Byte) -> Self { - self.0[12] = v; - self - } - - pub fn nth13(mut self, v: Byte) -> Self { - self.0[13] = v; - self - } - - pub fn nth14(mut self, v: Byte) -> Self { - self.0[14] = v; - self - } - - pub fn nth15(mut self, v: Byte) -> Self { - self.0[15] = v; - self - } -} -impl molecule::prelude::Builder for Uint128Builder { - type Entity = Uint128; - - const NAME: &'static str = "Uint128Builder"; - - fn expected_length(&self) -> usize { - Self::TOTAL_SIZE - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - writer.write_all(self.0[0].as_slice())?; - writer.write_all(self.0[1].as_slice())?; - writer.write_all(self.0[2].as_slice())?; - writer.write_all(self.0[3].as_slice())?; - writer.write_all(self.0[4].as_slice())?; - writer.write_all(self.0[5].as_slice())?; - writer.write_all(self.0[6].as_slice())?; - writer.write_all(self.0[7].as_slice())?; - writer.write_all(self.0[8].as_slice())?; - writer.write_all(self.0[9].as_slice())?; - writer.write_all(self.0[10].as_slice())?; - writer.write_all(self.0[11].as_slice())?; - writer.write_all(self.0[12].as_slice())?; - writer.write_all(self.0[13].as_slice())?; - writer.write_all(self.0[14].as_slice())?; - writer.write_all(self.0[15].as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Uint128::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct Address(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Address { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Address { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Address { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl ::core::default::Default for Address { - fn default() -> Self { - let v: Vec = vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - Address::new_unchecked(v.into()) - } -} -impl Address { - pub const ITEM_COUNT: usize = 20; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 20; - - pub fn nth0(&self) -> Byte { - Byte::new_unchecked(self.0.slice(0..1)) - } - - pub fn nth1(&self) -> Byte { - Byte::new_unchecked(self.0.slice(1..2)) - } - - pub fn nth2(&self) -> Byte { - Byte::new_unchecked(self.0.slice(2..3)) - } - - pub fn nth3(&self) -> Byte { - Byte::new_unchecked(self.0.slice(3..4)) - } - - pub fn nth4(&self) -> Byte { - Byte::new_unchecked(self.0.slice(4..5)) - } - - pub fn nth5(&self) -> Byte { - Byte::new_unchecked(self.0.slice(5..6)) - } - - pub fn nth6(&self) -> Byte { - Byte::new_unchecked(self.0.slice(6..7)) - } - - pub fn nth7(&self) -> Byte { - Byte::new_unchecked(self.0.slice(7..8)) - } - - pub fn nth8(&self) -> Byte { - Byte::new_unchecked(self.0.slice(8..9)) - } - - pub fn nth9(&self) -> Byte { - Byte::new_unchecked(self.0.slice(9..10)) - } - - pub fn nth10(&self) -> Byte { - Byte::new_unchecked(self.0.slice(10..11)) - } - - pub fn nth11(&self) -> Byte { - Byte::new_unchecked(self.0.slice(11..12)) - } - - pub fn nth12(&self) -> Byte { - Byte::new_unchecked(self.0.slice(12..13)) - } - - pub fn nth13(&self) -> Byte { - Byte::new_unchecked(self.0.slice(13..14)) - } - - pub fn nth14(&self) -> Byte { - Byte::new_unchecked(self.0.slice(14..15)) - } - - pub fn nth15(&self) -> Byte { - Byte::new_unchecked(self.0.slice(15..16)) - } - - pub fn nth16(&self) -> Byte { - Byte::new_unchecked(self.0.slice(16..17)) - } - - pub fn nth17(&self) -> Byte { - Byte::new_unchecked(self.0.slice(17..18)) - } - - pub fn nth18(&self) -> Byte { - Byte::new_unchecked(self.0.slice(18..19)) - } - - pub fn nth19(&self) -> Byte { - Byte::new_unchecked(self.0.slice(19..20)) - } - - pub fn raw_data(&self) -> molecule::bytes::Bytes { - self.as_bytes() - } - - pub fn as_reader<'r>(&'r self) -> AddressReader<'r> { - AddressReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Address { - type Builder = AddressBuilder; - - const NAME: &'static str = "Address"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Address(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - AddressReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - AddressReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().set([ - self.nth0(), - self.nth1(), - self.nth2(), - self.nth3(), - self.nth4(), - self.nth5(), - self.nth6(), - self.nth7(), - self.nth8(), - self.nth9(), - self.nth10(), - self.nth11(), - self.nth12(), - self.nth13(), - self.nth14(), - self.nth15(), - self.nth16(), - self.nth17(), - self.nth18(), - self.nth19(), - ]) - } -} -#[derive(Clone, Copy)] -pub struct AddressReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for AddressReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for AddressReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for AddressReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl<'r> AddressReader<'r> { - pub const ITEM_COUNT: usize = 20; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 20; - - pub fn nth0(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[0..1]) - } - - pub fn nth1(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[1..2]) - } - - pub fn nth2(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[2..3]) - } - - pub fn nth3(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[3..4]) - } - - pub fn nth4(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[4..5]) - } - - pub fn nth5(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[5..6]) - } - - pub fn nth6(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[6..7]) - } - - pub fn nth7(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[7..8]) - } - - pub fn nth8(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[8..9]) - } - - pub fn nth9(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[9..10]) - } - - pub fn nth10(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[10..11]) - } - - pub fn nth11(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[11..12]) - } - - pub fn nth12(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[12..13]) - } - - pub fn nth13(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[13..14]) - } - - pub fn nth14(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[14..15]) - } - - pub fn nth15(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[15..16]) - } - - pub fn nth16(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[16..17]) - } - - pub fn nth17(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[17..18]) - } - - pub fn nth18(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[18..19]) - } - - pub fn nth19(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[19..20]) - } - - pub fn raw_data(&self) -> &'r [u8] { - self.as_slice() - } -} -impl<'r> molecule::prelude::Reader<'r> for AddressReader<'r> { - type Entity = Address; - - const NAME: &'static str = "AddressReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - AddressReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len != Self::TOTAL_SIZE { - return ve!(Self, TotalSizeNotMatch, Self::TOTAL_SIZE, slice_len); - } - Ok(()) - } -} -pub struct AddressBuilder(pub(crate) [Byte; 20]); -impl ::core::fmt::Debug for AddressBuilder { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:?})", Self::NAME, &self.0[..]) - } -} -impl ::core::default::Default for AddressBuilder { - fn default() -> Self { - AddressBuilder([ - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - ]) - } -} -impl AddressBuilder { - pub const ITEM_COUNT: usize = 20; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 20; - - pub fn set(mut self, v: [Byte; 20]) -> Self { - self.0 = v; - self - } - - pub fn nth0(mut self, v: Byte) -> Self { - self.0[0] = v; - self - } - - pub fn nth1(mut self, v: Byte) -> Self { - self.0[1] = v; - self - } - - pub fn nth2(mut self, v: Byte) -> Self { - self.0[2] = v; - self - } - - pub fn nth3(mut self, v: Byte) -> Self { - self.0[3] = v; - self - } - - pub fn nth4(mut self, v: Byte) -> Self { - self.0[4] = v; - self - } - - pub fn nth5(mut self, v: Byte) -> Self { - self.0[5] = v; - self - } - - pub fn nth6(mut self, v: Byte) -> Self { - self.0[6] = v; - self - } - - pub fn nth7(mut self, v: Byte) -> Self { - self.0[7] = v; - self - } - - pub fn nth8(mut self, v: Byte) -> Self { - self.0[8] = v; - self - } - - pub fn nth9(mut self, v: Byte) -> Self { - self.0[9] = v; - self - } - - pub fn nth10(mut self, v: Byte) -> Self { - self.0[10] = v; - self - } - - pub fn nth11(mut self, v: Byte) -> Self { - self.0[11] = v; - self - } - - pub fn nth12(mut self, v: Byte) -> Self { - self.0[12] = v; - self - } - - pub fn nth13(mut self, v: Byte) -> Self { - self.0[13] = v; - self - } - - pub fn nth14(mut self, v: Byte) -> Self { - self.0[14] = v; - self - } - - pub fn nth15(mut self, v: Byte) -> Self { - self.0[15] = v; - self - } - - pub fn nth16(mut self, v: Byte) -> Self { - self.0[16] = v; - self - } - - pub fn nth17(mut self, v: Byte) -> Self { - self.0[17] = v; - self - } - - pub fn nth18(mut self, v: Byte) -> Self { - self.0[18] = v; - self - } - - pub fn nth19(mut self, v: Byte) -> Self { - self.0[19] = v; - self - } -} -impl molecule::prelude::Builder for AddressBuilder { - type Entity = Address; - - const NAME: &'static str = "AddressBuilder"; - - fn expected_length(&self) -> usize { - Self::TOTAL_SIZE - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - writer.write_all(self.0[0].as_slice())?; - writer.write_all(self.0[1].as_slice())?; - writer.write_all(self.0[2].as_slice())?; - writer.write_all(self.0[3].as_slice())?; - writer.write_all(self.0[4].as_slice())?; - writer.write_all(self.0[5].as_slice())?; - writer.write_all(self.0[6].as_slice())?; - writer.write_all(self.0[7].as_slice())?; - writer.write_all(self.0[8].as_slice())?; - writer.write_all(self.0[9].as_slice())?; - writer.write_all(self.0[10].as_slice())?; - writer.write_all(self.0[11].as_slice())?; - writer.write_all(self.0[12].as_slice())?; - writer.write_all(self.0[13].as_slice())?; - writer.write_all(self.0[14].as_slice())?; - writer.write_all(self.0[15].as_slice())?; - writer.write_all(self.0[16].as_slice())?; - writer.write_all(self.0[17].as_slice())?; - writer.write_all(self.0[18].as_slice())?; - writer.write_all(self.0[19].as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Address::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct Hash(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Hash { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Hash { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Hash { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl ::core::default::Default for Hash { - fn default() -> Self { - let v: Vec = vec![ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, - ]; - Hash::new_unchecked(v.into()) - } -} -impl Hash { - pub const ITEM_COUNT: usize = 32; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 32; - - pub fn nth0(&self) -> Byte { - Byte::new_unchecked(self.0.slice(0..1)) - } - - pub fn nth1(&self) -> Byte { - Byte::new_unchecked(self.0.slice(1..2)) - } - - pub fn nth2(&self) -> Byte { - Byte::new_unchecked(self.0.slice(2..3)) - } - - pub fn nth3(&self) -> Byte { - Byte::new_unchecked(self.0.slice(3..4)) - } - - pub fn nth4(&self) -> Byte { - Byte::new_unchecked(self.0.slice(4..5)) - } - - pub fn nth5(&self) -> Byte { - Byte::new_unchecked(self.0.slice(5..6)) - } - - pub fn nth6(&self) -> Byte { - Byte::new_unchecked(self.0.slice(6..7)) - } - - pub fn nth7(&self) -> Byte { - Byte::new_unchecked(self.0.slice(7..8)) - } - - pub fn nth8(&self) -> Byte { - Byte::new_unchecked(self.0.slice(8..9)) - } - - pub fn nth9(&self) -> Byte { - Byte::new_unchecked(self.0.slice(9..10)) - } - - pub fn nth10(&self) -> Byte { - Byte::new_unchecked(self.0.slice(10..11)) - } - - pub fn nth11(&self) -> Byte { - Byte::new_unchecked(self.0.slice(11..12)) - } - - pub fn nth12(&self) -> Byte { - Byte::new_unchecked(self.0.slice(12..13)) - } - - pub fn nth13(&self) -> Byte { - Byte::new_unchecked(self.0.slice(13..14)) - } - - pub fn nth14(&self) -> Byte { - Byte::new_unchecked(self.0.slice(14..15)) - } - - pub fn nth15(&self) -> Byte { - Byte::new_unchecked(self.0.slice(15..16)) - } - - pub fn nth16(&self) -> Byte { - Byte::new_unchecked(self.0.slice(16..17)) - } - - pub fn nth17(&self) -> Byte { - Byte::new_unchecked(self.0.slice(17..18)) - } - - pub fn nth18(&self) -> Byte { - Byte::new_unchecked(self.0.slice(18..19)) - } - - pub fn nth19(&self) -> Byte { - Byte::new_unchecked(self.0.slice(19..20)) - } - - pub fn nth20(&self) -> Byte { - Byte::new_unchecked(self.0.slice(20..21)) - } - - pub fn nth21(&self) -> Byte { - Byte::new_unchecked(self.0.slice(21..22)) - } - - pub fn nth22(&self) -> Byte { - Byte::new_unchecked(self.0.slice(22..23)) - } - - pub fn nth23(&self) -> Byte { - Byte::new_unchecked(self.0.slice(23..24)) - } - - pub fn nth24(&self) -> Byte { - Byte::new_unchecked(self.0.slice(24..25)) - } - - pub fn nth25(&self) -> Byte { - Byte::new_unchecked(self.0.slice(25..26)) - } - - pub fn nth26(&self) -> Byte { - Byte::new_unchecked(self.0.slice(26..27)) - } - - pub fn nth27(&self) -> Byte { - Byte::new_unchecked(self.0.slice(27..28)) - } - - pub fn nth28(&self) -> Byte { - Byte::new_unchecked(self.0.slice(28..29)) - } - - pub fn nth29(&self) -> Byte { - Byte::new_unchecked(self.0.slice(29..30)) - } - - pub fn nth30(&self) -> Byte { - Byte::new_unchecked(self.0.slice(30..31)) - } - - pub fn nth31(&self) -> Byte { - Byte::new_unchecked(self.0.slice(31..32)) - } - - pub fn raw_data(&self) -> molecule::bytes::Bytes { - self.as_bytes() - } - - pub fn as_reader<'r>(&'r self) -> HashReader<'r> { - HashReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Hash { - type Builder = HashBuilder; - - const NAME: &'static str = "Hash"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Hash(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - HashReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - HashReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().set([ - self.nth0(), - self.nth1(), - self.nth2(), - self.nth3(), - self.nth4(), - self.nth5(), - self.nth6(), - self.nth7(), - self.nth8(), - self.nth9(), - self.nth10(), - self.nth11(), - self.nth12(), - self.nth13(), - self.nth14(), - self.nth15(), - self.nth16(), - self.nth17(), - self.nth18(), - self.nth19(), - self.nth20(), - self.nth21(), - self.nth22(), - self.nth23(), - self.nth24(), - self.nth25(), - self.nth26(), - self.nth27(), - self.nth28(), - self.nth29(), - self.nth30(), - self.nth31(), - ]) - } -} -#[derive(Clone, Copy)] -pub struct HashReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for HashReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for HashReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for HashReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl<'r> HashReader<'r> { - pub const ITEM_COUNT: usize = 32; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 32; - - pub fn nth0(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[0..1]) - } - - pub fn nth1(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[1..2]) - } - - pub fn nth2(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[2..3]) - } - - pub fn nth3(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[3..4]) - } - - pub fn nth4(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[4..5]) - } - - pub fn nth5(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[5..6]) - } - - pub fn nth6(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[6..7]) - } - - pub fn nth7(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[7..8]) - } - - pub fn nth8(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[8..9]) - } - - pub fn nth9(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[9..10]) - } - - pub fn nth10(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[10..11]) - } - - pub fn nth11(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[11..12]) - } - - pub fn nth12(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[12..13]) - } - - pub fn nth13(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[13..14]) - } - - pub fn nth14(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[14..15]) - } - - pub fn nth15(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[15..16]) - } - - pub fn nth16(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[16..17]) - } - - pub fn nth17(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[17..18]) - } - - pub fn nth18(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[18..19]) - } - - pub fn nth19(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[19..20]) - } - - pub fn nth20(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[20..21]) - } - - pub fn nth21(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[21..22]) - } - - pub fn nth22(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[22..23]) - } - - pub fn nth23(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[23..24]) - } - - pub fn nth24(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[24..25]) - } - - pub fn nth25(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[25..26]) - } - - pub fn nth26(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[26..27]) - } - - pub fn nth27(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[27..28]) - } - - pub fn nth28(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[28..29]) - } - - pub fn nth29(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[29..30]) - } - - pub fn nth30(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[30..31]) - } - - pub fn nth31(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[31..32]) - } - - pub fn raw_data(&self) -> &'r [u8] { - self.as_slice() - } -} -impl<'r> molecule::prelude::Reader<'r> for HashReader<'r> { - type Entity = Hash; - - const NAME: &'static str = "HashReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - HashReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len != Self::TOTAL_SIZE { - return ve!(Self, TotalSizeNotMatch, Self::TOTAL_SIZE, slice_len); - } - Ok(()) - } -} -pub struct HashBuilder(pub(crate) [Byte; 32]); -impl ::core::fmt::Debug for HashBuilder { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:?})", Self::NAME, &self.0[..]) - } -} -impl ::core::default::Default for HashBuilder { - fn default() -> Self { - HashBuilder([ - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - ]) - } -} -impl HashBuilder { - pub const ITEM_COUNT: usize = 32; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 32; - - pub fn set(mut self, v: [Byte; 32]) -> Self { - self.0 = v; - self - } - - pub fn nth0(mut self, v: Byte) -> Self { - self.0[0] = v; - self - } - - pub fn nth1(mut self, v: Byte) -> Self { - self.0[1] = v; - self - } - - pub fn nth2(mut self, v: Byte) -> Self { - self.0[2] = v; - self - } - - pub fn nth3(mut self, v: Byte) -> Self { - self.0[3] = v; - self - } - - pub fn nth4(mut self, v: Byte) -> Self { - self.0[4] = v; - self - } - - pub fn nth5(mut self, v: Byte) -> Self { - self.0[5] = v; - self - } - - pub fn nth6(mut self, v: Byte) -> Self { - self.0[6] = v; - self - } - - pub fn nth7(mut self, v: Byte) -> Self { - self.0[7] = v; - self - } - - pub fn nth8(mut self, v: Byte) -> Self { - self.0[8] = v; - self - } - - pub fn nth9(mut self, v: Byte) -> Self { - self.0[9] = v; - self - } - - pub fn nth10(mut self, v: Byte) -> Self { - self.0[10] = v; - self - } - - pub fn nth11(mut self, v: Byte) -> Self { - self.0[11] = v; - self - } - - pub fn nth12(mut self, v: Byte) -> Self { - self.0[12] = v; - self - } - - pub fn nth13(mut self, v: Byte) -> Self { - self.0[13] = v; - self - } - - pub fn nth14(mut self, v: Byte) -> Self { - self.0[14] = v; - self - } - - pub fn nth15(mut self, v: Byte) -> Self { - self.0[15] = v; - self - } - - pub fn nth16(mut self, v: Byte) -> Self { - self.0[16] = v; - self - } - - pub fn nth17(mut self, v: Byte) -> Self { - self.0[17] = v; - self - } - - pub fn nth18(mut self, v: Byte) -> Self { - self.0[18] = v; - self - } - - pub fn nth19(mut self, v: Byte) -> Self { - self.0[19] = v; - self - } - - pub fn nth20(mut self, v: Byte) -> Self { - self.0[20] = v; - self - } - - pub fn nth21(mut self, v: Byte) -> Self { - self.0[21] = v; - self - } - - pub fn nth22(mut self, v: Byte) -> Self { - self.0[22] = v; - self - } - - pub fn nth23(mut self, v: Byte) -> Self { - self.0[23] = v; - self - } - - pub fn nth24(mut self, v: Byte) -> Self { - self.0[24] = v; - self - } - - pub fn nth25(mut self, v: Byte) -> Self { - self.0[25] = v; - self - } - - pub fn nth26(mut self, v: Byte) -> Self { - self.0[26] = v; - self - } - - pub fn nth27(mut self, v: Byte) -> Self { - self.0[27] = v; - self - } - - pub fn nth28(mut self, v: Byte) -> Self { - self.0[28] = v; - self - } - - pub fn nth29(mut self, v: Byte) -> Self { - self.0[29] = v; - self - } - - pub fn nth30(mut self, v: Byte) -> Self { - self.0[30] = v; - self - } - - pub fn nth31(mut self, v: Byte) -> Self { - self.0[31] = v; - self - } -} -impl molecule::prelude::Builder for HashBuilder { - type Entity = Hash; - - const NAME: &'static str = "HashBuilder"; - - fn expected_length(&self) -> usize { - Self::TOTAL_SIZE - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - writer.write_all(self.0[0].as_slice())?; - writer.write_all(self.0[1].as_slice())?; - writer.write_all(self.0[2].as_slice())?; - writer.write_all(self.0[3].as_slice())?; - writer.write_all(self.0[4].as_slice())?; - writer.write_all(self.0[5].as_slice())?; - writer.write_all(self.0[6].as_slice())?; - writer.write_all(self.0[7].as_slice())?; - writer.write_all(self.0[8].as_slice())?; - writer.write_all(self.0[9].as_slice())?; - writer.write_all(self.0[10].as_slice())?; - writer.write_all(self.0[11].as_slice())?; - writer.write_all(self.0[12].as_slice())?; - writer.write_all(self.0[13].as_slice())?; - writer.write_all(self.0[14].as_slice())?; - writer.write_all(self.0[15].as_slice())?; - writer.write_all(self.0[16].as_slice())?; - writer.write_all(self.0[17].as_slice())?; - writer.write_all(self.0[18].as_slice())?; - writer.write_all(self.0[19].as_slice())?; - writer.write_all(self.0[20].as_slice())?; - writer.write_all(self.0[21].as_slice())?; - writer.write_all(self.0[22].as_slice())?; - writer.write_all(self.0[23].as_slice())?; - writer.write_all(self.0[24].as_slice())?; - writer.write_all(self.0[25].as_slice())?; - writer.write_all(self.0[26].as_slice())?; - writer.write_all(self.0[27].as_slice())?; - writer.write_all(self.0[28].as_slice())?; - writer.write_all(self.0[29].as_slice())?; - writer.write_all(self.0[30].as_slice())?; - writer.write_all(self.0[31].as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Hash::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct BlsPubkey(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for BlsPubkey { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for BlsPubkey { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for BlsPubkey { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl ::core::default::Default for BlsPubkey { - fn default() -> Self { - let v: Vec = vec![ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - BlsPubkey::new_unchecked(v.into()) - } -} -impl BlsPubkey { - pub const ITEM_COUNT: usize = 48; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 48; - - pub fn nth0(&self) -> Byte { - Byte::new_unchecked(self.0.slice(0..1)) - } - - pub fn nth1(&self) -> Byte { - Byte::new_unchecked(self.0.slice(1..2)) - } - - pub fn nth2(&self) -> Byte { - Byte::new_unchecked(self.0.slice(2..3)) - } - - pub fn nth3(&self) -> Byte { - Byte::new_unchecked(self.0.slice(3..4)) - } - - pub fn nth4(&self) -> Byte { - Byte::new_unchecked(self.0.slice(4..5)) - } - - pub fn nth5(&self) -> Byte { - Byte::new_unchecked(self.0.slice(5..6)) - } - - pub fn nth6(&self) -> Byte { - Byte::new_unchecked(self.0.slice(6..7)) - } - - pub fn nth7(&self) -> Byte { - Byte::new_unchecked(self.0.slice(7..8)) - } - - pub fn nth8(&self) -> Byte { - Byte::new_unchecked(self.0.slice(8..9)) - } - - pub fn nth9(&self) -> Byte { - Byte::new_unchecked(self.0.slice(9..10)) - } - - pub fn nth10(&self) -> Byte { - Byte::new_unchecked(self.0.slice(10..11)) - } - - pub fn nth11(&self) -> Byte { - Byte::new_unchecked(self.0.slice(11..12)) - } - - pub fn nth12(&self) -> Byte { - Byte::new_unchecked(self.0.slice(12..13)) - } - - pub fn nth13(&self) -> Byte { - Byte::new_unchecked(self.0.slice(13..14)) - } - - pub fn nth14(&self) -> Byte { - Byte::new_unchecked(self.0.slice(14..15)) - } - - pub fn nth15(&self) -> Byte { - Byte::new_unchecked(self.0.slice(15..16)) - } - - pub fn nth16(&self) -> Byte { - Byte::new_unchecked(self.0.slice(16..17)) - } - - pub fn nth17(&self) -> Byte { - Byte::new_unchecked(self.0.slice(17..18)) - } - - pub fn nth18(&self) -> Byte { - Byte::new_unchecked(self.0.slice(18..19)) - } - - pub fn nth19(&self) -> Byte { - Byte::new_unchecked(self.0.slice(19..20)) - } - - pub fn nth20(&self) -> Byte { - Byte::new_unchecked(self.0.slice(20..21)) - } - - pub fn nth21(&self) -> Byte { - Byte::new_unchecked(self.0.slice(21..22)) - } - - pub fn nth22(&self) -> Byte { - Byte::new_unchecked(self.0.slice(22..23)) - } - - pub fn nth23(&self) -> Byte { - Byte::new_unchecked(self.0.slice(23..24)) - } - - pub fn nth24(&self) -> Byte { - Byte::new_unchecked(self.0.slice(24..25)) - } - - pub fn nth25(&self) -> Byte { - Byte::new_unchecked(self.0.slice(25..26)) - } - - pub fn nth26(&self) -> Byte { - Byte::new_unchecked(self.0.slice(26..27)) - } - - pub fn nth27(&self) -> Byte { - Byte::new_unchecked(self.0.slice(27..28)) - } - - pub fn nth28(&self) -> Byte { - Byte::new_unchecked(self.0.slice(28..29)) - } - - pub fn nth29(&self) -> Byte { - Byte::new_unchecked(self.0.slice(29..30)) - } - - pub fn nth30(&self) -> Byte { - Byte::new_unchecked(self.0.slice(30..31)) - } - - pub fn nth31(&self) -> Byte { - Byte::new_unchecked(self.0.slice(31..32)) - } - - pub fn nth32(&self) -> Byte { - Byte::new_unchecked(self.0.slice(32..33)) - } - - pub fn nth33(&self) -> Byte { - Byte::new_unchecked(self.0.slice(33..34)) - } - - pub fn nth34(&self) -> Byte { - Byte::new_unchecked(self.0.slice(34..35)) - } - - pub fn nth35(&self) -> Byte { - Byte::new_unchecked(self.0.slice(35..36)) - } - - pub fn nth36(&self) -> Byte { - Byte::new_unchecked(self.0.slice(36..37)) - } - - pub fn nth37(&self) -> Byte { - Byte::new_unchecked(self.0.slice(37..38)) - } - - pub fn nth38(&self) -> Byte { - Byte::new_unchecked(self.0.slice(38..39)) - } - - pub fn nth39(&self) -> Byte { - Byte::new_unchecked(self.0.slice(39..40)) - } - - pub fn nth40(&self) -> Byte { - Byte::new_unchecked(self.0.slice(40..41)) - } - - pub fn nth41(&self) -> Byte { - Byte::new_unchecked(self.0.slice(41..42)) - } - - pub fn nth42(&self) -> Byte { - Byte::new_unchecked(self.0.slice(42..43)) - } - - pub fn nth43(&self) -> Byte { - Byte::new_unchecked(self.0.slice(43..44)) - } - - pub fn nth44(&self) -> Byte { - Byte::new_unchecked(self.0.slice(44..45)) - } - - pub fn nth45(&self) -> Byte { - Byte::new_unchecked(self.0.slice(45..46)) - } - - pub fn nth46(&self) -> Byte { - Byte::new_unchecked(self.0.slice(46..47)) - } - - pub fn nth47(&self) -> Byte { - Byte::new_unchecked(self.0.slice(47..48)) - } - - pub fn raw_data(&self) -> molecule::bytes::Bytes { - self.as_bytes() - } - - pub fn as_reader<'r>(&'r self) -> BlsPubkeyReader<'r> { - BlsPubkeyReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for BlsPubkey { - type Builder = BlsPubkeyBuilder; - - const NAME: &'static str = "BlsPubkey"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - BlsPubkey(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - BlsPubkeyReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - BlsPubkeyReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().set([ - self.nth0(), - self.nth1(), - self.nth2(), - self.nth3(), - self.nth4(), - self.nth5(), - self.nth6(), - self.nth7(), - self.nth8(), - self.nth9(), - self.nth10(), - self.nth11(), - self.nth12(), - self.nth13(), - self.nth14(), - self.nth15(), - self.nth16(), - self.nth17(), - self.nth18(), - self.nth19(), - self.nth20(), - self.nth21(), - self.nth22(), - self.nth23(), - self.nth24(), - self.nth25(), - self.nth26(), - self.nth27(), - self.nth28(), - self.nth29(), - self.nth30(), - self.nth31(), - self.nth32(), - self.nth33(), - self.nth34(), - self.nth35(), - self.nth36(), - self.nth37(), - self.nth38(), - self.nth39(), - self.nth40(), - self.nth41(), - self.nth42(), - self.nth43(), - self.nth44(), - self.nth45(), - self.nth46(), - self.nth47(), - ]) - } -} -#[derive(Clone, Copy)] -pub struct BlsPubkeyReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for BlsPubkeyReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for BlsPubkeyReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for BlsPubkeyReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl<'r> BlsPubkeyReader<'r> { - pub const ITEM_COUNT: usize = 48; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 48; - - pub fn nth0(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[0..1]) - } - - pub fn nth1(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[1..2]) - } - - pub fn nth2(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[2..3]) - } - - pub fn nth3(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[3..4]) - } - - pub fn nth4(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[4..5]) - } - - pub fn nth5(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[5..6]) - } - - pub fn nth6(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[6..7]) - } - - pub fn nth7(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[7..8]) - } - - pub fn nth8(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[8..9]) - } - - pub fn nth9(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[9..10]) - } - - pub fn nth10(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[10..11]) - } - - pub fn nth11(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[11..12]) - } - - pub fn nth12(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[12..13]) - } - - pub fn nth13(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[13..14]) - } - - pub fn nth14(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[14..15]) - } - - pub fn nth15(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[15..16]) - } - - pub fn nth16(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[16..17]) - } - - pub fn nth17(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[17..18]) - } - - pub fn nth18(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[18..19]) - } - - pub fn nth19(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[19..20]) - } - - pub fn nth20(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[20..21]) - } - - pub fn nth21(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[21..22]) - } - - pub fn nth22(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[22..23]) - } - - pub fn nth23(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[23..24]) - } - - pub fn nth24(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[24..25]) - } - - pub fn nth25(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[25..26]) - } - - pub fn nth26(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[26..27]) - } - - pub fn nth27(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[27..28]) - } - - pub fn nth28(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[28..29]) - } - - pub fn nth29(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[29..30]) - } - - pub fn nth30(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[30..31]) - } - - pub fn nth31(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[31..32]) - } - - pub fn nth32(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[32..33]) - } - - pub fn nth33(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[33..34]) - } - - pub fn nth34(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[34..35]) - } - - pub fn nth35(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[35..36]) - } - - pub fn nth36(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[36..37]) - } - - pub fn nth37(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[37..38]) - } - - pub fn nth38(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[38..39]) - } - - pub fn nth39(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[39..40]) - } - - pub fn nth40(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[40..41]) - } - - pub fn nth41(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[41..42]) - } - - pub fn nth42(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[42..43]) - } - - pub fn nth43(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[43..44]) - } - - pub fn nth44(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[44..45]) - } - - pub fn nth45(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[45..46]) - } - - pub fn nth46(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[46..47]) - } - - pub fn nth47(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[47..48]) - } - - pub fn raw_data(&self) -> &'r [u8] { - self.as_slice() - } -} -impl<'r> molecule::prelude::Reader<'r> for BlsPubkeyReader<'r> { - type Entity = BlsPubkey; - - const NAME: &'static str = "BlsPubkeyReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - BlsPubkeyReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len != Self::TOTAL_SIZE { - return ve!(Self, TotalSizeNotMatch, Self::TOTAL_SIZE, slice_len); - } - Ok(()) - } -} -pub struct BlsPubkeyBuilder(pub(crate) [Byte; 48]); -impl ::core::fmt::Debug for BlsPubkeyBuilder { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:?})", Self::NAME, &self.0[..]) - } -} -impl ::core::default::Default for BlsPubkeyBuilder { - fn default() -> Self { - BlsPubkeyBuilder([ - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - ]) - } -} -impl BlsPubkeyBuilder { - pub const ITEM_COUNT: usize = 48; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 48; - - pub fn set(mut self, v: [Byte; 48]) -> Self { - self.0 = v; - self - } - - pub fn nth0(mut self, v: Byte) -> Self { - self.0[0] = v; - self - } - - pub fn nth1(mut self, v: Byte) -> Self { - self.0[1] = v; - self - } - - pub fn nth2(mut self, v: Byte) -> Self { - self.0[2] = v; - self - } - - pub fn nth3(mut self, v: Byte) -> Self { - self.0[3] = v; - self - } - - pub fn nth4(mut self, v: Byte) -> Self { - self.0[4] = v; - self - } - - pub fn nth5(mut self, v: Byte) -> Self { - self.0[5] = v; - self - } - - pub fn nth6(mut self, v: Byte) -> Self { - self.0[6] = v; - self - } - - pub fn nth7(mut self, v: Byte) -> Self { - self.0[7] = v; - self - } - - pub fn nth8(mut self, v: Byte) -> Self { - self.0[8] = v; - self - } - - pub fn nth9(mut self, v: Byte) -> Self { - self.0[9] = v; - self - } - - pub fn nth10(mut self, v: Byte) -> Self { - self.0[10] = v; - self - } - - pub fn nth11(mut self, v: Byte) -> Self { - self.0[11] = v; - self - } - - pub fn nth12(mut self, v: Byte) -> Self { - self.0[12] = v; - self - } - - pub fn nth13(mut self, v: Byte) -> Self { - self.0[13] = v; - self - } - - pub fn nth14(mut self, v: Byte) -> Self { - self.0[14] = v; - self - } - - pub fn nth15(mut self, v: Byte) -> Self { - self.0[15] = v; - self - } - - pub fn nth16(mut self, v: Byte) -> Self { - self.0[16] = v; - self - } - - pub fn nth17(mut self, v: Byte) -> Self { - self.0[17] = v; - self - } - - pub fn nth18(mut self, v: Byte) -> Self { - self.0[18] = v; - self - } - - pub fn nth19(mut self, v: Byte) -> Self { - self.0[19] = v; - self - } - - pub fn nth20(mut self, v: Byte) -> Self { - self.0[20] = v; - self - } - - pub fn nth21(mut self, v: Byte) -> Self { - self.0[21] = v; - self - } - - pub fn nth22(mut self, v: Byte) -> Self { - self.0[22] = v; - self - } - - pub fn nth23(mut self, v: Byte) -> Self { - self.0[23] = v; - self - } - - pub fn nth24(mut self, v: Byte) -> Self { - self.0[24] = v; - self - } - - pub fn nth25(mut self, v: Byte) -> Self { - self.0[25] = v; - self - } - - pub fn nth26(mut self, v: Byte) -> Self { - self.0[26] = v; - self - } - - pub fn nth27(mut self, v: Byte) -> Self { - self.0[27] = v; - self - } - - pub fn nth28(mut self, v: Byte) -> Self { - self.0[28] = v; - self - } - - pub fn nth29(mut self, v: Byte) -> Self { - self.0[29] = v; - self - } - - pub fn nth30(mut self, v: Byte) -> Self { - self.0[30] = v; - self - } - - pub fn nth31(mut self, v: Byte) -> Self { - self.0[31] = v; - self - } - - pub fn nth32(mut self, v: Byte) -> Self { - self.0[32] = v; - self - } - - pub fn nth33(mut self, v: Byte) -> Self { - self.0[33] = v; - self - } - - pub fn nth34(mut self, v: Byte) -> Self { - self.0[34] = v; - self - } - - pub fn nth35(mut self, v: Byte) -> Self { - self.0[35] = v; - self - } - - pub fn nth36(mut self, v: Byte) -> Self { - self.0[36] = v; - self - } - - pub fn nth37(mut self, v: Byte) -> Self { - self.0[37] = v; - self - } - - pub fn nth38(mut self, v: Byte) -> Self { - self.0[38] = v; - self - } - - pub fn nth39(mut self, v: Byte) -> Self { - self.0[39] = v; - self - } - - pub fn nth40(mut self, v: Byte) -> Self { - self.0[40] = v; - self - } - - pub fn nth41(mut self, v: Byte) -> Self { - self.0[41] = v; - self - } - - pub fn nth42(mut self, v: Byte) -> Self { - self.0[42] = v; - self - } - - pub fn nth43(mut self, v: Byte) -> Self { - self.0[43] = v; - self - } - - pub fn nth44(mut self, v: Byte) -> Self { - self.0[44] = v; - self - } - - pub fn nth45(mut self, v: Byte) -> Self { - self.0[45] = v; - self - } - - pub fn nth46(mut self, v: Byte) -> Self { - self.0[46] = v; - self - } - - pub fn nth47(mut self, v: Byte) -> Self { - self.0[47] = v; - self - } -} -impl molecule::prelude::Builder for BlsPubkeyBuilder { - type Entity = BlsPubkey; - - const NAME: &'static str = "BlsPubkeyBuilder"; - - fn expected_length(&self) -> usize { - Self::TOTAL_SIZE - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - writer.write_all(self.0[0].as_slice())?; - writer.write_all(self.0[1].as_slice())?; - writer.write_all(self.0[2].as_slice())?; - writer.write_all(self.0[3].as_slice())?; - writer.write_all(self.0[4].as_slice())?; - writer.write_all(self.0[5].as_slice())?; - writer.write_all(self.0[6].as_slice())?; - writer.write_all(self.0[7].as_slice())?; - writer.write_all(self.0[8].as_slice())?; - writer.write_all(self.0[9].as_slice())?; - writer.write_all(self.0[10].as_slice())?; - writer.write_all(self.0[11].as_slice())?; - writer.write_all(self.0[12].as_slice())?; - writer.write_all(self.0[13].as_slice())?; - writer.write_all(self.0[14].as_slice())?; - writer.write_all(self.0[15].as_slice())?; - writer.write_all(self.0[16].as_slice())?; - writer.write_all(self.0[17].as_slice())?; - writer.write_all(self.0[18].as_slice())?; - writer.write_all(self.0[19].as_slice())?; - writer.write_all(self.0[20].as_slice())?; - writer.write_all(self.0[21].as_slice())?; - writer.write_all(self.0[22].as_slice())?; - writer.write_all(self.0[23].as_slice())?; - writer.write_all(self.0[24].as_slice())?; - writer.write_all(self.0[25].as_slice())?; - writer.write_all(self.0[26].as_slice())?; - writer.write_all(self.0[27].as_slice())?; - writer.write_all(self.0[28].as_slice())?; - writer.write_all(self.0[29].as_slice())?; - writer.write_all(self.0[30].as_slice())?; - writer.write_all(self.0[31].as_slice())?; - writer.write_all(self.0[32].as_slice())?; - writer.write_all(self.0[33].as_slice())?; - writer.write_all(self.0[34].as_slice())?; - writer.write_all(self.0[35].as_slice())?; - writer.write_all(self.0[36].as_slice())?; - writer.write_all(self.0[37].as_slice())?; - writer.write_all(self.0[38].as_slice())?; - writer.write_all(self.0[39].as_slice())?; - writer.write_all(self.0[40].as_slice())?; - writer.write_all(self.0[41].as_slice())?; - writer.write_all(self.0[42].as_slice())?; - writer.write_all(self.0[43].as_slice())?; - writer.write_all(self.0[44].as_slice())?; - writer.write_all(self.0[45].as_slice())?; - writer.write_all(self.0[46].as_slice())?; - writer.write_all(self.0[47].as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - BlsPubkey::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct Signautre(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Signautre { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Signautre { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Signautre { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl ::core::default::Default for Signautre { - fn default() -> Self { - let v: Vec = vec![ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, - ]; - Signautre::new_unchecked(v.into()) - } -} -impl Signautre { - pub const ITEM_COUNT: usize = 65; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 65; - - pub fn nth0(&self) -> Byte { - Byte::new_unchecked(self.0.slice(0..1)) - } - - pub fn nth1(&self) -> Byte { - Byte::new_unchecked(self.0.slice(1..2)) - } - - pub fn nth2(&self) -> Byte { - Byte::new_unchecked(self.0.slice(2..3)) - } - - pub fn nth3(&self) -> Byte { - Byte::new_unchecked(self.0.slice(3..4)) - } - - pub fn nth4(&self) -> Byte { - Byte::new_unchecked(self.0.slice(4..5)) - } - - pub fn nth5(&self) -> Byte { - Byte::new_unchecked(self.0.slice(5..6)) - } - - pub fn nth6(&self) -> Byte { - Byte::new_unchecked(self.0.slice(6..7)) - } - - pub fn nth7(&self) -> Byte { - Byte::new_unchecked(self.0.slice(7..8)) - } - - pub fn nth8(&self) -> Byte { - Byte::new_unchecked(self.0.slice(8..9)) - } - - pub fn nth9(&self) -> Byte { - Byte::new_unchecked(self.0.slice(9..10)) - } - - pub fn nth10(&self) -> Byte { - Byte::new_unchecked(self.0.slice(10..11)) - } - - pub fn nth11(&self) -> Byte { - Byte::new_unchecked(self.0.slice(11..12)) - } - - pub fn nth12(&self) -> Byte { - Byte::new_unchecked(self.0.slice(12..13)) - } - - pub fn nth13(&self) -> Byte { - Byte::new_unchecked(self.0.slice(13..14)) - } - - pub fn nth14(&self) -> Byte { - Byte::new_unchecked(self.0.slice(14..15)) - } - - pub fn nth15(&self) -> Byte { - Byte::new_unchecked(self.0.slice(15..16)) - } - - pub fn nth16(&self) -> Byte { - Byte::new_unchecked(self.0.slice(16..17)) - } - - pub fn nth17(&self) -> Byte { - Byte::new_unchecked(self.0.slice(17..18)) - } - - pub fn nth18(&self) -> Byte { - Byte::new_unchecked(self.0.slice(18..19)) - } - - pub fn nth19(&self) -> Byte { - Byte::new_unchecked(self.0.slice(19..20)) - } - - pub fn nth20(&self) -> Byte { - Byte::new_unchecked(self.0.slice(20..21)) - } - - pub fn nth21(&self) -> Byte { - Byte::new_unchecked(self.0.slice(21..22)) - } - - pub fn nth22(&self) -> Byte { - Byte::new_unchecked(self.0.slice(22..23)) - } - - pub fn nth23(&self) -> Byte { - Byte::new_unchecked(self.0.slice(23..24)) - } - - pub fn nth24(&self) -> Byte { - Byte::new_unchecked(self.0.slice(24..25)) - } - - pub fn nth25(&self) -> Byte { - Byte::new_unchecked(self.0.slice(25..26)) - } - - pub fn nth26(&self) -> Byte { - Byte::new_unchecked(self.0.slice(26..27)) - } - - pub fn nth27(&self) -> Byte { - Byte::new_unchecked(self.0.slice(27..28)) - } - - pub fn nth28(&self) -> Byte { - Byte::new_unchecked(self.0.slice(28..29)) - } - - pub fn nth29(&self) -> Byte { - Byte::new_unchecked(self.0.slice(29..30)) - } - - pub fn nth30(&self) -> Byte { - Byte::new_unchecked(self.0.slice(30..31)) - } - - pub fn nth31(&self) -> Byte { - Byte::new_unchecked(self.0.slice(31..32)) - } - - pub fn nth32(&self) -> Byte { - Byte::new_unchecked(self.0.slice(32..33)) - } - - pub fn nth33(&self) -> Byte { - Byte::new_unchecked(self.0.slice(33..34)) - } - - pub fn nth34(&self) -> Byte { - Byte::new_unchecked(self.0.slice(34..35)) - } - - pub fn nth35(&self) -> Byte { - Byte::new_unchecked(self.0.slice(35..36)) - } - - pub fn nth36(&self) -> Byte { - Byte::new_unchecked(self.0.slice(36..37)) - } - - pub fn nth37(&self) -> Byte { - Byte::new_unchecked(self.0.slice(37..38)) - } - - pub fn nth38(&self) -> Byte { - Byte::new_unchecked(self.0.slice(38..39)) - } - - pub fn nth39(&self) -> Byte { - Byte::new_unchecked(self.0.slice(39..40)) - } - - pub fn nth40(&self) -> Byte { - Byte::new_unchecked(self.0.slice(40..41)) - } - - pub fn nth41(&self) -> Byte { - Byte::new_unchecked(self.0.slice(41..42)) - } - - pub fn nth42(&self) -> Byte { - Byte::new_unchecked(self.0.slice(42..43)) - } - - pub fn nth43(&self) -> Byte { - Byte::new_unchecked(self.0.slice(43..44)) - } - - pub fn nth44(&self) -> Byte { - Byte::new_unchecked(self.0.slice(44..45)) - } - - pub fn nth45(&self) -> Byte { - Byte::new_unchecked(self.0.slice(45..46)) - } - - pub fn nth46(&self) -> Byte { - Byte::new_unchecked(self.0.slice(46..47)) - } - - pub fn nth47(&self) -> Byte { - Byte::new_unchecked(self.0.slice(47..48)) - } - - pub fn nth48(&self) -> Byte { - Byte::new_unchecked(self.0.slice(48..49)) - } - - pub fn nth49(&self) -> Byte { - Byte::new_unchecked(self.0.slice(49..50)) - } - - pub fn nth50(&self) -> Byte { - Byte::new_unchecked(self.0.slice(50..51)) - } - - pub fn nth51(&self) -> Byte { - Byte::new_unchecked(self.0.slice(51..52)) - } - - pub fn nth52(&self) -> Byte { - Byte::new_unchecked(self.0.slice(52..53)) - } - - pub fn nth53(&self) -> Byte { - Byte::new_unchecked(self.0.slice(53..54)) - } - - pub fn nth54(&self) -> Byte { - Byte::new_unchecked(self.0.slice(54..55)) - } - - pub fn nth55(&self) -> Byte { - Byte::new_unchecked(self.0.slice(55..56)) - } - - pub fn nth56(&self) -> Byte { - Byte::new_unchecked(self.0.slice(56..57)) - } - - pub fn nth57(&self) -> Byte { - Byte::new_unchecked(self.0.slice(57..58)) - } - - pub fn nth58(&self) -> Byte { - Byte::new_unchecked(self.0.slice(58..59)) - } - - pub fn nth59(&self) -> Byte { - Byte::new_unchecked(self.0.slice(59..60)) - } - - pub fn nth60(&self) -> Byte { - Byte::new_unchecked(self.0.slice(60..61)) - } - - pub fn nth61(&self) -> Byte { - Byte::new_unchecked(self.0.slice(61..62)) - } - - pub fn nth62(&self) -> Byte { - Byte::new_unchecked(self.0.slice(62..63)) - } - - pub fn nth63(&self) -> Byte { - Byte::new_unchecked(self.0.slice(63..64)) - } - - pub fn nth64(&self) -> Byte { - Byte::new_unchecked(self.0.slice(64..65)) - } - - pub fn raw_data(&self) -> molecule::bytes::Bytes { - self.as_bytes() - } - - pub fn as_reader<'r>(&'r self) -> SignautreReader<'r> { - SignautreReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Signautre { - type Builder = SignautreBuilder; - - const NAME: &'static str = "Signautre"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Signautre(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - SignautreReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - SignautreReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().set([ - self.nth0(), - self.nth1(), - self.nth2(), - self.nth3(), - self.nth4(), - self.nth5(), - self.nth6(), - self.nth7(), - self.nth8(), - self.nth9(), - self.nth10(), - self.nth11(), - self.nth12(), - self.nth13(), - self.nth14(), - self.nth15(), - self.nth16(), - self.nth17(), - self.nth18(), - self.nth19(), - self.nth20(), - self.nth21(), - self.nth22(), - self.nth23(), - self.nth24(), - self.nth25(), - self.nth26(), - self.nth27(), - self.nth28(), - self.nth29(), - self.nth30(), - self.nth31(), - self.nth32(), - self.nth33(), - self.nth34(), - self.nth35(), - self.nth36(), - self.nth37(), - self.nth38(), - self.nth39(), - self.nth40(), - self.nth41(), - self.nth42(), - self.nth43(), - self.nth44(), - self.nth45(), - self.nth46(), - self.nth47(), - self.nth48(), - self.nth49(), - self.nth50(), - self.nth51(), - self.nth52(), - self.nth53(), - self.nth54(), - self.nth55(), - self.nth56(), - self.nth57(), - self.nth58(), - self.nth59(), - self.nth60(), - self.nth61(), - self.nth62(), - self.nth63(), - self.nth64(), - ]) - } -} -#[derive(Clone, Copy)] -pub struct SignautreReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for SignautreReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for SignautreReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for SignautreReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - let raw_data = hex_string(&self.raw_data()); - write!(f, "{}(0x{})", Self::NAME, raw_data) - } -} -impl<'r> SignautreReader<'r> { - pub const ITEM_COUNT: usize = 65; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 65; - - pub fn nth0(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[0..1]) - } - - pub fn nth1(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[1..2]) - } - - pub fn nth2(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[2..3]) - } - - pub fn nth3(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[3..4]) - } - - pub fn nth4(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[4..5]) - } - - pub fn nth5(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[5..6]) - } - - pub fn nth6(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[6..7]) - } - - pub fn nth7(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[7..8]) - } - - pub fn nth8(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[8..9]) - } - - pub fn nth9(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[9..10]) - } - - pub fn nth10(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[10..11]) - } - - pub fn nth11(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[11..12]) - } - - pub fn nth12(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[12..13]) - } - - pub fn nth13(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[13..14]) - } - - pub fn nth14(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[14..15]) - } - - pub fn nth15(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[15..16]) - } - - pub fn nth16(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[16..17]) - } - - pub fn nth17(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[17..18]) - } - - pub fn nth18(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[18..19]) - } - - pub fn nth19(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[19..20]) - } - - pub fn nth20(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[20..21]) - } - - pub fn nth21(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[21..22]) - } - - pub fn nth22(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[22..23]) - } - - pub fn nth23(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[23..24]) - } - - pub fn nth24(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[24..25]) - } - - pub fn nth25(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[25..26]) - } - - pub fn nth26(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[26..27]) - } - - pub fn nth27(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[27..28]) - } - - pub fn nth28(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[28..29]) - } - - pub fn nth29(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[29..30]) - } - - pub fn nth30(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[30..31]) - } - - pub fn nth31(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[31..32]) - } - - pub fn nth32(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[32..33]) - } - - pub fn nth33(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[33..34]) - } - - pub fn nth34(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[34..35]) - } - - pub fn nth35(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[35..36]) - } - - pub fn nth36(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[36..37]) - } - - pub fn nth37(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[37..38]) - } - - pub fn nth38(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[38..39]) - } - - pub fn nth39(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[39..40]) - } - - pub fn nth40(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[40..41]) - } - - pub fn nth41(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[41..42]) - } - - pub fn nth42(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[42..43]) - } - - pub fn nth43(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[43..44]) - } - - pub fn nth44(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[44..45]) - } - - pub fn nth45(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[45..46]) - } - - pub fn nth46(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[46..47]) - } - - pub fn nth47(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[47..48]) - } - - pub fn nth48(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[48..49]) - } - - pub fn nth49(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[49..50]) - } - - pub fn nth50(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[50..51]) - } - - pub fn nth51(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[51..52]) - } - - pub fn nth52(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[52..53]) - } - - pub fn nth53(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[53..54]) - } - - pub fn nth54(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[54..55]) - } - - pub fn nth55(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[55..56]) - } - - pub fn nth56(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[56..57]) - } - - pub fn nth57(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[57..58]) - } - - pub fn nth58(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[58..59]) - } - - pub fn nth59(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[59..60]) - } - - pub fn nth60(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[60..61]) - } - - pub fn nth61(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[61..62]) - } - - pub fn nth62(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[62..63]) - } - - pub fn nth63(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[63..64]) - } - - pub fn nth64(&self) -> ByteReader<'r> { - ByteReader::new_unchecked(&self.as_slice()[64..65]) - } - - pub fn raw_data(&self) -> &'r [u8] { - self.as_slice() - } -} -impl<'r> molecule::prelude::Reader<'r> for SignautreReader<'r> { - type Entity = Signautre; - - const NAME: &'static str = "SignautreReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - SignautreReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len != Self::TOTAL_SIZE { - return ve!(Self, TotalSizeNotMatch, Self::TOTAL_SIZE, slice_len); - } - Ok(()) - } -} -pub struct SignautreBuilder(pub(crate) [Byte; 65]); -impl ::core::fmt::Debug for SignautreBuilder { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:?})", Self::NAME, &self.0[..]) - } -} -impl ::core::default::Default for SignautreBuilder { - fn default() -> Self { - SignautreBuilder([ - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - Byte::default(), - ]) - } -} -impl SignautreBuilder { - pub const ITEM_COUNT: usize = 65; - pub const ITEM_SIZE: usize = 1; - pub const TOTAL_SIZE: usize = 65; - - pub fn set(mut self, v: [Byte; 65]) -> Self { - self.0 = v; - self - } - - pub fn nth0(mut self, v: Byte) -> Self { - self.0[0] = v; - self - } - - pub fn nth1(mut self, v: Byte) -> Self { - self.0[1] = v; - self - } - - pub fn nth2(mut self, v: Byte) -> Self { - self.0[2] = v; - self - } - - pub fn nth3(mut self, v: Byte) -> Self { - self.0[3] = v; - self - } - - pub fn nth4(mut self, v: Byte) -> Self { - self.0[4] = v; - self - } - - pub fn nth5(mut self, v: Byte) -> Self { - self.0[5] = v; - self - } - - pub fn nth6(mut self, v: Byte) -> Self { - self.0[6] = v; - self - } - - pub fn nth7(mut self, v: Byte) -> Self { - self.0[7] = v; - self - } - - pub fn nth8(mut self, v: Byte) -> Self { - self.0[8] = v; - self - } - - pub fn nth9(mut self, v: Byte) -> Self { - self.0[9] = v; - self - } - - pub fn nth10(mut self, v: Byte) -> Self { - self.0[10] = v; - self - } - - pub fn nth11(mut self, v: Byte) -> Self { - self.0[11] = v; - self - } - - pub fn nth12(mut self, v: Byte) -> Self { - self.0[12] = v; - self - } - - pub fn nth13(mut self, v: Byte) -> Self { - self.0[13] = v; - self - } - - pub fn nth14(mut self, v: Byte) -> Self { - self.0[14] = v; - self - } - - pub fn nth15(mut self, v: Byte) -> Self { - self.0[15] = v; - self - } - - pub fn nth16(mut self, v: Byte) -> Self { - self.0[16] = v; - self - } - - pub fn nth17(mut self, v: Byte) -> Self { - self.0[17] = v; - self - } - - pub fn nth18(mut self, v: Byte) -> Self { - self.0[18] = v; - self - } - - pub fn nth19(mut self, v: Byte) -> Self { - self.0[19] = v; - self - } - - pub fn nth20(mut self, v: Byte) -> Self { - self.0[20] = v; - self - } - - pub fn nth21(mut self, v: Byte) -> Self { - self.0[21] = v; - self - } - - pub fn nth22(mut self, v: Byte) -> Self { - self.0[22] = v; - self - } - - pub fn nth23(mut self, v: Byte) -> Self { - self.0[23] = v; - self - } - - pub fn nth24(mut self, v: Byte) -> Self { - self.0[24] = v; - self - } - - pub fn nth25(mut self, v: Byte) -> Self { - self.0[25] = v; - self - } - - pub fn nth26(mut self, v: Byte) -> Self { - self.0[26] = v; - self - } - - pub fn nth27(mut self, v: Byte) -> Self { - self.0[27] = v; - self - } - - pub fn nth28(mut self, v: Byte) -> Self { - self.0[28] = v; - self - } - - pub fn nth29(mut self, v: Byte) -> Self { - self.0[29] = v; - self - } - - pub fn nth30(mut self, v: Byte) -> Self { - self.0[30] = v; - self - } - - pub fn nth31(mut self, v: Byte) -> Self { - self.0[31] = v; - self - } - - pub fn nth32(mut self, v: Byte) -> Self { - self.0[32] = v; - self - } - - pub fn nth33(mut self, v: Byte) -> Self { - self.0[33] = v; - self - } - - pub fn nth34(mut self, v: Byte) -> Self { - self.0[34] = v; - self - } - - pub fn nth35(mut self, v: Byte) -> Self { - self.0[35] = v; - self - } - - pub fn nth36(mut self, v: Byte) -> Self { - self.0[36] = v; - self - } - - pub fn nth37(mut self, v: Byte) -> Self { - self.0[37] = v; - self - } - - pub fn nth38(mut self, v: Byte) -> Self { - self.0[38] = v; - self - } - - pub fn nth39(mut self, v: Byte) -> Self { - self.0[39] = v; - self - } - - pub fn nth40(mut self, v: Byte) -> Self { - self.0[40] = v; - self - } - - pub fn nth41(mut self, v: Byte) -> Self { - self.0[41] = v; - self - } - - pub fn nth42(mut self, v: Byte) -> Self { - self.0[42] = v; - self - } - - pub fn nth43(mut self, v: Byte) -> Self { - self.0[43] = v; - self - } - - pub fn nth44(mut self, v: Byte) -> Self { - self.0[44] = v; - self - } - - pub fn nth45(mut self, v: Byte) -> Self { - self.0[45] = v; - self - } - - pub fn nth46(mut self, v: Byte) -> Self { - self.0[46] = v; - self - } - - pub fn nth47(mut self, v: Byte) -> Self { - self.0[47] = v; - self - } - - pub fn nth48(mut self, v: Byte) -> Self { - self.0[48] = v; - self - } - - pub fn nth49(mut self, v: Byte) -> Self { - self.0[49] = v; - self - } - - pub fn nth50(mut self, v: Byte) -> Self { - self.0[50] = v; - self - } - - pub fn nth51(mut self, v: Byte) -> Self { - self.0[51] = v; - self - } - - pub fn nth52(mut self, v: Byte) -> Self { - self.0[52] = v; - self - } - - pub fn nth53(mut self, v: Byte) -> Self { - self.0[53] = v; - self - } - - pub fn nth54(mut self, v: Byte) -> Self { - self.0[54] = v; - self - } - - pub fn nth55(mut self, v: Byte) -> Self { - self.0[55] = v; - self - } - - pub fn nth56(mut self, v: Byte) -> Self { - self.0[56] = v; - self - } - - pub fn nth57(mut self, v: Byte) -> Self { - self.0[57] = v; - self - } - - pub fn nth58(mut self, v: Byte) -> Self { - self.0[58] = v; - self - } - - pub fn nth59(mut self, v: Byte) -> Self { - self.0[59] = v; - self - } - - pub fn nth60(mut self, v: Byte) -> Self { - self.0[60] = v; - self - } - - pub fn nth61(mut self, v: Byte) -> Self { - self.0[61] = v; - self - } - - pub fn nth62(mut self, v: Byte) -> Self { - self.0[62] = v; - self - } - - pub fn nth63(mut self, v: Byte) -> Self { - self.0[63] = v; - self - } - - pub fn nth64(mut self, v: Byte) -> Self { - self.0[64] = v; - self - } -} -impl molecule::prelude::Builder for SignautreBuilder { - type Entity = Signautre; - - const NAME: &'static str = "SignautreBuilder"; - - fn expected_length(&self) -> usize { - Self::TOTAL_SIZE - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - writer.write_all(self.0[0].as_slice())?; - writer.write_all(self.0[1].as_slice())?; - writer.write_all(self.0[2].as_slice())?; - writer.write_all(self.0[3].as_slice())?; - writer.write_all(self.0[4].as_slice())?; - writer.write_all(self.0[5].as_slice())?; - writer.write_all(self.0[6].as_slice())?; - writer.write_all(self.0[7].as_slice())?; - writer.write_all(self.0[8].as_slice())?; - writer.write_all(self.0[9].as_slice())?; - writer.write_all(self.0[10].as_slice())?; - writer.write_all(self.0[11].as_slice())?; - writer.write_all(self.0[12].as_slice())?; - writer.write_all(self.0[13].as_slice())?; - writer.write_all(self.0[14].as_slice())?; - writer.write_all(self.0[15].as_slice())?; - writer.write_all(self.0[16].as_slice())?; - writer.write_all(self.0[17].as_slice())?; - writer.write_all(self.0[18].as_slice())?; - writer.write_all(self.0[19].as_slice())?; - writer.write_all(self.0[20].as_slice())?; - writer.write_all(self.0[21].as_slice())?; - writer.write_all(self.0[22].as_slice())?; - writer.write_all(self.0[23].as_slice())?; - writer.write_all(self.0[24].as_slice())?; - writer.write_all(self.0[25].as_slice())?; - writer.write_all(self.0[26].as_slice())?; - writer.write_all(self.0[27].as_slice())?; - writer.write_all(self.0[28].as_slice())?; - writer.write_all(self.0[29].as_slice())?; - writer.write_all(self.0[30].as_slice())?; - writer.write_all(self.0[31].as_slice())?; - writer.write_all(self.0[32].as_slice())?; - writer.write_all(self.0[33].as_slice())?; - writer.write_all(self.0[34].as_slice())?; - writer.write_all(self.0[35].as_slice())?; - writer.write_all(self.0[36].as_slice())?; - writer.write_all(self.0[37].as_slice())?; - writer.write_all(self.0[38].as_slice())?; - writer.write_all(self.0[39].as_slice())?; - writer.write_all(self.0[40].as_slice())?; - writer.write_all(self.0[41].as_slice())?; - writer.write_all(self.0[42].as_slice())?; - writer.write_all(self.0[43].as_slice())?; - writer.write_all(self.0[44].as_slice())?; - writer.write_all(self.0[45].as_slice())?; - writer.write_all(self.0[46].as_slice())?; - writer.write_all(self.0[47].as_slice())?; - writer.write_all(self.0[48].as_slice())?; - writer.write_all(self.0[49].as_slice())?; - writer.write_all(self.0[50].as_slice())?; - writer.write_all(self.0[51].as_slice())?; - writer.write_all(self.0[52].as_slice())?; - writer.write_all(self.0[53].as_slice())?; - writer.write_all(self.0[54].as_slice())?; - writer.write_all(self.0[55].as_slice())?; - writer.write_all(self.0[56].as_slice())?; - writer.write_all(self.0[57].as_slice())?; - writer.write_all(self.0[58].as_slice())?; - writer.write_all(self.0[59].as_slice())?; - writer.write_all(self.0[60].as_slice())?; - writer.write_all(self.0[61].as_slice())?; - writer.write_all(self.0[62].as_slice())?; - writer.write_all(self.0[63].as_slice())?; - writer.write_all(self.0[64].as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Signautre::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct BlsPubkeyList(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for BlsPubkeyList { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for BlsPubkeyList { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for BlsPubkeyList { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} [", Self::NAME)?; - for i in 0..self.len() { - if i == 0 { - write!(f, "{}", self.get_unchecked(i))?; - } else { - write!(f, ", {}", self.get_unchecked(i))?; - } - } - write!(f, "]") - } -} -impl ::core::default::Default for BlsPubkeyList { - fn default() -> Self { - let v: Vec = vec![0, 0, 0, 0]; - BlsPubkeyList::new_unchecked(v.into()) - } -} -impl BlsPubkeyList { - pub const ITEM_SIZE: usize = 48; - - pub fn total_size(&self) -> usize { - molecule::NUMBER_SIZE + Self::ITEM_SIZE * self.item_count() - } - - pub fn item_count(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn len(&self) -> usize { - self.item_count() - } - - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - pub fn get(&self, idx: usize) -> Option { - if idx >= self.len() { - None - } else { - Some(self.get_unchecked(idx)) - } - } - - pub fn get_unchecked(&self, idx: usize) -> BlsPubkey { - let start = molecule::NUMBER_SIZE + Self::ITEM_SIZE * idx; - let end = start + Self::ITEM_SIZE; - BlsPubkey::new_unchecked(self.0.slice(start..end)) - } - - pub fn as_reader<'r>(&'r self) -> BlsPubkeyListReader<'r> { - BlsPubkeyListReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for BlsPubkeyList { - type Builder = BlsPubkeyListBuilder; - - const NAME: &'static str = "BlsPubkeyList"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - BlsPubkeyList(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - BlsPubkeyListReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - BlsPubkeyListReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().extend(self.into_iter()) - } -} -#[derive(Clone, Copy)] -pub struct BlsPubkeyListReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for BlsPubkeyListReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for BlsPubkeyListReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for BlsPubkeyListReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} [", Self::NAME)?; - for i in 0..self.len() { - if i == 0 { - write!(f, "{}", self.get_unchecked(i))?; - } else { - write!(f, ", {}", self.get_unchecked(i))?; - } - } - write!(f, "]") - } -} -impl<'r> BlsPubkeyListReader<'r> { - pub const ITEM_SIZE: usize = 48; - - pub fn total_size(&self) -> usize { - molecule::NUMBER_SIZE + Self::ITEM_SIZE * self.item_count() - } - - pub fn item_count(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn len(&self) -> usize { - self.item_count() - } - - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - pub fn get(&self, idx: usize) -> Option> { - if idx >= self.len() { - None - } else { - Some(self.get_unchecked(idx)) - } - } - - pub fn get_unchecked(&self, idx: usize) -> BlsPubkeyReader<'r> { - let start = molecule::NUMBER_SIZE + Self::ITEM_SIZE * idx; - let end = start + Self::ITEM_SIZE; - BlsPubkeyReader::new_unchecked(&self.as_slice()[start..end]) - } -} -impl<'r> molecule::prelude::Reader<'r> for BlsPubkeyListReader<'r> { - type Entity = BlsPubkeyList; - - const NAME: &'static str = "BlsPubkeyListReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - BlsPubkeyListReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let item_count = molecule::unpack_number(slice) as usize; - if item_count == 0 { - if slice_len != molecule::NUMBER_SIZE { - return ve!(Self, TotalSizeNotMatch, molecule::NUMBER_SIZE, slice_len); - } - return Ok(()); - } - let total_size = molecule::NUMBER_SIZE + Self::ITEM_SIZE * item_count; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct BlsPubkeyListBuilder(pub(crate) Vec); -impl BlsPubkeyListBuilder { - pub const ITEM_SIZE: usize = 48; - - pub fn set(mut self, v: Vec) -> Self { - self.0 = v; - self - } - - pub fn push(mut self, v: BlsPubkey) -> Self { - self.0.push(v); - self - } - - pub fn extend>(mut self, iter: T) -> Self { - for elem in iter { - self.0.push(elem); - } - self - } -} -impl molecule::prelude::Builder for BlsPubkeyListBuilder { - type Entity = BlsPubkeyList; - - const NAME: &'static str = "BlsPubkeyListBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE + Self::ITEM_SIZE * self.0.len() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - writer.write_all(&molecule::pack_number(self.0.len() as molecule::Number))?; - for inner in &self.0[..] { - writer.write_all(inner.as_slice())?; - } - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - BlsPubkeyList::new_unchecked(inner.into()) - } -} -pub struct BlsPubkeyListIterator(BlsPubkeyList, usize, usize); -impl ::core::iter::Iterator for BlsPubkeyListIterator { - type Item = BlsPubkey; - - fn next(&mut self) -> Option { - if self.1 >= self.2 { - None - } else { - let ret = self.0.get_unchecked(self.1); - self.1 += 1; - Some(ret) - } - } -} -impl ::core::iter::ExactSizeIterator for BlsPubkeyListIterator { - fn len(&self) -> usize { - self.2 - self.1 - } -} -impl ::core::iter::IntoIterator for BlsPubkeyList { - type IntoIter = BlsPubkeyListIterator; - type Item = BlsPubkey; - - fn into_iter(self) -> Self::IntoIter { - let len = self.len(); - BlsPubkeyListIterator(self, 0, len) - } -} -impl<'r> BlsPubkeyListReader<'r> { - pub fn iter<'t>(&'t self) -> BlsPubkeyListReaderIterator<'t, 'r> { - BlsPubkeyListReaderIterator(&self, 0, self.len()) - } -} -pub struct BlsPubkeyListReaderIterator<'t, 'r>(&'t BlsPubkeyListReader<'r>, usize, usize); -impl<'t: 'r, 'r> ::core::iter::Iterator for BlsPubkeyListReaderIterator<'t, 'r> { - type Item = BlsPubkeyReader<'t>; - - fn next(&mut self) -> Option { - if self.1 >= self.2 { - None - } else { - let ret = self.0.get_unchecked(self.1); - self.1 += 1; - Some(ret) - } - } -} -impl<'t: 'r, 'r> ::core::iter::ExactSizeIterator for BlsPubkeyListReaderIterator<'t, 'r> { - fn len(&self) -> usize { - self.2 - self.1 - } -} -#[derive(Clone)] -pub struct Witness(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Witness { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Witness { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Witness { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "signature", self.signature())?; - write!(f, ", {}: {}", "bls_pubkeys", self.bls_pubkeys())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl ::core::default::Default for Witness { - fn default() -> Self { - let v: Vec = vec![ - 81, 0, 0, 0, 12, 0, 0, 0, 77, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - Witness::new_unchecked(v.into()) - } -} -impl Witness { - pub const FIELD_COUNT: usize = 2; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn signature(&self) -> Signautre { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - Signautre::new_unchecked(self.0.slice(start..end)) - } - - pub fn bls_pubkeys(&self) -> BlsPubkeyList { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[12..]) as usize; - BlsPubkeyList::new_unchecked(self.0.slice(start..end)) - } else { - BlsPubkeyList::new_unchecked(self.0.slice(start..)) - } - } - - pub fn as_reader<'r>(&'r self) -> WitnessReader<'r> { - WitnessReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Witness { - type Builder = WitnessBuilder; - - const NAME: &'static str = "Witness"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Witness(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - WitnessReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - WitnessReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder() - .signature(self.signature()) - .bls_pubkeys(self.bls_pubkeys()) - } -} -#[derive(Clone, Copy)] -pub struct WitnessReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for WitnessReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for WitnessReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for WitnessReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "signature", self.signature())?; - write!(f, ", {}: {}", "bls_pubkeys", self.bls_pubkeys())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl<'r> WitnessReader<'r> { - pub const FIELD_COUNT: usize = 2; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn signature(&self) -> SignautreReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - SignautreReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn bls_pubkeys(&self) -> BlsPubkeyListReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[12..]) as usize; - BlsPubkeyListReader::new_unchecked(&self.as_slice()[start..end]) - } else { - BlsPubkeyListReader::new_unchecked(&self.as_slice()[start..]) - } - } -} -impl<'r> molecule::prelude::Reader<'r> for WitnessReader<'r> { - type Entity = Witness; - - const NAME: &'static str = "WitnessReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - WitnessReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let total_size = molecule::unpack_number(slice) as usize; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { - return Ok(()); - } - if slice_len < molecule::NUMBER_SIZE * 2 { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); - } - let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { - return ve!(Self, OffsetsNotMatch); - } - if slice_len < offset_first { - return ve!(Self, HeaderIsBroken, offset_first, slice_len); - } - let field_count = offset_first / molecule::NUMBER_SIZE - 1; - if field_count < Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - } else if !compatible && field_count > Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - }; - let mut offsets: Vec = slice[molecule::NUMBER_SIZE..offset_first] - .chunks_exact(molecule::NUMBER_SIZE) - .map(|x| molecule::unpack_number(x) as usize) - .collect(); - offsets.push(total_size); - if offsets.windows(2).any(|i| i[0] > i[1]) { - return ve!(Self, OffsetsNotMatch); - } - SignautreReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; - BlsPubkeyListReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct WitnessBuilder { - pub(crate) signature: Signautre, - pub(crate) bls_pubkeys: BlsPubkeyList, -} -impl WitnessBuilder { - pub const FIELD_COUNT: usize = 2; - - pub fn signature(mut self, v: Signautre) -> Self { - self.signature = v; - self - } - - pub fn bls_pubkeys(mut self, v: BlsPubkeyList) -> Self { - self.bls_pubkeys = v; - self - } -} -impl molecule::prelude::Builder for WitnessBuilder { - type Entity = Witness; - - const NAME: &'static str = "WitnessBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) - + self.signature.as_slice().len() - + self.bls_pubkeys.as_slice().len() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); - let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); - offsets.push(total_size); - total_size += self.signature.as_slice().len(); - offsets.push(total_size); - total_size += self.bls_pubkeys.as_slice().len(); - writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; - for offset in offsets.into_iter() { - writer.write_all(&molecule::pack_number(offset as molecule::Number))?; - } - writer.write_all(self.signature.as_slice())?; - writer.write_all(self.bls_pubkeys.as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Witness::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct Token(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Token { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Token { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Token { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "ERC20_address", self.e_r_c20_address())?; - write!(f, ", {}: {}", "sUDT_typehash", self.s_u_d_t_typehash())?; - write!(f, ", {}: {}", "fee_ratio", self.fee_ratio())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl ::core::default::Default for Token { - fn default() -> Self { - let v: Vec = vec![ - 72, 0, 0, 0, 16, 0, 0, 0, 36, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - Token::new_unchecked(v.into()) - } -} -impl Token { - pub const FIELD_COUNT: usize = 3; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn e_r_c20_address(&self) -> Address { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - Address::new_unchecked(self.0.slice(start..end)) - } - - pub fn s_u_d_t_typehash(&self) -> Hash { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - let end = molecule::unpack_number(&slice[12..]) as usize; - Hash::new_unchecked(self.0.slice(start..end)) - } - - pub fn fee_ratio(&self) -> Uint32 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[12..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[16..]) as usize; - Uint32::new_unchecked(self.0.slice(start..end)) - } else { - Uint32::new_unchecked(self.0.slice(start..)) - } - } - - pub fn as_reader<'r>(&'r self) -> TokenReader<'r> { - TokenReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Token { - type Builder = TokenBuilder; - - const NAME: &'static str = "Token"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Token(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - TokenReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - TokenReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder() - .e_r_c20_address(self.e_r_c20_address()) - .s_u_d_t_typehash(self.s_u_d_t_typehash()) - .fee_ratio(self.fee_ratio()) - } -} -#[derive(Clone, Copy)] -pub struct TokenReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for TokenReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for TokenReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for TokenReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "ERC20_address", self.e_r_c20_address())?; - write!(f, ", {}: {}", "sUDT_typehash", self.s_u_d_t_typehash())?; - write!(f, ", {}: {}", "fee_ratio", self.fee_ratio())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl<'r> TokenReader<'r> { - pub const FIELD_COUNT: usize = 3; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn e_r_c20_address(&self) -> AddressReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - AddressReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn s_u_d_t_typehash(&self) -> HashReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - let end = molecule::unpack_number(&slice[12..]) as usize; - HashReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn fee_ratio(&self) -> Uint32Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[12..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[16..]) as usize; - Uint32Reader::new_unchecked(&self.as_slice()[start..end]) - } else { - Uint32Reader::new_unchecked(&self.as_slice()[start..]) - } - } -} -impl<'r> molecule::prelude::Reader<'r> for TokenReader<'r> { - type Entity = Token; - - const NAME: &'static str = "TokenReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - TokenReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let total_size = molecule::unpack_number(slice) as usize; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { - return Ok(()); - } - if slice_len < molecule::NUMBER_SIZE * 2 { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); - } - let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { - return ve!(Self, OffsetsNotMatch); - } - if slice_len < offset_first { - return ve!(Self, HeaderIsBroken, offset_first, slice_len); - } - let field_count = offset_first / molecule::NUMBER_SIZE - 1; - if field_count < Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - } else if !compatible && field_count > Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - }; - let mut offsets: Vec = slice[molecule::NUMBER_SIZE..offset_first] - .chunks_exact(molecule::NUMBER_SIZE) - .map(|x| molecule::unpack_number(x) as usize) - .collect(); - offsets.push(total_size); - if offsets.windows(2).any(|i| i[0] > i[1]) { - return ve!(Self, OffsetsNotMatch); - } - AddressReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; - HashReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; - Uint32Reader::verify(&slice[offsets[2]..offsets[3]], compatible)?; - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct TokenBuilder { - pub(crate) e_r_c20_address: Address, - pub(crate) s_u_d_t_typehash: Hash, - pub(crate) fee_ratio: Uint32, -} -impl TokenBuilder { - pub const FIELD_COUNT: usize = 3; - - pub fn e_r_c20_address(mut self, v: Address) -> Self { - self.e_r_c20_address = v; - self - } - - pub fn s_u_d_t_typehash(mut self, v: Hash) -> Self { - self.s_u_d_t_typehash = v; - self - } - - pub fn fee_ratio(mut self, v: Uint32) -> Self { - self.fee_ratio = v; - self - } -} -impl molecule::prelude::Builder for TokenBuilder { - type Entity = Token; - - const NAME: &'static str = "TokenBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) - + self.e_r_c20_address.as_slice().len() - + self.s_u_d_t_typehash.as_slice().len() - + self.fee_ratio.as_slice().len() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); - let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); - offsets.push(total_size); - total_size += self.e_r_c20_address.as_slice().len(); - offsets.push(total_size); - total_size += self.s_u_d_t_typehash.as_slice().len(); - offsets.push(total_size); - total_size += self.fee_ratio.as_slice().len(); - writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; - for offset in offsets.into_iter() { - writer.write_all(&molecule::pack_number(offset as molecule::Number))?; - } - writer.write_all(self.e_r_c20_address.as_slice())?; - writer.write_all(self.s_u_d_t_typehash.as_slice())?; - writer.write_all(self.fee_ratio.as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Token::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct TokenConfig(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for TokenConfig { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for TokenConfig { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for TokenConfig { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} [", Self::NAME)?; - for i in 0..self.len() { - if i == 0 { - write!(f, "{}", self.get_unchecked(i))?; - } else { - write!(f, ", {}", self.get_unchecked(i))?; - } - } - write!(f, "]") - } -} -impl ::core::default::Default for TokenConfig { - fn default() -> Self { - let v: Vec = vec![4, 0, 0, 0]; - TokenConfig::new_unchecked(v.into()) - } -} -impl TokenConfig { - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn item_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn len(&self) -> usize { - self.item_count() - } - - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - pub fn get(&self, idx: usize) -> Option { - if idx >= self.len() { - None - } else { - Some(self.get_unchecked(idx)) - } - } - - pub fn get_unchecked(&self, idx: usize) -> Token { - let slice = self.as_slice(); - let start_idx = molecule::NUMBER_SIZE * (1 + idx); - let start = molecule::unpack_number(&slice[start_idx..]) as usize; - if idx == self.len() - 1 { - Token::new_unchecked(self.0.slice(start..)) - } else { - let end_idx = start_idx + molecule::NUMBER_SIZE; - let end = molecule::unpack_number(&slice[end_idx..]) as usize; - Token::new_unchecked(self.0.slice(start..end)) - } - } - - pub fn as_reader<'r>(&'r self) -> TokenConfigReader<'r> { - TokenConfigReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for TokenConfig { - type Builder = TokenConfigBuilder; - - const NAME: &'static str = "TokenConfig"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - TokenConfig(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - TokenConfigReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - TokenConfigReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder().extend(self.into_iter()) - } -} -#[derive(Clone, Copy)] -pub struct TokenConfigReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for TokenConfigReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for TokenConfigReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for TokenConfigReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} [", Self::NAME)?; - for i in 0..self.len() { - if i == 0 { - write!(f, "{}", self.get_unchecked(i))?; - } else { - write!(f, ", {}", self.get_unchecked(i))?; - } - } - write!(f, "]") - } -} -impl<'r> TokenConfigReader<'r> { - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn item_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn len(&self) -> usize { - self.item_count() - } - - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - pub fn get(&self, idx: usize) -> Option> { - if idx >= self.len() { - None - } else { - Some(self.get_unchecked(idx)) - } - } - - pub fn get_unchecked(&self, idx: usize) -> TokenReader<'r> { - let slice = self.as_slice(); - let start_idx = molecule::NUMBER_SIZE * (1 + idx); - let start = molecule::unpack_number(&slice[start_idx..]) as usize; - if idx == self.len() - 1 { - TokenReader::new_unchecked(&self.as_slice()[start..]) - } else { - let end_idx = start_idx + molecule::NUMBER_SIZE; - let end = molecule::unpack_number(&slice[end_idx..]) as usize; - TokenReader::new_unchecked(&self.as_slice()[start..end]) - } - } -} -impl<'r> molecule::prelude::Reader<'r> for TokenConfigReader<'r> { - type Entity = TokenConfig; - - const NAME: &'static str = "TokenConfigReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - TokenConfigReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let total_size = molecule::unpack_number(slice) as usize; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - if slice_len == molecule::NUMBER_SIZE { - return Ok(()); - } - if slice_len < molecule::NUMBER_SIZE * 2 { - return ve!( - Self, - TotalSizeNotMatch, - molecule::NUMBER_SIZE * 2, - slice_len - ); - } - let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { - return ve!(Self, OffsetsNotMatch); - } - if slice_len < offset_first { - return ve!(Self, HeaderIsBroken, offset_first, slice_len); - } - let mut offsets: Vec = slice[molecule::NUMBER_SIZE..offset_first] - .chunks_exact(molecule::NUMBER_SIZE) - .map(|x| molecule::unpack_number(x) as usize) - .collect(); - offsets.push(total_size); - if offsets.windows(2).any(|i| i[0] > i[1]) { - return ve!(Self, OffsetsNotMatch); - } - for pair in offsets.windows(2) { - let start = pair[0]; - let end = pair[1]; - TokenReader::verify(&slice[start..end], compatible)?; - } - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct TokenConfigBuilder(pub(crate) Vec); -impl TokenConfigBuilder { - pub fn set(mut self, v: Vec) -> Self { - self.0 = v; - self - } - - pub fn push(mut self, v: Token) -> Self { - self.0.push(v); - self - } - - pub fn extend>(mut self, iter: T) -> Self { - for elem in iter { - self.0.push(elem); - } - self - } -} -impl molecule::prelude::Builder for TokenConfigBuilder { - type Entity = TokenConfig; - - const NAME: &'static str = "TokenConfigBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE * (self.0.len() + 1) - + self - .0 - .iter() - .map(|inner| inner.as_slice().len()) - .sum::() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - let item_count = self.0.len(); - if item_count == 0 { - writer.write_all(&molecule::pack_number( - molecule::NUMBER_SIZE as molecule::Number, - ))?; - } else { - let (total_size, offsets) = self.0.iter().fold( - ( - molecule::NUMBER_SIZE * (item_count + 1), - Vec::with_capacity(item_count), - ), - |(start, mut offsets), inner| { - offsets.push(start); - (start + inner.as_slice().len(), offsets) - }, - ); - writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; - for offset in offsets.into_iter() { - writer.write_all(&molecule::pack_number(offset as molecule::Number))?; - } - for inner in self.0.iter() { - writer.write_all(inner.as_slice())?; - } - } - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - TokenConfig::new_unchecked(inner.into()) - } -} -pub struct TokenConfigIterator(TokenConfig, usize, usize); -impl ::core::iter::Iterator for TokenConfigIterator { - type Item = Token; - - fn next(&mut self) -> Option { - if self.1 >= self.2 { - None - } else { - let ret = self.0.get_unchecked(self.1); - self.1 += 1; - Some(ret) - } - } -} -impl ::core::iter::ExactSizeIterator for TokenConfigIterator { - fn len(&self) -> usize { - self.2 - self.1 - } -} -impl ::core::iter::IntoIterator for TokenConfig { - type IntoIter = TokenConfigIterator; - type Item = Token; - - fn into_iter(self) -> Self::IntoIter { - let len = self.len(); - TokenConfigIterator(self, 0, len) - } -} -impl<'r> TokenConfigReader<'r> { - pub fn iter<'t>(&'t self) -> TokenConfigReaderIterator<'t, 'r> { - TokenConfigReaderIterator(&self, 0, self.len()) - } -} -pub struct TokenConfigReaderIterator<'t, 'r>(&'t TokenConfigReader<'r>, usize, usize); -impl<'t: 'r, 'r> ::core::iter::Iterator for TokenConfigReaderIterator<'t, 'r> { - type Item = TokenReader<'t>; - - fn next(&mut self) -> Option { - if self.1 >= self.2 { - None - } else { - let ret = self.0.get_unchecked(self.1); - self.1 += 1; - Some(ret) - } - } -} -impl<'t: 'r, 'r> ::core::iter::ExactSizeIterator for TokenConfigReaderIterator<'t, 'r> { - fn len(&self) -> usize { - self.2 - self.1 - } -} -#[derive(Clone)] -pub struct Metadata(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Metadata { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Metadata { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Metadata { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "chain_id", self.chain_id())?; - write!(f, ", {}: {}", "token_config", self.token_config())?; - write!(f, ", {}: {}", "ckb_fee_ratio", self.ckb_fee_ratio())?; - write!(f, ", {}: {}", "stake_typehash", self.stake_typehash())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl ::core::default::Default for Metadata { - fn default() -> Self { - let v: Vec = vec![ - 61, 0, 0, 0, 20, 0, 0, 0, 21, 0, 0, 0, 25, 0, 0, 0, 29, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - ]; - Metadata::new_unchecked(v.into()) - } -} -impl Metadata { - pub const FIELD_COUNT: usize = 4; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn chain_id(&self) -> Byte { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - Byte::new_unchecked(self.0.slice(start..end)) - } - - pub fn token_config(&self) -> TokenConfig { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - let end = molecule::unpack_number(&slice[12..]) as usize; - TokenConfig::new_unchecked(self.0.slice(start..end)) - } - - pub fn ckb_fee_ratio(&self) -> Uint32 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[12..]) as usize; - let end = molecule::unpack_number(&slice[16..]) as usize; - Uint32::new_unchecked(self.0.slice(start..end)) - } - - pub fn stake_typehash(&self) -> Hash { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[16..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[20..]) as usize; - Hash::new_unchecked(self.0.slice(start..end)) - } else { - Hash::new_unchecked(self.0.slice(start..)) - } - } - - pub fn as_reader<'r>(&'r self) -> MetadataReader<'r> { - MetadataReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Metadata { - type Builder = MetadataBuilder; - - const NAME: &'static str = "Metadata"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Metadata(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - MetadataReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - MetadataReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder() - .chain_id(self.chain_id()) - .token_config(self.token_config()) - .ckb_fee_ratio(self.ckb_fee_ratio()) - .stake_typehash(self.stake_typehash()) - } -} -#[derive(Clone, Copy)] -pub struct MetadataReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for MetadataReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for MetadataReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for MetadataReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "chain_id", self.chain_id())?; - write!(f, ", {}: {}", "token_config", self.token_config())?; - write!(f, ", {}: {}", "ckb_fee_ratio", self.ckb_fee_ratio())?; - write!(f, ", {}: {}", "stake_typehash", self.stake_typehash())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl<'r> MetadataReader<'r> { - pub const FIELD_COUNT: usize = 4; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn chain_id(&self) -> ByteReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - ByteReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn token_config(&self) -> TokenConfigReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - let end = molecule::unpack_number(&slice[12..]) as usize; - TokenConfigReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn ckb_fee_ratio(&self) -> Uint32Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[12..]) as usize; - let end = molecule::unpack_number(&slice[16..]) as usize; - Uint32Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn stake_typehash(&self) -> HashReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[16..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[20..]) as usize; - HashReader::new_unchecked(&self.as_slice()[start..end]) - } else { - HashReader::new_unchecked(&self.as_slice()[start..]) - } - } -} -impl<'r> molecule::prelude::Reader<'r> for MetadataReader<'r> { - type Entity = Metadata; - - const NAME: &'static str = "MetadataReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - MetadataReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let total_size = molecule::unpack_number(slice) as usize; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { - return Ok(()); - } - if slice_len < molecule::NUMBER_SIZE * 2 { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); - } - let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { - return ve!(Self, OffsetsNotMatch); - } - if slice_len < offset_first { - return ve!(Self, HeaderIsBroken, offset_first, slice_len); - } - let field_count = offset_first / molecule::NUMBER_SIZE - 1; - if field_count < Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - } else if !compatible && field_count > Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - }; - let mut offsets: Vec = slice[molecule::NUMBER_SIZE..offset_first] - .chunks_exact(molecule::NUMBER_SIZE) - .map(|x| molecule::unpack_number(x) as usize) - .collect(); - offsets.push(total_size); - if offsets.windows(2).any(|i| i[0] > i[1]) { - return ve!(Self, OffsetsNotMatch); - } - ByteReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; - TokenConfigReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; - Uint32Reader::verify(&slice[offsets[2]..offsets[3]], compatible)?; - HashReader::verify(&slice[offsets[3]..offsets[4]], compatible)?; - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct MetadataBuilder { - pub(crate) chain_id: Byte, - pub(crate) token_config: TokenConfig, - pub(crate) ckb_fee_ratio: Uint32, - pub(crate) stake_typehash: Hash, -} -impl MetadataBuilder { - pub const FIELD_COUNT: usize = 4; - - pub fn chain_id(mut self, v: Byte) -> Self { - self.chain_id = v; - self - } - - pub fn token_config(mut self, v: TokenConfig) -> Self { - self.token_config = v; - self - } - - pub fn ckb_fee_ratio(mut self, v: Uint32) -> Self { - self.ckb_fee_ratio = v; - self - } - - pub fn stake_typehash(mut self, v: Hash) -> Self { - self.stake_typehash = v; - self - } -} -impl molecule::prelude::Builder for MetadataBuilder { - type Entity = Metadata; - - const NAME: &'static str = "MetadataBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) - + self.chain_id.as_slice().len() - + self.token_config.as_slice().len() - + self.ckb_fee_ratio.as_slice().len() - + self.stake_typehash.as_slice().len() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); - let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); - offsets.push(total_size); - total_size += self.chain_id.as_slice().len(); - offsets.push(total_size); - total_size += self.token_config.as_slice().len(); - offsets.push(total_size); - total_size += self.ckb_fee_ratio.as_slice().len(); - offsets.push(total_size); - total_size += self.stake_typehash.as_slice().len(); - writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; - for offset in offsets.into_iter() { - writer.write_all(&molecule::pack_number(offset as molecule::Number))?; - } - writer.write_all(self.chain_id.as_slice())?; - writer.write_all(self.token_config.as_slice())?; - writer.write_all(self.ckb_fee_ratio.as_slice())?; - writer.write_all(self.stake_typehash.as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Metadata::new_unchecked(inner.into()) - } -} -#[derive(Clone)] -pub struct Transfer(molecule::bytes::Bytes); -impl ::core::fmt::LowerHex for Transfer { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl ::core::fmt::Debug for Transfer { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl ::core::fmt::Display for Transfer { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "axon_address", self.axon_address())?; - write!(f, ", {}: {}", "ckb_amount", self.ckb_amount())?; - write!(f, ", {}: {}", "sUDT_amount", self.s_u_d_t_amount())?; - write!(f, ", {}: {}", "ERC20_address", self.e_r_c20_address())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl ::core::default::Default for Transfer { - fn default() -> Self { - let v: Vec = vec![ - 84, 0, 0, 0, 20, 0, 0, 0, 40, 0, 0, 0, 48, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ]; - Transfer::new_unchecked(v.into()) - } -} -impl Transfer { - pub const FIELD_COUNT: usize = 4; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn axon_address(&self) -> Address { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - Address::new_unchecked(self.0.slice(start..end)) - } - - pub fn ckb_amount(&self) -> Uint64 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - let end = molecule::unpack_number(&slice[12..]) as usize; - Uint64::new_unchecked(self.0.slice(start..end)) - } - - pub fn s_u_d_t_amount(&self) -> Uint128 { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[12..]) as usize; - let end = molecule::unpack_number(&slice[16..]) as usize; - Uint128::new_unchecked(self.0.slice(start..end)) - } - - pub fn e_r_c20_address(&self) -> Address { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[16..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[20..]) as usize; - Address::new_unchecked(self.0.slice(start..end)) - } else { - Address::new_unchecked(self.0.slice(start..)) - } - } - - pub fn as_reader<'r>(&'r self) -> TransferReader<'r> { - TransferReader::new_unchecked(self.as_slice()) - } -} -impl molecule::prelude::Entity for Transfer { - type Builder = TransferBuilder; - - const NAME: &'static str = "Transfer"; - - fn new_unchecked(data: molecule::bytes::Bytes) -> Self { - Transfer(data) - } - - fn as_bytes(&self) -> molecule::bytes::Bytes { - self.0.clone() - } - - fn as_slice(&self) -> &[u8] { - &self.0[..] - } - - fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult { - TransferReader::from_slice(slice).map(|reader| reader.to_entity()) - } - - fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult { - TransferReader::from_compatible_slice(slice).map(|reader| reader.to_entity()) - } - - fn new_builder() -> Self::Builder { - ::core::default::Default::default() - } - - fn as_builder(self) -> Self::Builder { - Self::new_builder() - .axon_address(self.axon_address()) - .ckb_amount(self.ckb_amount()) - .s_u_d_t_amount(self.s_u_d_t_amount()) - .e_r_c20_address(self.e_r_c20_address()) - } -} -#[derive(Clone, Copy)] -pub struct TransferReader<'r>(&'r [u8]); -impl<'r> ::core::fmt::LowerHex for TransferReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - use molecule::hex_string; - if f.alternate() { - write!(f, "0x")?; - } - write!(f, "{}", hex_string(self.as_slice())) - } -} -impl<'r> ::core::fmt::Debug for TransferReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{}({:#x})", Self::NAME, self) - } -} -impl<'r> ::core::fmt::Display for TransferReader<'r> { - fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - write!(f, "{} {{ ", Self::NAME)?; - write!(f, "{}: {}", "axon_address", self.axon_address())?; - write!(f, ", {}: {}", "ckb_amount", self.ckb_amount())?; - write!(f, ", {}: {}", "sUDT_amount", self.s_u_d_t_amount())?; - write!(f, ", {}: {}", "ERC20_address", self.e_r_c20_address())?; - let extra_count = self.count_extra_fields(); - if extra_count != 0 { - write!(f, ", .. ({} fields)", extra_count)?; - } - write!(f, " }}") - } -} -impl<'r> TransferReader<'r> { - pub const FIELD_COUNT: usize = 4; - - pub fn total_size(&self) -> usize { - molecule::unpack_number(self.as_slice()) as usize - } - - pub fn field_count(&self) -> usize { - if self.total_size() == molecule::NUMBER_SIZE { - 0 - } else { - (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 - } - } - - pub fn count_extra_fields(&self) -> usize { - self.field_count() - Self::FIELD_COUNT - } - - pub fn has_extra_fields(&self) -> bool { - Self::FIELD_COUNT != self.field_count() - } - - pub fn axon_address(&self) -> AddressReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[4..]) as usize; - let end = molecule::unpack_number(&slice[8..]) as usize; - AddressReader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn ckb_amount(&self) -> Uint64Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[8..]) as usize; - let end = molecule::unpack_number(&slice[12..]) as usize; - Uint64Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn s_u_d_t_amount(&self) -> Uint128Reader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[12..]) as usize; - let end = molecule::unpack_number(&slice[16..]) as usize; - Uint128Reader::new_unchecked(&self.as_slice()[start..end]) - } - - pub fn e_r_c20_address(&self) -> AddressReader<'r> { - let slice = self.as_slice(); - let start = molecule::unpack_number(&slice[16..]) as usize; - if self.has_extra_fields() { - let end = molecule::unpack_number(&slice[20..]) as usize; - AddressReader::new_unchecked(&self.as_slice()[start..end]) - } else { - AddressReader::new_unchecked(&self.as_slice()[start..]) - } - } -} -impl<'r> molecule::prelude::Reader<'r> for TransferReader<'r> { - type Entity = Transfer; - - const NAME: &'static str = "TransferReader"; - - fn to_entity(&self) -> Self::Entity { - Self::Entity::new_unchecked(self.as_slice().to_owned().into()) - } - - fn new_unchecked(slice: &'r [u8]) -> Self { - TransferReader(slice) - } - - fn as_slice(&self) -> &'r [u8] { - self.0 - } - - fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { - use molecule::verification_error as ve; - let slice_len = slice.len(); - if slice_len < molecule::NUMBER_SIZE { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); - } - let total_size = molecule::unpack_number(slice) as usize; - if slice_len != total_size { - return ve!(Self, TotalSizeNotMatch, total_size, slice_len); - } - if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { - return Ok(()); - } - if slice_len < molecule::NUMBER_SIZE * 2 { - return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); - } - let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { - return ve!(Self, OffsetsNotMatch); - } - if slice_len < offset_first { - return ve!(Self, HeaderIsBroken, offset_first, slice_len); - } - let field_count = offset_first / molecule::NUMBER_SIZE - 1; - if field_count < Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - } else if !compatible && field_count > Self::FIELD_COUNT { - return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); - }; - let mut offsets: Vec = slice[molecule::NUMBER_SIZE..offset_first] - .chunks_exact(molecule::NUMBER_SIZE) - .map(|x| molecule::unpack_number(x) as usize) - .collect(); - offsets.push(total_size); - if offsets.windows(2).any(|i| i[0] > i[1]) { - return ve!(Self, OffsetsNotMatch); - } - AddressReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; - Uint64Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?; - Uint128Reader::verify(&slice[offsets[2]..offsets[3]], compatible)?; - AddressReader::verify(&slice[offsets[3]..offsets[4]], compatible)?; - Ok(()) - } -} -#[derive(Debug, Default)] -pub struct TransferBuilder { - pub(crate) axon_address: Address, - pub(crate) ckb_amount: Uint64, - pub(crate) s_u_d_t_amount: Uint128, - pub(crate) e_r_c20_address: Address, -} -impl TransferBuilder { - pub const FIELD_COUNT: usize = 4; - - pub fn axon_address(mut self, v: Address) -> Self { - self.axon_address = v; - self - } - - pub fn ckb_amount(mut self, v: Uint64) -> Self { - self.ckb_amount = v; - self - } - - pub fn s_u_d_t_amount(mut self, v: Uint128) -> Self { - self.s_u_d_t_amount = v; - self - } - - pub fn e_r_c20_address(mut self, v: Address) -> Self { - self.e_r_c20_address = v; - self - } -} -impl molecule::prelude::Builder for TransferBuilder { - type Entity = Transfer; - - const NAME: &'static str = "TransferBuilder"; - - fn expected_length(&self) -> usize { - molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) - + self.axon_address.as_slice().len() - + self.ckb_amount.as_slice().len() - + self.s_u_d_t_amount.as_slice().len() - + self.e_r_c20_address.as_slice().len() - } - - fn write(&self, writer: &mut W) -> molecule::io::Result<()> { - let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); - let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); - offsets.push(total_size); - total_size += self.axon_address.as_slice().len(); - offsets.push(total_size); - total_size += self.ckb_amount.as_slice().len(); - offsets.push(total_size); - total_size += self.s_u_d_t_amount.as_slice().len(); - offsets.push(total_size); - total_size += self.e_r_c20_address.as_slice().len(); - writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; - for offset in offsets.into_iter() { - writer.write_all(&molecule::pack_number(offset as molecule::Number))?; - } - writer.write_all(self.axon_address.as_slice())?; - writer.write_all(self.ckb_amount.as_slice())?; - writer.write_all(self.s_u_d_t_amount.as_slice())?; - writer.write_all(self.e_r_c20_address.as_slice())?; - Ok(()) - } - - fn build(&self) -> Self::Entity { - let mut inner = Vec::with_capacity(self.expected_length()); - self.write(&mut inner) - .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); - Transfer::new_unchecked(inner.into()) - } -} diff --git a/core/cross-client/src/generated/mod.rs b/core/cross-client/src/generated/mod.rs deleted file mode 100644 index e79b81638..000000000 --- a/core/cross-client/src/generated/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -#[allow(clippy::all)] -pub mod axon; -#[allow(clippy::all)] -pub mod crosschain; - -pub use crosschain::*; diff --git a/core/cross-client/src/lib.rs b/core/cross-client/src/lib.rs deleted file mode 100644 index 7a1f79d91..000000000 --- a/core/cross-client/src/lib.rs +++ /dev/null @@ -1,476 +0,0 @@ -#![allow(clippy::uninlined_format_args)] - -mod abi; -mod adapter; -mod error; -#[allow(dead_code)] -mod generated; -pub mod monitor; -mod sidechain; -mod task; - -pub use abi::{crosschain_abi, wckb_abi}; -pub use adapter::{CrossChainDBImpl, DefaultCrossChainAdapter}; -use protocol::codec::ProtocolCodec; -pub use task::message::{ - CrossChainMessageHandler, END_GOSSIP_BUILD_CKB_TX, END_GOSSIP_CKB_TX_SIGNATURE, -}; - -use std::sync::Arc; - -use arc_swap::ArcSwap; -use ckb_sdk::constants::ONE_CKB; -use ckb_types::{core::TransactionView, prelude::*}; -use ethers_contract::decode_logs; -use ethers_core::abi::{decode as abi_decode, AbiEncode, AbiType, Detokenize, RawLog}; - -use common_config_parser::types::ConfigCrossChain; -use common_crypto::{ - PrivateKey, Secp256k1RecoverablePrivateKey, Signature, ToPublicKey, UncompressedPublicKey, -}; -use protocol::tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; -use protocol::traits::{CkbClient, Context, CrossAdapter, CrossChain}; -use protocol::types::{ - Address, Block, BlockNumber, Direction, Eip1559Transaction, Hash, Hasher, Log, Proof, - RequestTxHashes, Requests, SignedTransaction, TransactionAction, Transfer, UnsignedTransaction, - UnverifiedTransaction, H160, H256, MAX_BLOCK_GAS_LIMIT, MAX_PRIORITY_FEE_PER_GAS, U256, -}; -use protocol::{async_trait, lazy::CHAIN_ID, tokio, ProtocolResult}; - -use crate::error::CrossChainError; -use crate::task::{message::CrossChainMessage, RequestCkbTask}; -use crate::{adapter::fixed_array, monitor::CrossChainMonitor, sidechain::SidechainTask}; - -pub const CKB_BLOCK_INTERVAL: u64 = 8; // second -pub const NON_FORK_BLOCK_GAP: u64 = 24; -const BASE_CROSSCHAIN_CELL_CAPACITY: u64 = 200 * ONE_CKB; - -lazy_static::lazy_static! { - pub static ref CKB_TIP: ArcSwap = ArcSwap::from_pointee(0); -} - -pub struct CrossChainImpl { - priv_key: Secp256k1RecoverablePrivateKey, - address: H160, - log_rx: UnboundedReceiver<(Vec>, H256)>, - req_rx: UnboundedReceiver>, - reqs_tx: UnboundedSender, - - adapter: Arc, - - cross_chain_address: H160, - wckb_address: H160, -} - -impl CrossChainImpl { - pub async fn new( - private_key: &[u8], - config: ConfigCrossChain, - ckb_client: Arc, - adapter: Arc, - cross_chain_address: H160, - wckb_address: H160, - ) -> ( - Self, - CrossChainHandler, - UnboundedSender, - ) { - let priv_key = Secp256k1RecoverablePrivateKey::try_from(private_key) - .expect("Invalid secp private key"); - let address = Address::from_pubkey_bytes(priv_key.pub_key().to_uncompressed_bytes()) - .unwrap() - .0; - - let (log_tx, log_rx) = unbounded_channel(); - let (req_tx, req_rx) = unbounded_channel(); - let client_clone = Arc::clone(&ckb_client); - let _init_monitor_number = adapter - .get_monitor_ckb_number(Context::new()) - .await - .unwrap_or(config.start_block_number); - - let (reqs_tx, reqs_rx) = unbounded_channel(); - let (ckb_task, crosschain_net_handler) = - RequestCkbTask::new(address, private_key, reqs_rx, Arc::clone(&adapter)).await; - - tokio::spawn(async move { ckb_task.run().await }); - - let adapter_clone = Arc::clone(&adapter); - tokio::spawn(async move { - CrossChainMonitor::new( - client_clone, - req_tx, - config.start_block_number, - config.acs_lock_code_hash, - config.request_type_code_hash, - adapter_clone, - ) - .await - .run() - .await - }); - - let handler = CrossChainHandler::new(priv_key.clone(), log_tx, config, ckb_client); - let crosschain = CrossChainImpl { - priv_key, - address, - log_rx, - req_rx, - reqs_tx, - adapter, - cross_chain_address, - wckb_address, - }; - - crosschain - .recover_tasks() - .await - .expect("Recover crosschain tasks"); - - (crosschain, handler, crosschain_net_handler) - } - - pub async fn run(mut self) { - loop { - tokio::select! { - Some((logs, block_hash)) = self.log_rx.recv() => { - let (to_ckbs, to_ckb_alerts) = self.classify_logs(logs, block_hash).await.unwrap(); - - if !to_ckbs.is_empty() { - let tx_clone = self.reqs_tx.clone(); - tokio::spawn(async move { - build_ckb_tx_process(to_ckbs, tx_clone, &self.wckb_address).await; - }); - } - - if !to_ckb_alerts.is_empty() { - log::error!("to_ckb_alerts"); - } - } - - Some(reqs) = self.req_rx.recv() => { - log::info!("[cross-chain]: receive requests {:?} from CKB", reqs); - let nonce = self.nonce(self.address).await; - let (reqs, stx) = build_axon_txs(reqs, nonce, &self.priv_key, self.cross_chain_address); - self.adapter.insert_in_process( - Context::new(), - &rlp::encode(&reqs).freeze(), - &rlp::encode(&stx).freeze() - ) - .await - .unwrap(); - self.adapter.send_axon_tx(Context::new(), stx).await.unwrap(); - } - } - } - } - - async fn recover_tasks(&self) -> ProtocolResult<()> { - let ctx = Context::new(); - - for item in self.adapter.get_all_in_process(ctx.clone()).await?.iter() { - let req: Requests = - rlp::decode(&item.0).map_err(|e| CrossChainError::Adapter(e.to_string()))?; - let direction = req.direction(); - - if direction.is_from_ckb() { - let _ = self - .adapter - .send_axon_tx( - ctx.clone(), - rlp::decode(&item.1) - .map_err(|e| CrossChainError::Adapter(e.to_string()))?, - ) - .await; - } - } - - Ok(()) - } - - async fn classify_logs( - &self, - logs: Vec>, - block_hash: H256, - ) -> ProtocolResult<( - Vec, - Vec, - )> { - let logs = logs.iter().filter_map(|inner_logs| { - inner_logs.last().cloned().map(|l| RawLog { - topics: l.topics.clone(), - data: l.data, - }) - }); - - let mut to_ckbs = Vec::new(); - let mut to_ckb_alerts = Vec::new(); - - for log in logs { - if let Ok(event) = decode_logs::(&[log.clone()]) { - let key = rlp::encode::(&(event[0].clone().into())); - let relay_tx = SignedTransaction::decode( - self.adapter - .get_in_process(Context::new(), &key) - .await? - .unwrap(), - )?; - self.adapter.remove_in_process(Context::new(), &key).await?; - - let hashes = event[0] - .records - .iter() - .map(|r| H256(r.tx_hash)) - .collect::>(); - self.adapter - .insert_record( - Context::new(), - RequestTxHashes::new_from_ckb(hashes), - relay_tx.transaction.hash, - ) - .await?; - - log::info!( - "[crosschain]: Complete cross from CKB, request count {:?}, axon tx hash {:?}", - event[0].records.len(), - relay_tx.transaction.hash - ); - } else if let Ok(event) = - decode_logs::(&[log.clone()]) - { - log::info!( - "[crosschain]: Complete cross from Axon, axon block hash {:?}", - block_hash - ); - to_ckbs.push(event[0].clone()); - } else if let Ok(event) = decode_logs::(&[log]) { - to_ckb_alerts.push(event[0].clone()); - } - } - - Ok((to_ckbs, to_ckb_alerts)) - } - - async fn nonce(&self, _address: H160) -> U256 { - self.adapter - .nonce(Context::new(), self.address) - .await - .unwrap() - + 1 - } -} - -pub struct CrossChainHandler { - priv_key: Secp256k1RecoverablePrivateKey, - logs_tx: UnboundedSender<(Vec>, H256)>, - config: ConfigCrossChain, - ckb_client: Arc, -} - -#[async_trait] -impl CrossChain for CrossChainHandler { - async fn set_evm_log( - &self, - _ctx: Context, - _block_number: BlockNumber, - block_hash: Hash, - logs: &[Vec], - ) { - if let Err(e) = self.logs_tx.send((logs.to_vec(), block_hash)) { - log::error!("[cross-chain]: send log to process error {:?}", e); - } - } - - async fn set_checkpoint(&self, _ctx: Context, block: Block, proof: Proof) { - let priv_key = self.priv_key.clone(); - let node_address = self.config.node_address; - let admin_address = self.config.admin_address; - let selection_lock_hash = self.config.selection_lock_hash; - let checkpoint_type_hash = self.config.checkpoint_type_hash; - let ckb_client = Arc::clone(&self.ckb_client); - - tokio::spawn(async move { - SidechainTask::new( - priv_key, - node_address, - admin_address, - selection_lock_hash, - checkpoint_type_hash, - ) - .run(Arc::clone(&ckb_client), block, proof) - .await - }); - } -} - -impl CrossChainHandler { - fn new( - priv_key: Secp256k1RecoverablePrivateKey, - logs_tx: UnboundedSender<(Vec>, H256)>, - config: ConfigCrossChain, - ckb_client: Arc, - ) -> Self { - CrossChainHandler { - priv_key, - logs_tx, - config, - ckb_client, - } - } -} - -pub fn decode_resp_nonce(data: &[u8]) -> U256 { - U256::from_tokens(abi_decode(&[U256::param_type()], data).unwrap()).unwrap() -} - -async fn build_ckb_tx_process( - to_ckbs: Vec, - request_tx: UnboundedSender, - wckb_address: &H160, -) { - let _ = request_tx.send(Requests( - to_ckbs - .iter() - .map(|log| { - let (s_amount, c_amount) = if &log.token == wckb_address { - (0, log.amount.as_u64() + BASE_CROSSCHAIN_CELL_CAPACITY) - } else { - (log.amount.as_u128(), BASE_CROSSCHAIN_CELL_CAPACITY) - }; - - Transfer { - direction: Direction::FromAxon, - ckb_address: log.to.clone(), - address: H160::default(), - erc20_address: log.token, - sudt_amount: s_amount, - ckb_amount: c_amount, - tx_hash: H256::default(), - } - }) - .collect::>(), - )); -} - -pub fn build_axon_txs( - txs: Vec, - addr_nonce: U256, - priv_key: &Secp256k1RecoverablePrivateKey, - cross_chain_address: H160, -) -> (Requests, SignedTransaction) { - let reqs = txs - .iter() - .map(|tx| { - let type_script = tx.output(1).unwrap().type_().to_opt().unwrap(); - let request_args = generated::Transfer::new_unchecked(type_script.args().unpack()); - - Transfer { - direction: Direction::FromCkb, - ckb_address: String::new(), - tx_hash: H256::from_slice(&tx.hash().raw_data()), - address: H160::from_slice(&request_args.axon_address().raw_data()), - erc20_address: H160::from_slice(&request_args.e_r_c20_address().raw_data()), - ckb_amount: u64::from_le_bytes(fixed_array( - &request_args.ckb_amount().raw_data(), - )), - sudt_amount: u128::from_le_bytes(fixed_array( - &request_args.s_u_d_t_amount().raw_data(), - )), - } - }) - .collect::>(); - - let call_data = crosschain_abi::CrossFromCKBCall { - records: reqs - .iter() - .map(|req| crosschain_abi::CkbtoAxonRecord { - to: req.address, - token_address: req.erc20_address, - s_udt_amount: req.sudt_amount.into(), - ckb_amount: req.ckb_amount.into(), - tx_hash: req.tx_hash.0, - }) - .collect(), - nonce: U256::zero(), - }; - - let tx = UnsignedTransaction::Eip1559(Eip1559Transaction { - nonce: addr_nonce, - max_priority_fee_per_gas: MAX_PRIORITY_FEE_PER_GAS.into(), - gas_price: U256::zero(), - gas_limit: MAX_BLOCK_GAS_LIMIT.into(), - action: TransactionAction::Call(cross_chain_address), - value: U256::zero(), - data: AbiEncode::encode(call_data).into(), - access_list: vec![], - }); - - let id = **CHAIN_ID.load(); - let signature = priv_key.sign_message( - &Hasher::digest(tx.encode(id, None)) - .as_bytes() - .try_into() - .unwrap(), - ); - - let utx = UnverifiedTransaction { - unsigned: tx, - signature: Some(signature.to_bytes().into()), - chain_id: id, - hash: Default::default(), - } - .calc_hash(); - - let stx: SignedTransaction = utx.try_into().unwrap(); - - log::info!("[cross-chain]: build cross from CKB transaction {:?}", stx); - - (Requests(reqs), stx) -} - -impl From for Requests { - fn from(logs: crosschain_abi::CrossFromCKBFilter) -> Self { - Requests( - logs.records - .into_iter() - .map(|r| Transfer { - direction: Direction::FromCkb, - ckb_address: String::new(), - address: r.to, - erc20_address: r.token_address, - sudt_amount: r.s_udt_amount.as_u128(), - ckb_amount: r.ckb_amount.as_u64(), - tx_hash: H256(r.tx_hash), - }) - .collect(), - ) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_raw_data() { - let transfer = generated::TransferBuilder::default().build(); - assert_eq!( - transfer.axon_address().raw_data(), - H160::default().0.to_vec() - ); - - let byte32 = ckb_types::packed::Byte32Builder::default().build(); - assert_eq!(byte32.raw_data(), H256::default().0.to_vec()); - } - - #[test] - #[ignore] - fn gen_abi_binding() { - ethers_contract::Abigen::new("wckb", "./wckb_abi.json") - .unwrap() - .generate() - .unwrap() - .write_to_file("src/abi/wckb_abi.rs") - .unwrap(); - } -} diff --git a/core/cross-client/src/monitor.rs b/core/cross-client/src/monitor.rs deleted file mode 100644 index 4a11b4135..000000000 --- a/core/cross-client/src/monitor.rs +++ /dev/null @@ -1,154 +0,0 @@ -use std::sync::Arc; -use std::time::Duration; - -use ckb_types::core::{BlockView, TransactionView}; -use ckb_types::{packed, prelude::Pack}; - -use protocol::tokio::{sync::mpsc::UnboundedSender, time}; -use protocol::traits::{CkbClient, Context, CrossAdapter}; -use protocol::types::H256; -use protocol::ProtocolResult; - -use crate::{error::CrossChainError, CKB_BLOCK_INTERVAL, CKB_TIP, NON_FORK_BLOCK_GAP}; - -pub struct CrossChainMonitor { - ckb_client: Arc, - req_tx: UnboundedSender>, - handle_ckb_number: u64, - acs_code_hash: packed::Byte32, - request_code_hash: packed::Byte32, - - adapter: Arc, -} - -impl CrossChainMonitor -where - C: CkbClient + 'static, - Adapter: CrossAdapter + 'static, -{ - pub async fn new( - client: Arc, - sender: UnboundedSender>, - init_ckb_number: u64, - acs_code_hash: H256, - request_code_hash: H256, - cross_adapter: Arc, - ) -> Self { - let init_number = cross_adapter - .get_monitor_ckb_number(Context::new()) - .await - .unwrap_or(init_ckb_number); - - CKB_TIP.swap(Arc::new(init_number + NON_FORK_BLOCK_GAP)); - - CrossChainMonitor { - ckb_client: client, - req_tx: sender, - handle_ckb_number: init_number, - acs_code_hash: acs_code_hash.0.pack(), - request_code_hash: request_code_hash.0.pack(), - adapter: cross_adapter, - } - } - - pub async fn run(mut self) { - let mut interval = time::interval(Duration::from_secs(CKB_BLOCK_INTERVAL)); - - loop { - if let Err(e) = self.update_tip_number().await { - log::error!("[cross-chain]: monitor error {:?}", e); - } - - interval.tick().await; - } - } - - async fn update_tip_number(&mut self) -> ProtocolResult<()> { - let tip_header = self.ckb_client.get_tip_header(Context::new()).await?; - - let tip_number: u64 = tip_header.inner.number.into(); - let current_tip = **CKB_TIP.load(); - - if current_tip < tip_number { - CKB_TIP.swap(Arc::new(tip_number)); - self.fetch_block().await?; - } - - Ok(()) - } - - async fn fetch_block(&mut self) -> ProtocolResult<()> { - let non_fork_tip = **CKB_TIP.load() - NON_FORK_BLOCK_GAP; - if self.handle_ckb_number > non_fork_tip { - return Ok(()); - } - - let mut list = Vec::new(); - for i in self.handle_ckb_number..=non_fork_tip { - loop { - match self - .ckb_client - .get_block_by_number(Context::new(), i.into()) - .await - { - Ok(block) => { - list.append(&mut search_tx( - block.into(), - &self.acs_code_hash, - &self.request_code_hash, - )); - break; - } - Err(_e) => { - log::error!("[cross-chain]: get block from ckb node failed"); - time::sleep(Duration::from_secs(2)).await; - } - } - } - } - - if !list.is_empty() { - log::info!( - "[cross-chain]: Cross from CKB block {:?}, request tx count {:?}", - (self.handle_ckb_number..=non_fork_tip), - list.len() - ); - - self.req_tx - .send(list) - .map_err(|e| CrossChainError::Sender(e.to_string()))?; - } - - self.handle_ckb_number = non_fork_tip + 1; - self.adapter - .update_monitor_ckb_number(Context::new(), self.handle_ckb_number) - .await?; - Ok(()) - } -} - -pub fn search_tx( - block: BlockView, - acs_code_hash: &packed::Byte32, - request_code_hash: &packed::Byte32, -) -> Vec { - block - .transactions() - .into_iter() - .filter(|tx| { - if tx.is_cellbase() || tx.output_pts().len() < 2 { - return false; - } - - if &tx.output(0).unwrap().lock().code_hash() == acs_code_hash { - if let Some(type_script) = tx.output(1).unwrap().type_().to_opt() { - if &type_script.code_hash() == request_code_hash { - return true; - } - } - } - - false - }) - .collect() -} diff --git a/core/cross-client/src/schemas/axon.mol b/core/cross-client/src/schemas/axon.mol deleted file mode 100644 index 95ea71a09..000000000 --- a/core/cross-client/src/schemas/axon.mol +++ /dev/null @@ -1,88 +0,0 @@ -array Byte4 [byte; 4]; -array Byte8 [byte; 8]; -array Byte10 [byte; 10]; -array Byte16 [byte; 16]; -array Byte20 [byte; 20]; -array Byte32 [byte; 32]; -array Byte48 [byte; 48]; - -table Identity { - flag: byte, - content: Byte20, -} - -table StakeInfo { - identity: Identity, - l2_address: Byte20, - bls_pub_key: Byte48, - stake_amount: Byte16, - inauguration_era: Byte8, -} - -vector Bytes ; -vector StakeInfoVec ; -option IdentityOpt (Identity); - -//////////////////// -// selection lock -//////////////////// -table SelectionLockArgs { - omni_lock_hash: Byte32, - checkpoint_lock_hash: Byte32, -} - -//////////////////// -// stake lock -//////////////////// -table StakeLockArgs { - admin_identity: Identity, - type_id_hash: Byte32, - node_identity: IdentityOpt, -} - -table StakeLockCellData { - version: byte, - stake_infos: StakeInfoVec, - checkpoint_type_hash: Byte32, - sudt_type_hash: Byte32, - quorum_size: byte, -} - -//////////////////// -// checkpoint lock -//////////////////// -table CheckpointLockArgs { - admin_identity: Identity, - type_id_hash: Byte32, -} - -table CheckpointLockCellData { - version: byte, - state: byte, - period: Byte8, - era: Byte8, - block_hash: Byte32, - period_interval: Byte4, - era_period: Byte4, - unlock_period: Byte4, - base_reward: Byte16, - half_period: Byte8, - common_ref: Byte10, - sudt_type_hash: Byte32, - stake_type_hash: Byte32, - withdrawal_lock_code_hash: Byte32, -} - -table CheckpointLockWitnessLock { - proposal: Bytes, - proof: Bytes, -} - -//////////////////// -// withdrawal lock -//////////////////// -table WithdrawalLockArgs { - admin_identity: Identity, - checkpoint_cell_type_hash: Byte32, - node_identity: IdentityOpt, -} diff --git a/core/cross-client/src/schemas/crosschain.mol b/core/cross-client/src/schemas/crosschain.mol deleted file mode 100644 index 484ea1322..000000000 --- a/core/cross-client/src/schemas/crosschain.mol +++ /dev/null @@ -1,36 +0,0 @@ -array Uint32 [byte; 4]; -array Uint64 [byte; 8]; -array Uint128 [byte; 16]; -array Address [byte; 20]; -array Hash [byte; 32]; -array BlsPubkey [byte; 48]; -array Signautre [byte; 65]; - -vector BlsPubkeyList ; - -table Witness { - signature: Signautre, - bls_pubkeys: BlsPubkeyList, -} - -table Token { - ERC20_address: Address, - sUDT_typehash: Hash, - fee_ratio: Uint32, -} - -vector TokenConfig ; - -table Metadata { - chain_id: byte, - token_config: TokenConfig, - ckb_fee_ratio: Uint32, - stake_typehash: Hash, -} - -table Transfer { - axon_address: Address, - ckb_amount: Uint64, - sUDT_amount: Uint128, - ERC20_address: Address, -} diff --git a/core/cross-client/src/sidechain.rs b/core/cross-client/src/sidechain.rs deleted file mode 100644 index be477096b..000000000 --- a/core/cross-client/src/sidechain.rs +++ /dev/null @@ -1,71 +0,0 @@ -use std::sync::Arc; - -use ckb_jsonrpc_types::OutputsValidator; - -use common_crypto::Secp256k1RecoverablePrivateKey; -use protocol::codec::ProtocolCodec; -use protocol::traits::{CkbClient, Context}; -use protocol::types::{Block, Hash, Identity, Proof, Proposal, SubmitCheckpointPayload, H160}; - -pub struct SidechainTask { - priv_key: Secp256k1RecoverablePrivateKey, - node_address: H160, - admin_address: H160, - selection_lock_hash: Hash, - checkpoint_type_hash: Hash, -} - -impl SidechainTask { - pub fn new( - priv_key: Secp256k1RecoverablePrivateKey, - node_address: H160, - admin_address: H160, - selection_lock_hash: Hash, - checkpoint_type_hash: Hash, - ) -> Self { - SidechainTask { - priv_key, - node_address, - admin_address, - selection_lock_hash, - checkpoint_type_hash, - } - } - - pub async fn run(self, client: Arc, block: Block, proof: Proof) { - let number = block.header.number; - let mut proposal = Proposal::from(&block).encode().unwrap().to_vec(); - let mut proof = proof.encode().unwrap().to_vec(); - proposal.append(&mut proof); - - let payload = SubmitCheckpointPayload { - node_id: Identity::new(0, self.node_address.0.to_vec()), - admin_id: Identity::new(0, self.admin_address.0.to_vec()), - period_number: number, - checkpoint: proposal.into(), - selection_lock_hash: self.selection_lock_hash.0.into(), - checkpoint_type_hash: self.checkpoint_type_hash.0.into(), - }; - - match client - .build_submit_checkpoint_transaction(Context::new(), payload) - .await - { - Ok(respond) => { - let tx = respond.sign(&self.priv_key); - match client - .send_transaction(Context::new(), &tx, Some(OutputsValidator::Passthrough)) - .await - { - Ok(tx_hash) => log::info!("set_checkpoint send tx hash: {}", tx_hash), - Err(e) => { - log::info!("set_checkpoint send tx error: {}", e); - } - } - } - Err(e) => { - log::info!("build_submit_checkpoint_transaction error: {}", e); - } - } - } -} diff --git a/core/cross-client/src/task/message.rs b/core/cross-client/src/task/message.rs deleted file mode 100644 index 55cdfe3cb..000000000 --- a/core/cross-client/src/task/message.rs +++ /dev/null @@ -1,143 +0,0 @@ -use ckb_types::{core::TransactionView, packed, prelude::*}; -use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream}; - -use common_crypto::{ - BlsPublicKey, BlsSignature, BlsSignatureVerify, HashValue, PublicKey, Signature, -}; -use protocol::async_trait; -use protocol::tokio::sync::mpsc::UnboundedSender; -use protocol::traits::{Context, MessageHandler, TrustFeedback}; -use protocol::types::{Bytes, H256}; - -pub const END_GOSSIP_BUILD_CKB_TX: &str = "/gossip/crosschain/ckb_tx"; -pub const END_GOSSIP_CKB_TX_SIGNATURE: &str = "/gossip/crosschain/signature"; - -pub struct CrossChainMessageHandler(UnboundedSender); - -#[async_trait] -impl MessageHandler for CrossChainMessageHandler { - type Message = CrossChainMessage; - - async fn process(&self, _ctx: Context, msg: Self::Message) -> TrustFeedback { - if let Err(e) = self.0.send(msg) { - log::warn!("set crosschain message {:?}", e); - return TrustFeedback::Worse(e.to_string()); - } - - TrustFeedback::Good - } -} - -impl CrossChainMessageHandler { - pub fn new(sender: UnboundedSender) -> Self { - CrossChainMessageHandler(sender) - } -} - -#[allow(clippy::large_enum_variant)] -#[derive(Clone, Debug)] -pub enum CrossChainMessage { - TxView(TxViewWrapper), - Signature(CrossChainSignature), -} - -impl Encodable for CrossChainMessage { - fn rlp_append(&self, s: &mut RlpStream) { - s.begin_list(2); - match self { - CrossChainMessage::TxView(hash) => s.append(&0u8).append(hash), - CrossChainMessage::Signature(sig) => s.append(&1u8).append(sig), - }; - } -} - -impl Decodable for CrossChainMessage { - fn decode(rlp: &Rlp) -> Result { - let ty: u8 = rlp.val_at(0)?; - match ty { - 0 => Ok(CrossChainMessage::TxView(rlp.val_at(1)?)), - 1 => Ok(CrossChainMessage::Signature(rlp.val_at(1)?)), - _ => Err(DecoderError::Custom("Invalid message type")), - } - } -} - -#[derive(Clone, Debug)] -pub struct TxViewWrapper { - pub req_hash: H256, - pub tx_view: TransactionView, -} - -impl TxViewWrapper { - pub fn new(req_hash: H256, tx_view: TransactionView) -> Self { - TxViewWrapper { req_hash, tx_view } - } -} - -impl Encodable for TxViewWrapper { - fn rlp_append(&self, s: &mut RlpStream) { - s.begin_list(2) - .append(&self.req_hash) - .append(&self.tx_view.pack().as_bytes()); - } -} - -impl Decodable for TxViewWrapper { - fn decode(rlp: &Rlp) -> Result { - Ok(TxViewWrapper { - req_hash: rlp.val_at(0)?, - tx_view: packed::TransactionView::new_unchecked(rlp.val_at(1)?).unpack(), - }) - } -} - -#[derive(Clone, Debug)] -pub struct CrossChainSignature { - pub req_hash: H256, - pub tx_hash: H256, - pub bls_pubkey: BlsPublicKey, - pub signature: BlsSignature, -} - -impl CrossChainSignature { - pub fn verify(&self) -> bool { - self.signature - .verify( - &HashValue::from_bytes_unchecked(self.tx_hash.0), - &self.bls_pubkey, - &String::new(), - ) - .is_ok() - } -} - -impl Encodable for CrossChainSignature { - fn rlp_append(&self, s: &mut RlpStream) { - s.begin_list(4) - .append(&self.req_hash) - .append(&self.tx_hash) - .append(&self.bls_pubkey.to_bytes()) - .append(&self.signature.to_bytes()); - } -} - -impl Decodable for CrossChainSignature { - fn decode(rlp: &Rlp) -> Result { - Ok(CrossChainSignature { - req_hash: rlp.val_at(0)?, - tx_hash: rlp.val_at(1)?, - bls_pubkey: { - let raw: Bytes = rlp.val_at(2)?; - raw.as_ref() - .try_into() - .map_err(|_| DecoderError::Custom("decode public key"))? - }, - signature: { - let raw: Bytes = rlp.val_at(3)?; - raw.as_ref() - .try_into() - .map_err(|_| DecoderError::Custom("decode public key"))? - }, - }) - } -} diff --git a/core/cross-client/src/task/mod.rs b/core/cross-client/src/task/mod.rs deleted file mode 100644 index 9e80919f0..000000000 --- a/core/cross-client/src/task/mod.rs +++ /dev/null @@ -1,311 +0,0 @@ -pub mod message; - -use std::collections::HashMap; -use std::sync::Arc; - -use ckb_types::prelude::Unpack; - -use common_crypto::{ - BlsPrivateKey, BlsPublicKey, BlsSignature, HashValue, PrivateKey, ToBlsPublicKey, -}; -use protocol::tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; -use protocol::traits::{Context, CrossAdapter, MessageTarget}; -use protocol::types::{Bytes, Hasher, Requests, ValidatorExtend, H160, H256}; -use protocol::{codec::ProtocolCodec, tokio, ProtocolResult}; - -use crate::error::CrossChainError; -use crate::task::message::{ - CrossChainMessage, CrossChainSignature, TxViewWrapper, END_GOSSIP_BUILD_CKB_TX, - END_GOSSIP_CKB_TX_SIGNATURE, -}; - -pub struct RequestCkbTask { - address: H160, - private_key: BlsPrivateKey, - public_key: BlsPublicKey, - validators: Vec, - validate_power: bool, - req_records: ReqRecords, - - reqs_rx: UnboundedReceiver, - net_rx: UnboundedReceiver, - - adapter: Arc, -} - -impl RequestCkbTask -where - Adapter: CrossAdapter + 'static, -{ - pub async fn new( - addr: H160, - private_key: &[u8], - reqs_rx: UnboundedReceiver, - adapter: Arc, - ) -> (Self, UnboundedSender) { - let (net_tx, net_rx) = unbounded_channel(); - let private_key = BlsPrivateKey::try_from(private_key).expect("Invalid bls private key"); - - let task = RequestCkbTask { - address: addr, - private_key: private_key.clone(), - public_key: private_key.pub_key(&String::new()), - validators: vec![], - validate_power: false, - req_records: Default::default(), - - reqs_rx, - net_rx, - - adapter, - }; - - (task, net_tx) - } - - async fn is_leader(&mut self, reqs: &Requests) -> bool { - self.update_metadata().await; - - if !self.validate_power { - return false; - } - - let offset = reqs.0.len() % self.validators.len(); - self.validators[offset].address == self.address - } - - fn calc_leader(&self, hash: &H256) -> H160 { - let reqs = self.req_records.get_req(hash).unwrap(); - self.validators[reqs.0.len() % self.validators.len()].address - } - - async fn update_metadata(&mut self) { - let mut validators = self - .adapter - .current_metadata(Context::new()) - .await - .verifier_list; - validators.sort(); - self.validators = validators; - self.update_validate_power().await; - self.req_records - .update_threshold((self.validators.len() / 3) * 2 + 1) - } - - async fn update_validate_power(&mut self) { - self.validate_power = self.validators.iter().any(|ve| ve.address == self.address); - } - - pub async fn run(mut self) { - loop { - tokio::select! { - Some(reqs) = self.reqs_rx.recv() => { - log::info!("[cross-chain]: receive cross to CKB requests, len {}", reqs.0.len()); - - if let Err(e) = self.handle_reqs(reqs).await { - log::error!("[cross-chain]: handle requests error {:?}", e); - } - } - Some(msg) = self.net_rx.recv() => { - log::info!("[cross-chain]: receive network message {:?}", msg); - - if let Err(e) = self.handle_msgs(msg).await { - log::error!("[cross-chain]: handle message error {:?}", e); - } - } - } - } - } - - async fn handle_msgs(&mut self, msg: CrossChainMessage) -> ProtocolResult<()> { - if !self.validate_power { - return Ok(()); - } - - match msg { - CrossChainMessage::TxView(tx_view_wrapper) => { - if let Ok(sig) = self.verify_tx_wrapper(&tx_view_wrapper) { - self.adapter - .transmit( - Context::new(), - CrossChainMessage::Signature(sig).encode().unwrap().to_vec(), - END_GOSSIP_CKB_TX_SIGNATURE, - MessageTarget::Specified(Bytes::from( - self.calc_leader(&tx_view_wrapper.req_hash) - .to_fixed_bytes() - .to_vec(), - )), - ) - .await?; - } - } - - CrossChainMessage::Signature(sig) => { - if let Some((c_sig, pks)) = - self.req_records.insert_vote(&sig.req_hash, (&sig).into()) - { - let _tx = - self.adapter - .build_to_ckb_tx(Context::new(), sig.tx_hash, &c_sig, &pks); - } - } - } - - Ok(()) - } - - async fn handle_reqs(&mut self, reqs: Requests) -> ProtocolResult<()> { - if !self.is_leader(&reqs).await { - log::warn!("[cross-client]: do not have power"); - return Ok(()); - } - - let hash = self.req_records.add_req(reqs.clone()); - - log::info!("[cross-chain]: cross to CKB request {:?}", reqs.0); - - let ctx = Context::new(); - let tx_view = self.adapter.calc_to_ckb_tx(ctx.clone(), &reqs.0).await?; - self.req_records - .update_tx_hash(&hash, H256(tx_view.hash().unpack().0)); - - let tx_wrapper = TxViewWrapper::new(hash, tx_view); - - if self.validators.len() == 1 { - let sig = self.verify_tx_wrapper(&tx_wrapper)?; - let comb_sig = - BlsSignature::combine(vec![(sig.signature.clone(), sig.bls_pubkey.clone())]) - .map_err(|e| CrossChainError::Crypto(e.to_string()))?; - - let intact_tx = - self.adapter - .build_to_ckb_tx(ctx.clone(), sig.tx_hash, &comb_sig, &[sig.bls_pubkey])?; - - return self - .adapter - .send_ckb_tx(ctx.clone(), intact_tx.into()) - .await; - } - - self.adapter - .transmit( - ctx.clone(), - CrossChainMessage::TxView(tx_wrapper) - .encode() - .unwrap() - .to_vec(), - END_GOSSIP_BUILD_CKB_TX, - MessageTarget::Broadcast, - ) - .await - } - - fn verify_tx_wrapper(&self, tx: &TxViewWrapper) -> ProtocolResult { - // Todo: add verify process - let sig = self - .private_key - .sign_message(&HashValue::from_bytes_unchecked( - tx.tx_view.hash().unpack().0, - )); - - Ok(CrossChainSignature { - req_hash: tx.req_hash, - tx_hash: H256(tx.tx_view.hash().unpack().0), - bls_pubkey: self.public_key.clone(), - signature: sig, - }) - } -} - -#[derive(Default, Clone, Debug)] -struct ReqRecords(HashMap, usize); - -impl ReqRecords { - fn _new(threshold: usize) -> Self { - ReqRecords(HashMap::new(), threshold) - } - - fn get_req(&self, hash: &H256) -> Option { - self.0.get(hash).map(|b| b.reqs.clone()) - } - - fn add_req(&mut self, req: Requests) -> H256 { - let hash = Hasher::digest(&req.encode().unwrap()); - self.0.entry(hash).or_insert_with(|| ReqBucket::new(req)); - hash - } - - fn update_tx_hash(&mut self, req_hash: &H256, tx_hash: H256) { - if let Some(b) = self.0.get_mut(req_hash) { - b.set_tx_hash(tx_hash); - } - } - - fn update_threshold(&mut self, threshold: usize) { - self.1 = threshold; - } - - fn insert_vote( - &mut self, - req_hash: &H256, - vote: Vote, - ) -> Option<(BlsSignature, Vec)> { - if let Some(b) = self.0.get_mut(req_hash) { - b.add_vote(vote); - - if b.votes.len() == self.1 { - let mut sig_pks = Vec::with_capacity(self.1); - let mut pks = Vec::with_capacity(self.1); - - for v in b.votes.iter() { - sig_pks.push((v.signature.clone(), v.pubkey.clone())); - pks.push(v.pubkey.clone()); - } - - return Some((BlsSignature::combine(sig_pks).unwrap(), pks)); - } - } - - None - } -} - -#[derive(Clone, Debug)] -struct ReqBucket { - reqs: Requests, - tx_hash: H256, - votes: Vec, -} - -impl ReqBucket { - fn new(reqs: Requests) -> Self { - ReqBucket { - reqs, - tx_hash: H256::default(), - votes: Vec::new(), - } - } - - fn set_tx_hash(&mut self, tx_hash: H256) { - self.tx_hash = tx_hash; - } - - fn add_vote(&mut self, vote: Vote) { - self.votes.push(vote); - } -} - -#[derive(Clone, Debug)] -struct Vote { - pubkey: BlsPublicKey, - signature: BlsSignature, -} - -impl From<&CrossChainSignature> for Vote { - fn from(signature: &CrossChainSignature) -> Self { - Vote { - pubkey: signature.bls_pubkey.clone(), - signature: signature.signature.clone(), - } - } -} diff --git a/core/cross-client/wckb_abi.json b/core/cross-client/wckb_abi.json deleted file mode 100644 index b89b669c0..000000000 --- a/core/cross-client/wckb_abi.json +++ /dev/null @@ -1,598 +0,0 @@ -[ - { - "inputs": [ - { - "internalType": "string", - "name": "name", - "type": "string" - }, - { - "internalType": "string", - "name": "symbol", - "type": "string" - }, - { - "internalType": "uint8", - "name": "decimals_", - "type": "uint8" - } - ], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "spender", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "value", - "type": "uint256" - } - ], - "name": "Approval", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "previousOwner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "newOwner", - "type": "address" - } - ], - "name": "OwnershipTransferred", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "indexed": true, - "internalType": "bytes32", - "name": "previousAdminRole", - "type": "bytes32" - }, - { - "indexed": true, - "internalType": "bytes32", - "name": "newAdminRole", - "type": "bytes32" - } - ], - "name": "RoleAdminChanged", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "indexed": true, - "internalType": "address", - "name": "account", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "sender", - "type": "address" - } - ], - "name": "RoleGranted", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "indexed": true, - "internalType": "address", - "name": "account", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "sender", - "type": "address" - } - ], - "name": "RoleRevoked", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "from", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "value", - "type": "uint256" - } - ], - "name": "Transfer", - "type": "event" - }, - { - "inputs": [], - "name": "DEFAULT_ADMIN_ROLE", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "MANAGER_ROLE", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "internalType": "address", - "name": "spender", - "type": "address" - } - ], - "name": "allowance", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "spender", - "type": "address" - }, - { - "internalType": "uint256", - "name": "amount", - "type": "uint256" - } - ], - "name": "approve", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "balanceOf", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "from", - "type": "address" - }, - { - "internalType": "uint256", - "name": "amount", - "type": "uint256" - } - ], - "name": "burn", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "decimals", - "outputs": [ - { - "internalType": "uint8", - "name": "", - "type": "uint8" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "spender", - "type": "address" - }, - { - "internalType": "uint256", - "name": "subtractedValue", - "type": "uint256" - } - ], - "name": "decreaseAllowance", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - } - ], - "name": "getRoleAdmin", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "grantRole", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "hasRole", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "spender", - "type": "address" - }, - { - "internalType": "uint256", - "name": "addedValue", - "type": "uint256" - } - ], - "name": "increaseAllowance", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "amount", - "type": "uint256" - } - ], - "name": "mint", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "name", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "owner", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "renounceOwnership", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "renounceRole", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "role", - "type": "bytes32" - }, - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "revokeRole", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes4", - "name": "interfaceId", - "type": "bytes4" - } - ], - "name": "supportsInterface", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "symbol", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "totalSupply", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "amount", - "type": "uint256" - } - ], - "name": "transfer", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "from", - "type": "address" - }, - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "amount", - "type": "uint256" - } - ], - "name": "transferFrom", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "newOwner", - "type": "address" - } - ], - "name": "transferOwnership", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - } -] diff --git a/core/executor/Cargo.toml b/core/executor/Cargo.toml index 060c693d3..3bfa556f5 100644 --- a/core/executor/Cargo.toml +++ b/core/executor/Cargo.toml @@ -16,7 +16,7 @@ common-config-parser = { path = "../../common/config-parser" } common-crypto = { path = "../../common/crypto" } common-merkle = { path = "../../common/merkle" } core-interoperation = { path = "../interoperation" } -ethers = "1.0" +ethers = "2.0" evm = { version = "0.37", features = ["tracing"] } futures = "0.3" hasher = "0.1" @@ -27,7 +27,6 @@ molecule = "0.7" once_cell = "1.17" parking_lot = "0.12" protocol = { path = "../../protocol", package = "axon-protocol" } -rand = { version = "0.8", features = ["small_rng"] } ripemd = "0.1" rlp = "0.5" rlp-derive = "0.1" @@ -41,18 +40,13 @@ bytemuck = "1.13" ckb-jsonrpc-types = "0.106" ckb-types = "0.106" common-crypto = { path = "../../common/crypto" } -core-cross-client = { path = "../cross-client" } core-rpc-client = { path = "../rpc-client" } core-storage = { path = "../storage" } criterion = "0.4" ethabi = "18.0" ethabi-contract = { git = "https://github.com/rust-ethereum/ethabi.git", rev = "7edf185" } ethabi-derive = { git = "https://github.com/rust-ethereum/ethabi.git", rev = "7edf185" } -ethers-contract = "1.0" -ethers-core = "1.0" -getrandom = "0.2" hashbrown = "0.13" -rand7 = { package = "rand", version = "0.7" } revm = "2.3" rlp = "0.5" serde_json = "1.0" diff --git a/core/executor/benches/bench_convert_u256.rs b/core/executor/benches/bench_convert_u256.rs index ff7c2f24e..f1e03e317 100644 --- a/core/executor/benches/bench_convert_u256.rs +++ b/core/executor/benches/bench_convert_u256.rs @@ -46,14 +46,14 @@ fn criterion_convert(c: &mut Criterion) { fn criterion_rand(c: &mut Criterion) { const RAND_SEED: u64 = 49999; - use rand::rngs::SmallRng; - use rand::{Rng, SeedableRng}; + use protocol::rand::rngs::SmallRng; + use protocol::rand::{Rng, SeedableRng}; // MacOS M1 Pro 16G: 15.80µs c.bench_function("gen rand", |b| { b.iter(|| { let mut rng = SmallRng::seed_from_u64(RAND_SEED); for _ in 0..10000 { - rng.gen_range(10..1000000); + rng.gen_range(10, 1000000); } }) }); diff --git a/core/executor/benches/mock.rs b/core/executor/benches/mock.rs index d0932a907..0be032bfa 100644 --- a/core/executor/benches/mock.rs +++ b/core/executor/benches/mock.rs @@ -133,8 +133,9 @@ impl From for KeyPair { } fn gen_key_pairs(n: usize) -> Vec { + use protocol::rand::rngs::OsRng; + let mut result = Vec::with_capacity(n); - use rand7::rngs::OsRng; for _ in 0..n { let private_key = Secp256k1RecoverablePrivateKey::generate(&mut OsRng); result.push(KeyPair::from(private_key)); diff --git a/core/executor/src/adapter/trie_db.rs b/core/executor/src/adapter/trie_db.rs index b5c25becd..20d75b0fb 100644 --- a/core/executor/src/adapter/trie_db.rs +++ b/core/executor/src/adapter/trie_db.rs @@ -1,13 +1,13 @@ use std::{collections::HashMap, fs, io, path::Path, sync::Arc}; use parking_lot::RwLock; -use rand::{rngs::SmallRng, Rng, SeedableRng}; use rocksdb::ops::{Get, Open, Put, WriteOps}; use rocksdb::{FullOptions, Options, WriteBatch, DB}; use common_apm::metrics::storage::{on_storage_get_state, on_storage_put_state}; use common_apm::Instant; use common_config_parser::types::ConfigRocksDB; +use protocol::rand::{rngs::SmallRng, Rng, SeedableRng}; use protocol::{trie, Display, From, ProtocolError, ProtocolErrorKind, ProtocolResult}; // 49999 is the largest prime number within 50000. @@ -197,7 +197,7 @@ fn rand_remove_list(keys: Vec<&T>, num: usize) -> impl Iterator RocksTrieDBError { #[cfg(test)] mod tests { - use getrandom::getrandom; + use protocol::rand::random; use trie::DB; use super::*; fn rand_bytes(len: usize) -> Vec { - let mut ret = (0..len).map(|_| 0u8).collect::>(); - getrandom(&mut ret).unwrap(); - ret + (0..len).map(|_| random()).collect() } #[test] diff --git a/core/executor/src/adapter/wrapped_trie.rs b/core/executor/src/adapter/wrapped_trie.rs index cc7fc929b..1aec4279f 100644 --- a/core/executor/src/adapter/wrapped_trie.rs +++ b/core/executor/src/adapter/wrapped_trie.rs @@ -77,12 +77,10 @@ impl From for ProtocolError { mod tests { use super::*; use crate::adapter::RocksTrieDB; - use getrandom::getrandom; + use protocol::rand::random; fn rand_bytes(len: usize) -> Vec { - let mut ret = (0..len).map(|_| 0u8).collect::>(); - getrandom(&mut ret).unwrap(); - ret + (0..len).map(|_| random()).collect() } #[test] diff --git a/core/executor/src/debugger/crosschain.rs b/core/executor/src/debugger/crosschain.rs deleted file mode 100644 index 80ae48eb9..000000000 --- a/core/executor/src/debugger/crosschain.rs +++ /dev/null @@ -1,231 +0,0 @@ -use ckb_jsonrpc_types::BlockView; -use ckb_types::{h256, prelude::Pack}; -use ethers_contract::decode_logs; -use ethers_core::abi::{AbiDecode, AbiEncode, RawLog}; - -use protocol::types::{ - Address, Eip1559Transaction, TransactionAction, H160, H256, MAX_BLOCK_GAS_LIMIT, - MAX_PRIORITY_FEE_PER_GAS, U256, -}; -use protocol::{codec::hex_decode, tokio}; - -use core_cross_client::crosschain_abi as abi; -use core_cross_client::{build_axon_txs, monitor::search_tx}; - -use crate::debugger::{clear_data, mock_signed_tx, EvmDebugger, CROSSCHAIN_CONTRACT_ADDRESS}; - -const CKB_BLOCK_5910757: &str = "./src/debugger/block_5910757.json"; -const ACS_CODE_HASH: ckb_types::H256 = - h256!("0x97e6179be134d47ca10322a1534d8dcb65052de7e099b5556bea924137839bab"); -const REQUEST_CODE_HASH: ckb_types::H256 = - h256!("0xd8f9afaad8eb3e26a1ef2538bac91d68635502508358ae901941513bfe2edb1d"); - -fn load_block() -> BlockView { - let file = std::fs::File::options() - .read(true) - .open(CKB_BLOCK_5910757) - .unwrap(); - - serde_json::from_reader(file).unwrap() -} - -#[tokio::test(flavor = "multi_thread")] -async fn test_cross_from_ckb() { - use common_crypto::{Secp256k1RecoverablePrivateKey, ToPublicKey, UncompressedPublicKey}; - - let self_priv_key = - hex_decode("37aa0f893d05914a4def0460c0a984d3611546cfb26924d7a7ca6e0db9950a2d").unwrap(); - let priv_key = Secp256k1RecoverablePrivateKey::try_from(self_priv_key.as_ref()) - .expect("Invalid secp private key"); - let address = Address::from_pubkey_bytes(priv_key.pub_key().to_uncompressed_bytes()) - .unwrap() - .0; - let to_ckb_sender = - H160::from_slice(&hex_decode("0x421871e656E04c9A106A55CEd53Fc9A49560a424").unwrap()); - let to = H160::from_slice(&hex_decode("421871e656E04c9A106A55CEd53Fc9A49560a424").unwrap()); - - let mut debugger = EvmDebugger::new( - vec![address, to_ckb_sender], - 10000000000000000000u64.into(), - "./free-space/db2", - ); - debugger.init_genesis(); - - let ckb_txs = search_tx( - load_block().into(), - &(ACS_CODE_HASH.pack()), - &(REQUEST_CODE_HASH.pack()), - ); - let mut ckb_tx_hash = [0u8; 32]; - ckb_tx_hash.copy_from_slice(&ckb_txs[0].hash().raw_data()[..32]); - - let (_, stx) = build_axon_txs( - ckb_txs, - debugger.nonce(address), - &priv_key, - CROSSCHAIN_CONTRACT_ADDRESS, - ); - let resp = debugger.exec(1, vec![stx]); - - println!("{:?}", resp); - - let logs: Vec = decode_logs(&[resp.tx_resp[0] - .logs - .last() - .cloned() - .map(|l| RawLog::from((l.topics.clone(), l.data))) - .unwrap()]) - .unwrap(); - - assert_eq!(logs[0].records[0], abi::CkbtoAxonRecord { - to, - token_address: H160::default(), - s_udt_amount: U256::zero(), - ckb_amount: U256::from(450), - tx_hash: ckb_tx_hash, - }); - - let tx = mock_signed_tx( - build_change_limit_tx(debugger.nonce(address).as_u64()), - address, - ); - let _ = debugger.exec(2, vec![tx]); - - let to_ckb_tx = mock_signed_tx(build_axon_to_ckb_tx(1), to_ckb_sender); - - // let mut to_ckb_tx: SignedTransaction = - // UnverifiedTransaction::decode(hex_decode("02f9017105098459682f00845968397283013e6c94f67bc4e50d1df92b0e4c61794a4517af6a995cb280b90104b8f564f800000000000000000000000000000000000000000000000000000000000000600000000000000000000000004af5ec5e3d29d9ddd7f4bf91a022131c41b7235200000000000000000000000000000000000000000000000000000000000000050000000000000000000000000000000000000000000000000000000000000061636b7431717a646130637230386d38356863386a6c6e6670337a65723778756c656a79777434396b74327272307674687977616135307877737167797934736a6333616539647676683630306e366563716667326673717873346373646a77376500000000000000000000000000000000000000000000000000000000000000c080a06d992b3f958161bca24246caa99f3ac5a171e844a44e9feb8be96f847edbb5d7a05d5158ef716f6f4cdcb471eef6408dfd00e56167ff4809ca0abb424bb58bf90d").unwrap()) - // .unwrap() - // .try_into() - // .unwrap(); - let resp = debugger.exec(3, vec![to_ckb_tx]); - - let logs: Vec = decode_logs(&[resp.tx_resp[0] - .logs - .last() - .cloned() - .map(|l| RawLog::from((l.topics.clone(), l.data))) - .unwrap()]) - .unwrap(); - - println!("{:?}", logs); - - clear_data("./free-space"); -} - -// #[tokio::test(flavor = "multi_thread")] -// async fn test_crosschain() { -// use common_crypto::{Secp256k1RecoverablePrivateKey, ToPublicKey, -// UncompressedPublicKey}; - -// let self_priv_key = -// hex_decode(" -// 0x37aa0f893d05914a4def0460c0a984d3611546cfb26924d7a7ca6e0db9950a2d"). -// unwrap(); let priv_key = -// Secp256k1RecoverablePrivateKey::try_from(self_priv_key.as_ref()) -// .expect("Invalid secp private key"); -// let address = -// Address::from_pubkey_bytes(priv_key.pub_key().to_uncompressed_bytes()) -// .unwrap() -// .0; - -// let mut debugger = -// EvmDebugger::new(address, 10000000000000000000u64.into(), -// "./free-space/db2"); debugger.init_genesis(); - -// let to = -// H160::from_slice(&hex_decode("0x8ab0cf264df99d83525e9e11c7e4db01558ae1b1"). -// unwrap()); let stx = mock_signed_tx(build_ckb_to_axon_tx(to), address); -// let resp = debugger.exec(1, vec![stx]); - -// let logs: Vec = decode_logs( -// &resp.tx_resp[0] -// .logs -// .iter() -// .skip(1) -// .map(|l| RawLog::from((l.topics.clone(), l.data.clone()))) -// .collect::>(), -// ) -// .unwrap(); - -// println!("{:?}", resp); - -// assert_eq!( -// logs[0].records[0], -// ( -// to, -// H160::default(), -// U256::zero(), -// U256::from(100000u64), -// H256::default().0 -// ) -// ); - -// let priv_key = -// "37aa0f893d05914a4def0460c0a984d3611546cfb26924d7a7ca6e0db9950a2d"; -// let tx = mock_efficient_signed_tx(build_axon_to_ckb_tx(7), priv_key); -// let resp = debugger.exec(2, vec![tx]); - -// println!("{:?}", resp); - -// let logs: Vec = decode_logs( -// &resp.tx_resp[0] -// .logs -// .iter() -// .skip(2) -// .map(|l| RawLog::from((l.topics.clone(), l.data.clone()))) -// .collect::>(), -// ) -// .unwrap(); - -// println!("{:?}", logs); - -// let tx = mock_signed_tx(build_change_limit_tx(8), address); -// let resp = debugger.exec(3, vec![tx]); -// println!("{:?}", resp); - -// assert!(resp.tx_resp[0].exit_reason.is_succeed()); - -// clear_data("./free-space"); -// } - -fn build_ckb_to_axon_tx(to_address: H160) -> Eip1559Transaction { - let call_data = abi::CrossFromCKBCall { - records: vec![abi::CkbtoAxonRecord { - to: to_address, - token_address: H160::default(), - s_udt_amount: 0u64.into(), - ckb_amount: 100000u64.into(), - tx_hash: H256::default().0, - }], - nonce: U256::zero(), - }; - - build_eip1559_tx(6, AbiEncode::encode(call_data)) -} - -fn build_axon_to_ckb_tx(nonce: u64) -> Eip1559Transaction { - let data = hex_decode("0xb8f564f800000000000000000000000000000000000000000000000000000000000000600000000000000000000000004af5ec5e3d29d9ddd7f4bf91a022131c41b7235200000000000000000000000000000000000000000000000000000000000000050000000000000000000000000000000000000000000000000000000000000061636b7431717a646130637230386d38356863386a6c6e6670337a65723778756c656a79777434396b74327272307674687977616135307877737167797934736a6333616539647676683630306e366563716667326673717873346373646a77376500000000000000000000000000000000000000000000000000000000000000").unwrap(); - let call: abi::crosschainCalls = AbiDecode::decode(&data).unwrap(); - println!("axon to ckb call {:?}", call); - build_eip1559_tx(nonce, data) -} - -fn build_change_limit_tx(nonce: u64) -> Eip1559Transaction { - let data = hex_decode("0x3edfdbb00000000000000000000000004af5ec5e3d29d9ddd7f4bf91a022131c41b72352000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000152d02c7e14af6800000").unwrap(); - // let _call: abi::crosschainCalls = AbiDecode::decode(&data).unwrap(); - build_eip1559_tx(nonce, data) -} - -fn build_eip1559_tx(nonce: u64, data: Vec) -> Eip1559Transaction { - Eip1559Transaction { - nonce: nonce.into(), - max_priority_fee_per_gas: MAX_PRIORITY_FEE_PER_GAS.into(), - gas_price: U256::one(), - gas_limit: MAX_BLOCK_GAS_LIMIT.into(), - action: TransactionAction::Call(CROSSCHAIN_CONTRACT_ADDRESS), - value: U256::zero(), - data: data.into(), - access_list: vec![], - } -} diff --git a/core/executor/src/debugger/mod.rs b/core/executor/src/debugger/mod.rs index ef790f251..ff628e5b4 100644 --- a/core/executor/src/debugger/mod.rs +++ b/core/executor/src/debugger/mod.rs @@ -1,14 +1,12 @@ #![allow(dead_code)] mod create2; -mod crosschain; mod uniswap2; use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; use evm::tracing::{Event, EventListener}; -use getrandom::getrandom; use common_config_parser::parse_file; use common_crypto::{PrivateKey, Secp256k1RecoverablePrivateKey, Signature}; @@ -102,12 +100,12 @@ impl EvmDebugger { fn backend(&self, number: u64) -> AxonExecutorAdapter, RocksTrieDB> { let exec_ctx = ExecutorContext { block_number: number.into(), - block_hash: rand_hash(), - block_coinbase: rand_hash().into(), + block_hash: H256::random(), + block_coinbase: H160::random(), block_timestamp: time_now().into(), chain_id: 5u64.into(), difficulty: U256::one(), - origin: rand_hash().into(), + origin: H160::random(), gas_price: 1u64.into(), block_gas_limit: 4294967295000u64.into(), block_base_fee_per_gas: 1337u64.into(), @@ -180,12 +178,6 @@ pub fn clear_data(db_path: &str) { std::fs::remove_dir_all(db_path).unwrap() } -fn rand_hash() -> Hash { - let mut data = [0u8; 128]; - getrandom(&mut data).unwrap(); - Hasher::digest(data) -} - fn time_now() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) diff --git a/core/executor/src/precompiles/tests.rs b/core/executor/src/precompiles/tests.rs index 75f4f05d4..4dcee19e2 100644 --- a/core/executor/src/precompiles/tests.rs +++ b/core/executor/src/precompiles/tests.rs @@ -1,8 +1,7 @@ use evm::Context; -use rand::random; use sha2::Digest; -use protocol::{codec::hex_decode, types::U256}; +use protocol::{codec::hex_decode, rand::random, types::U256}; use crate::precompiles::{ Blake2F, EcAdd, EcMul, EcPairing, EcRecover, Identity, ModExp, PrecompileContract, Ripemd160, diff --git a/core/executor/src/system_contract/ckb_light_client/abi/ckb_light_client_abi.json b/core/executor/src/system_contract/ckb_light_client/abi/ckb_light_client_abi.json index d7b185ea7..b5acbd078 100644 --- a/core/executor/src/system_contract/ckb_light_client/abi/ckb_light_client_abi.json +++ b/core/executor/src/system_contract/ckb_light_client/abi/ckb_light_client_abi.json @@ -3,7 +3,7 @@ "inputs": [ { "internalType": "bytes32[]", - "name": "blockHashs", + "name": "blockHashes", "type": "bytes32[]" } ], diff --git a/core/executor/src/system_contract/ckb_light_client/abi/ckb_light_client_abi.rs b/core/executor/src/system_contract/ckb_light_client/abi/ckb_light_client_abi.rs index bb098e50f..9381ca142 100644 --- a/core/executor/src/system_contract/ckb_light_client/abi/ckb_light_client_abi.rs +++ b/core/executor/src/system_contract/ckb_light_client/abi/ckb_light_client_abi.rs @@ -1,131 +1,143 @@ -pub use ckb_light_client::*; -#[allow(clippy::too_many_arguments, non_camel_case_types)] -pub mod ckb_light_client { - #![allow(clippy::enum_variant_names)] - #![allow(dead_code)] - #![allow(clippy::type_complexity)] - #![allow(unused_imports)] - use ethers::contract::{ - builders::{ContractCall, Event}, - Contract, Lazy, - }; - use ethers::core::{ - abi::{Abi, Detokenize, InvalidOutputType, Token, Tokenizable}, - types::*, - }; - use ethers::providers::Middleware; - #[doc = "CkbLightClient was auto-generated with ethers-rs Abigen. More information at: https://github.com/gakonst/ethers-rs"] - use std::sync::Arc; - # [rustfmt :: skip] const __ABI : & str = "[\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32[]\",\n \"name\": \"blockHashs\",\n \"type\": \"bytes32[]\"\n }\n ],\n \"name\": \"rollback\",\n \"outputs\": [],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"allowRead\",\n \"type\": \"bool\"\n }\n ],\n \"name\": \"setState\",\n \"outputs\": [],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"components\": [\n {\n \"internalType\": \"uint32\",\n \"name\": \"version\",\n \"type\": \"uint32\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"compactTarget\",\n \"type\": \"uint32\"\n },\n {\n \"internalType\": \"uint64\",\n \"name\": \"timestamp\",\n \"type\": \"uint64\"\n },\n {\n \"internalType\": \"uint64\",\n \"name\": \"number\",\n \"type\": \"uint64\"\n },\n {\n \"internalType\": \"uint64\",\n \"name\": \"epoch\",\n \"type\": \"uint64\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"parentHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"transactionsRoot\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"proposalsHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"unclesHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"dao\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"uint128\",\n \"name\": \"nonce\",\n \"type\": \"uint128\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"blockHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"internalType\": \"struct CkbType.Header[]\",\n \"name\": \"headers\",\n \"type\": \"tuple[]\"\n }\n ],\n \"name\": \"update\",\n \"outputs\": [],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n }\n]" ; - #[doc = r" The parsed JSON-ABI of the contract."] - pub static CKBLIGHTCLIENT_ABI: ethers::contract::Lazy = - ethers::contract::Lazy::new(|| { - ethers::core::utils::__serde_json::from_str(__ABI).expect("invalid abi") +pub use ckb_light_client_contract::*; +/// This module was auto-generated with ethers-rs Abigen. +/// More information at: +#[allow( + clippy::enum_variant_names, + clippy::too_many_arguments, + clippy::upper_case_acronyms, + clippy::type_complexity, + dead_code, + non_camel_case_types +)] +pub mod ckb_light_client_contract { + #[rustfmt::skip] + const __ABI: &str = "[\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes32[]\",\n \"name\": \"blockHashes\",\n \"type\": \"bytes32[]\"\n }\n ],\n \"name\": \"rollback\",\n \"outputs\": [],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"allowRead\",\n \"type\": \"bool\"\n }\n ],\n \"name\": \"setState\",\n \"outputs\": [],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"components\": [\n {\n \"internalType\": \"uint32\",\n \"name\": \"version\",\n \"type\": \"uint32\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"compactTarget\",\n \"type\": \"uint32\"\n },\n {\n \"internalType\": \"uint64\",\n \"name\": \"timestamp\",\n \"type\": \"uint64\"\n },\n {\n \"internalType\": \"uint64\",\n \"name\": \"number\",\n \"type\": \"uint64\"\n },\n {\n \"internalType\": \"uint64\",\n \"name\": \"epoch\",\n \"type\": \"uint64\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"parentHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"transactionsRoot\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"proposalsHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"unclesHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"dao\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"uint128\",\n \"name\": \"nonce\",\n \"type\": \"uint128\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"blockHash\",\n \"type\": \"bytes32\"\n }\n ],\n \"internalType\": \"struct CkbType.Header[]\",\n \"name\": \"headers\",\n \"type\": \"tuple[]\"\n }\n ],\n \"name\": \"update\",\n \"outputs\": [],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n }\n]\n"; + /// The parsed JSON ABI of the contract. + pub static CKBLIGHTCLIENTCONTRACT_ABI: ::ethers::contract::Lazy<::ethers::core::abi::Abi> = + ::ethers::contract::Lazy::new(|| { + ::ethers::core::utils::__serde_json::from_str(__ABI).expect("ABI is always valid") }); - pub struct CkbLightClient(ethers::contract::Contract); - impl Clone for CkbLightClient { + pub struct CkbLightClientContract(::ethers::contract::Contract); + impl ::core::clone::Clone for CkbLightClientContract { fn clone(&self) -> Self { - CkbLightClient(self.0.clone()) + Self(::core::clone::Clone::clone(&self.0)) } } - impl std::ops::Deref for CkbLightClient { - type Target = ethers::contract::Contract; + impl ::core::ops::Deref for CkbLightClientContract { + type Target = ::ethers::contract::Contract; fn deref(&self) -> &Self::Target { &self.0 } } - impl std::fmt::Debug for CkbLightClient { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - f.debug_tuple(stringify!(CkbLightClient)) + impl ::core::ops::DerefMut for CkbLightClientContract { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } + } + impl ::core::fmt::Debug for CkbLightClientContract { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_tuple(stringify!(CkbLightClientContract)) .field(&self.address()) .finish() } } - impl CkbLightClient { - #[doc = r" Creates a new contract instance with the specified `ethers`"] - #[doc = r" client at the given `Address`. The contract derefs to a `ethers::Contract`"] - #[doc = r" object"] - pub fn new>( + impl CkbLightClientContract { + /// Creates a new contract instance with the specified `ethers` client + /// at `address`. The contract derefs to a `ethers::Contract` + /// object. + pub fn new>( address: T, client: ::std::sync::Arc, ) -> Self { - ethers::contract::Contract::new(address.into(), CKBLIGHTCLIENT_ABI.clone(), client) - .into() + Self(::ethers::contract::Contract::new( + address.into(), + CKBLIGHTCLIENTCONTRACT_ABI.clone(), + client, + )) } - #[doc = "Calls the contract's `rollback` (0xd32a2285) function"] + /// Calls the contract's `rollback` (0xd32a2285) function pub fn rollback( &self, - block_hashs: ::std::vec::Vec<[u8; 32]>, - ) -> ethers::contract::builders::ContractCall { + block_hashes: ::std::vec::Vec<[u8; 32]>, + ) -> ::ethers::contract::builders::ContractCall { self.0 - .method_hash([211, 42, 34, 133], block_hashs) + .method_hash([211, 42, 34, 133], block_hashes) .expect("method not found (this should never happen)") } - #[doc = "Calls the contract's `setState` (0xac9f0222) function"] + /// Calls the contract's `setState` (0xac9f0222) function pub fn set_state( &self, allow_read: bool, - ) -> ethers::contract::builders::ContractCall { + ) -> ::ethers::contract::builders::ContractCall { self.0 .method_hash([172, 159, 2, 34], allow_read) .expect("method not found (this should never happen)") } - #[doc = "Calls the contract's `update` (0x2b196cf3) function"] + /// Calls the contract's `update` (0x2b196cf3) function pub fn update( &self, headers: ::std::vec::Vec
, - ) -> ethers::contract::builders::ContractCall { + ) -> ::ethers::contract::builders::ContractCall { self.0 .method_hash([43, 25, 108, 243], headers) .expect("method not found (this should never happen)") } } - impl From> for CkbLightClient { - fn from(contract: ethers::contract::Contract) -> Self { - Self(contract) + impl From<::ethers::contract::Contract> + for CkbLightClientContract + { + fn from(contract: ::ethers::contract::Contract) -> Self { + Self::new(contract.address(), contract.client()) } } - #[doc = "Container type for all input parameters for the `rollback` function with signature `rollback(bytes32[])` and selector `[211, 42, 34, 133]`"] + /// Container type for all input parameters for the `rollback` function with + /// signature `rollback(bytes32[])` and selector `0xd32a2285` #[derive( Clone, + ::ethers::contract::EthCall, + ::ethers::contract::EthDisplay, + Default, Debug, - Eq, PartialEq, - ethers::contract::EthCall, - ethers::contract::EthDisplay, - Default, + Eq, + Hash, )] #[ethcall(name = "rollback", abi = "rollback(bytes32[])")] pub struct RollbackCall { - pub block_hashs: ::std::vec::Vec<[u8; 32]>, + pub block_hashes: ::std::vec::Vec<[u8; 32]>, } - #[doc = "Container type for all input parameters for the `setState` function with signature `setState(bool)` and selector `[172, 159, 2, 34]`"] + /// Container type for all input parameters for the `setState` function with + /// signature `setState(bool)` and selector `0xac9f0222` #[derive( Clone, + ::ethers::contract::EthCall, + ::ethers::contract::EthDisplay, + Default, Debug, - Eq, PartialEq, - ethers::contract::EthCall, - ethers::contract::EthDisplay, - Default, + Eq, + Hash, )] #[ethcall(name = "setState", abi = "setState(bool)")] pub struct SetStateCall { pub allow_read: bool, } - #[doc = "Container type for all input parameters for the `update` function with signature `update((uint32,uint32,uint64,uint64,uint64,bytes32,bytes32,bytes32,bytes32,bytes32,uint128,bytes32)[])` and selector `[43, 25, 108, 243]`"] + /// Container type for all input parameters for the `update` function with + /// signature `update((uint32,uint32,uint64,uint64,uint64,bytes32,bytes32, + /// bytes32,bytes32,bytes32,uint128,bytes32)[])` and selector `0x2b196cf3` #[derive( Clone, + ::ethers::contract::EthCall, + ::ethers::contract::EthDisplay, + Default, Debug, - Eq, PartialEq, - ethers::contract::EthCall, - ethers::contract::EthDisplay, - Default, + Eq, + Hash, )] #[ethcall( name = "update", @@ -134,75 +146,74 @@ pub mod ckb_light_client { pub struct UpdateCall { pub headers: ::std::vec::Vec
, } - #[derive(Debug, Clone, PartialEq, Eq, ethers::contract::EthAbiType)] - pub enum CkbLightClientCalls { + /// Container type for all of the contract's call + #[derive(Clone, ::ethers::contract::EthAbiType, Debug, PartialEq, Eq, Hash)] + pub enum CkbLightClientContractCalls { Rollback(RollbackCall), SetState(SetStateCall), Update(UpdateCall), } - impl ethers::core::abi::AbiDecode for CkbLightClientCalls { + impl ::ethers::core::abi::AbiDecode for CkbLightClientContractCalls { fn decode( data: impl AsRef<[u8]>, - ) -> ::std::result::Result { - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(CkbLightClientCalls::Rollback(decoded)); + ) -> ::core::result::Result { + let data = data.as_ref(); + if let Ok(decoded) = ::decode(data) { + return Ok(Self::Rollback(decoded)); } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(CkbLightClientCalls::SetState(decoded)); + if let Ok(decoded) = ::decode(data) { + return Ok(Self::SetState(decoded)); } - if let Ok(decoded) = ::decode(data.as_ref()) - { - return Ok(CkbLightClientCalls::Update(decoded)); + if let Ok(decoded) = ::decode(data) { + return Ok(Self::Update(decoded)); } - Err(ethers::core::abi::Error::InvalidData.into()) + Err(::ethers::core::abi::Error::InvalidData.into()) } } - impl ethers::core::abi::AbiEncode for CkbLightClientCalls { + impl ::ethers::core::abi::AbiEncode for CkbLightClientContractCalls { fn encode(self) -> Vec { match self { - CkbLightClientCalls::Rollback(element) => element.encode(), - CkbLightClientCalls::SetState(element) => element.encode(), - CkbLightClientCalls::Update(element) => element.encode(), + Self::Rollback(element) => ::ethers::core::abi::AbiEncode::encode(element), + Self::SetState(element) => ::ethers::core::abi::AbiEncode::encode(element), + Self::Update(element) => ::ethers::core::abi::AbiEncode::encode(element), } } } - impl ::std::fmt::Display for CkbLightClientCalls { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + impl ::core::fmt::Display for CkbLightClientContractCalls { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { - CkbLightClientCalls::Rollback(element) => element.fmt(f), - CkbLightClientCalls::SetState(element) => element.fmt(f), - CkbLightClientCalls::Update(element) => element.fmt(f), + Self::Rollback(element) => ::core::fmt::Display::fmt(element, f), + Self::SetState(element) => ::core::fmt::Display::fmt(element, f), + Self::Update(element) => ::core::fmt::Display::fmt(element, f), } } } - impl ::std::convert::From for CkbLightClientCalls { - fn from(var: RollbackCall) -> Self { - CkbLightClientCalls::Rollback(var) + impl ::core::convert::From for CkbLightClientContractCalls { + fn from(value: RollbackCall) -> Self { + Self::Rollback(value) } } - impl ::std::convert::From for CkbLightClientCalls { - fn from(var: SetStateCall) -> Self { - CkbLightClientCalls::SetState(var) + impl ::core::convert::From for CkbLightClientContractCalls { + fn from(value: SetStateCall) -> Self { + Self::SetState(value) } } - impl ::std::convert::From for CkbLightClientCalls { - fn from(var: UpdateCall) -> Self { - CkbLightClientCalls::Update(var) + impl ::core::convert::From for CkbLightClientContractCalls { + fn from(value: UpdateCall) -> Self { + Self::Update(value) } } - #[doc = "`Header(uint32,uint32,uint64,uint64,uint64,bytes32,bytes32,bytes32,bytes32,bytes32,uint128,bytes32)`"] + /// `Header(uint32,uint32,uint64,uint64,uint64,bytes32,bytes32,bytes32, + /// bytes32,bytes32,uint128,bytes32)` #[derive( Clone, - Debug, + ::ethers::contract::EthAbiType, + ::ethers::contract::EthAbiCodec, Default, - Eq, + Debug, PartialEq, - ethers::contract::EthAbiType, - ethers::contract::EthAbiCodec, + Eq, + Hash, )] pub struct Header { pub version: u32, diff --git a/core/executor/src/system_contract/ckb_light_client/mod.rs b/core/executor/src/system_contract/ckb_light_client/mod.rs index 0fccc48e1..e102dc3cb 100644 --- a/core/executor/src/system_contract/ckb_light_client/mod.rs +++ b/core/executor/src/system_contract/ckb_light_client/mod.rs @@ -36,23 +36,23 @@ impl SystemContract for CkbLightClientContract { ); let call_abi = exec_try!( - ckb_light_client_abi::CkbLightClientCalls::decode(tx_data), + ckb_light_client_abi::CkbLightClientContractCalls::decode(tx_data), gas_limit, "[ckb light client] invalid tx data" ); match call_abi { - ckb_light_client_abi::CkbLightClientCalls::SetState(data) => { + ckb_light_client_abi::CkbLightClientContractCalls::SetState(data) => { ALLOW_READ.store(data.allow_read, Ordering::Relaxed); } - ckb_light_client_abi::CkbLightClientCalls::Update(data) => { + ckb_light_client_abi::CkbLightClientContractCalls::Update(data) => { exec_try!( store.update(data), gas_limit, "[ckb light client] update error:" ); } - ckb_light_client_abi::CkbLightClientCalls::Rollback(data) => { + ckb_light_client_abi::CkbLightClientContractCalls::Rollback(data) => { exec_try!( store.rollback(data), gas_limit, diff --git a/core/executor/src/system_contract/ckb_light_client/store.rs b/core/executor/src/system_contract/ckb_light_client/store.rs index 7e090e20b..b2c120c15 100644 --- a/core/executor/src/system_contract/ckb_light_client/store.rs +++ b/core/executor/src/system_contract/ckb_light_client/store.rs @@ -45,7 +45,7 @@ impl CkbLightClientStore { } pub fn rollback(&mut self, data: ckb_light_client_abi::RollbackCall) -> ProtocolResult<()> { - for block_hash in data.block_hashs { + for block_hash in data.block_hashes { self.remove_header(&block_hash)?; } diff --git a/core/executor/src/system_contract/image_cell/abi/image_cell_abi.rs b/core/executor/src/system_contract/image_cell/abi/image_cell_abi.rs index 5cd933631..b8220f5c7 100644 --- a/core/executor/src/system_contract/image_cell/abi/image_cell_abi.rs +++ b/core/executor/src/system_contract/image_cell/abi/image_cell_abi.rs @@ -1,105 +1,114 @@ -pub use image_cell::*; -#[allow(clippy::too_many_arguments, non_camel_case_types)] -pub mod image_cell { - #![allow(clippy::enum_variant_names)] - #![allow(dead_code)] - #![allow(clippy::type_complexity)] - #![allow(unused_imports)] - use ethers::contract::{ - builders::{ContractCall, Event}, - Contract, Lazy, - }; - use ethers::core::{ - abi::{Abi, Detokenize, InvalidOutputType, Token, Tokenizable}, - types::*, - }; - use ethers::providers::Middleware; - #[doc = "ImageCell was auto-generated with ethers-rs Abigen. More information at: https://github.com/gakonst/ethers-rs"] - use std::sync::Arc; - # [rustfmt::skip] const __ABI: & str = "[\n {\n \"inputs\": [\n {\n \"components\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"index\",\n \"type\": \"uint32\"\n }\n ],\n \"internalType\": \"struct CkbType.OutPoint[]\",\n \"name\": \"inputs\",\n \"type\": \"tuple[]\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"index\",\n \"type\": \"uint32\"\n }\n ],\n \"internalType\": \"struct CkbType.OutPoint[]\",\n \"name\": \"outputs\",\n \"type\": \"tuple[]\"\n }\n ],\n \"name\": \"rollback\",\n \"outputs\": [],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"allowRead\",\n \"type\": \"bool\"\n }\n ],\n \"name\": \"setState\",\n \"outputs\": [],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint64\",\n \"name\": \"blockNumber\",\n \"type\": \"uint64\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"index\",\n \"type\": \"uint32\"\n }\n ],\n \"internalType\": \"struct CkbType.OutPoint[]\",\n \"name\": \"inputs\",\n \"type\": \"tuple[]\"\n },\n {\n \"components\": [\n {\n \"components\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"index\",\n \"type\": \"uint32\"\n }\n ],\n \"internalType\": \"struct CkbType.OutPoint\",\n \"name\": \"outPoint\",\n \"type\": \"tuple\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"uint64\",\n \"name\": \"capacity\",\n \"type\": \"uint64\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"codeHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"enum CkbType.ScriptHashType\",\n \"name\": \"hashType\",\n \"type\": \"uint8\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"args\",\n \"type\": \"bytes\"\n }\n ],\n \"internalType\": \"struct CkbType.Script\",\n \"name\": \"lock\",\n \"type\": \"tuple\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"codeHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"enum CkbType.ScriptHashType\",\n \"name\": \"hashType\",\n \"type\": \"uint8\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"args\",\n \"type\": \"bytes\"\n }\n ],\n \"internalType\": \"struct CkbType.Script[]\",\n \"name\": \"type_\",\n \"type\": \"tuple[]\"\n }\n ],\n \"internalType\": \"struct CkbType.CellOutput\",\n \"name\": \"output\",\n \"type\": \"tuple\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"internalType\": \"struct CkbType.CellInfo[]\",\n \"name\": \"outputs\",\n \"type\": \"tuple[]\"\n }\n ],\n \"name\": \"update\",\n \"outputs\": [],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n }\n]\n" ; - #[doc = r" The parsed JSON-ABI of the contract."] - pub static IMAGECELL_ABI: ethers::contract::Lazy = - ethers::contract::Lazy::new(|| { - ethers::core::utils::__serde_json::from_str(__ABI).expect("invalid abi") +pub use image_cell_contract::*; +/// This module was auto-generated with ethers-rs Abigen. +/// More information at: +#[allow( + clippy::enum_variant_names, + clippy::too_many_arguments, + clippy::upper_case_acronyms, + clippy::type_complexity, + dead_code, + non_camel_case_types +)] +pub mod image_cell_contract { + #[rustfmt::skip] + const __ABI: &str = "[\n {\n \"inputs\": [\n {\n \"components\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"index\",\n \"type\": \"uint32\"\n }\n ],\n \"internalType\": \"struct CkbType.OutPoint[]\",\n \"name\": \"inputs\",\n \"type\": \"tuple[]\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"index\",\n \"type\": \"uint32\"\n }\n ],\n \"internalType\": \"struct CkbType.OutPoint[]\",\n \"name\": \"outputs\",\n \"type\": \"tuple[]\"\n }\n ],\n \"name\": \"rollback\",\n \"outputs\": [],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"allowRead\",\n \"type\": \"bool\"\n }\n ],\n \"name\": \"setState\",\n \"outputs\": [],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint64\",\n \"name\": \"blockNumber\",\n \"type\": \"uint64\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"index\",\n \"type\": \"uint32\"\n }\n ],\n \"internalType\": \"struct CkbType.OutPoint[]\",\n \"name\": \"inputs\",\n \"type\": \"tuple[]\"\n },\n {\n \"components\": [\n {\n \"components\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"txHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"uint32\",\n \"name\": \"index\",\n \"type\": \"uint32\"\n }\n ],\n \"internalType\": \"struct CkbType.OutPoint\",\n \"name\": \"outPoint\",\n \"type\": \"tuple\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"uint64\",\n \"name\": \"capacity\",\n \"type\": \"uint64\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"codeHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"enum CkbType.ScriptHashType\",\n \"name\": \"hashType\",\n \"type\": \"uint8\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"args\",\n \"type\": \"bytes\"\n }\n ],\n \"internalType\": \"struct CkbType.Script\",\n \"name\": \"lock\",\n \"type\": \"tuple\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"codeHash\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"enum CkbType.ScriptHashType\",\n \"name\": \"hashType\",\n \"type\": \"uint8\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"args\",\n \"type\": \"bytes\"\n }\n ],\n \"internalType\": \"struct CkbType.Script[]\",\n \"name\": \"type_\",\n \"type\": \"tuple[]\"\n }\n ],\n \"internalType\": \"struct CkbType.CellOutput\",\n \"name\": \"output\",\n \"type\": \"tuple\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"internalType\": \"struct CkbType.CellInfo[]\",\n \"name\": \"outputs\",\n \"type\": \"tuple[]\"\n }\n ],\n \"name\": \"update\",\n \"outputs\": [],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n }\n]\n"; + /// The parsed JSON ABI of the contract. + pub static IMAGECELLCONTRACT_ABI: ::ethers::contract::Lazy<::ethers::core::abi::Abi> = + ::ethers::contract::Lazy::new(|| { + ::ethers::core::utils::__serde_json::from_str(__ABI).expect("ABI is always valid") }); - pub struct ImageCell(ethers::contract::Contract); - impl Clone for ImageCell { + pub struct ImageCellContract(::ethers::contract::Contract); + impl ::core::clone::Clone for ImageCellContract { fn clone(&self) -> Self { - ImageCell(self.0.clone()) + Self(::core::clone::Clone::clone(&self.0)) } } - impl std::ops::Deref for ImageCell { - type Target = ethers::contract::Contract; + impl ::core::ops::Deref for ImageCellContract { + type Target = ::ethers::contract::Contract; fn deref(&self) -> &Self::Target { &self.0 } } - impl std::fmt::Debug for ImageCell { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - f.debug_tuple(stringify!(ImageCell)) + impl ::core::ops::DerefMut for ImageCellContract { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } + } + impl ::core::fmt::Debug for ImageCellContract { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_tuple(stringify!(ImageCellContract)) .field(&self.address()) .finish() } } - impl ImageCell { - #[doc = r" Creates a new contract instance with the specified `ethers`"] - #[doc = r" client at the given `Address`. The contract derefs to a `ethers::Contract`"] - #[doc = r" object"] - pub fn new>( + impl ImageCellContract { + /// Creates a new contract instance with the specified `ethers` client + /// at `address`. The contract derefs to a `ethers::Contract` + /// object. + pub fn new>( address: T, client: ::std::sync::Arc, ) -> Self { - ethers::contract::Contract::new(address.into(), IMAGECELL_ABI.clone(), client).into() + Self(::ethers::contract::Contract::new( + address.into(), + IMAGECELLCONTRACT_ABI.clone(), + client, + )) } - #[doc = "Calls the contract's `rollback` (0xec5d646a) function"] + /// Calls the contract's `rollback` (0xec5d646a) function pub fn rollback( &self, inputs: ::std::vec::Vec, outputs: ::std::vec::Vec, - ) -> ethers::contract::builders::ContractCall { + ) -> ::ethers::contract::builders::ContractCall { self.0 .method_hash([236, 93, 100, 106], (inputs, outputs)) .expect("method not found (this should never happen)") } - #[doc = "Calls the contract's `setState` (0xac9f0222) function"] + /// Calls the contract's `setState` (0xac9f0222) function pub fn set_state( &self, allow_read: bool, - ) -> ethers::contract::builders::ContractCall { + ) -> ::ethers::contract::builders::ContractCall { self.0 .method_hash([172, 159, 2, 34], allow_read) .expect("method not found (this should never happen)") } - #[doc = "Calls the contract's `update` (0x4d98c254) function"] + /// Calls the contract's `update` (0x4d98c254) function pub fn update( &self, block_number: u64, inputs: ::std::vec::Vec, outputs: ::std::vec::Vec, - ) -> ethers::contract::builders::ContractCall { + ) -> ::ethers::contract::builders::ContractCall { self.0 .method_hash([77, 152, 194, 84], (block_number, inputs, outputs)) .expect("method not found (this should never happen)") } } - impl From> for ImageCell { - fn from(contract: ethers::contract::Contract) -> Self { - Self(contract) + impl From<::ethers::contract::Contract> + for ImageCellContract + { + fn from(contract: ::ethers::contract::Contract) -> Self { + Self::new(contract.address(), contract.client()) } } - #[doc = "Container type for all input parameters for the `rollback` function with signature `rollback((bytes32,uint32)[],(bytes32,uint32)[])` and selector `[236, 93, 100, 106]`"] + /// Container type for all input parameters for the `rollback` function with + /// signature `rollback((bytes32,uint32)[],(bytes32,uint32)[])` and selector + /// `0xec5d646a` #[derive( Clone, + ::ethers::contract::EthCall, + ::ethers::contract::EthDisplay, + Default, Debug, - Eq, PartialEq, - ethers::contract::EthCall, - ethers::contract::EthDisplay, - Default, + Eq, + Hash, )] #[ethcall( name = "rollback", @@ -109,29 +118,35 @@ pub mod image_cell { pub inputs: ::std::vec::Vec, pub outputs: ::std::vec::Vec, } - #[doc = "Container type for all input parameters for the `setState` function with signature `setState(bool)` and selector `[172, 159, 2, 34]`"] + /// Container type for all input parameters for the `setState` function with + /// signature `setState(bool)` and selector `0xac9f0222` #[derive( Clone, + ::ethers::contract::EthCall, + ::ethers::contract::EthDisplay, + Default, Debug, - Eq, PartialEq, - ethers::contract::EthCall, - ethers::contract::EthDisplay, - Default, + Eq, + Hash, )] #[ethcall(name = "setState", abi = "setState(bool)")] pub struct SetStateCall { pub allow_read: bool, } - #[doc = "Container type for all input parameters for the `update` function with signature `update(uint64,(bytes32,uint32)[],((bytes32,uint32),(uint64,(bytes32,uint8,bytes),(bytes32,uint8,bytes)[]),bytes)[])` and selector `[77, 152, 194, 84]`"] + /// Container type for all input parameters for the `update` function with + /// signature `update(uint64,(bytes32,uint32)[],((bytes32,uint32),(uint64, + /// (bytes32,uint8,bytes),(bytes32,uint8,bytes)[]),bytes)[])` and selector + /// `0x4d98c254` #[derive( Clone, + ::ethers::contract::EthCall, + ::ethers::contract::EthDisplay, + Default, Debug, - Eq, PartialEq, - ethers::contract::EthCall, - ethers::contract::EthDisplay, - Default, + Eq, + Hash, )] #[ethcall( name = "update", @@ -142,123 +157,125 @@ pub mod image_cell { pub inputs: ::std::vec::Vec, pub outputs: ::std::vec::Vec, } - #[derive(Debug, Clone, PartialEq, Eq, ethers::contract::EthAbiType)] - pub enum ImageCellCalls { + /// Container type for all of the contract's call + #[derive(Clone, ::ethers::contract::EthAbiType, Debug, PartialEq, Eq, Hash)] + pub enum ImageCellContractCalls { Rollback(RollbackCall), SetState(SetStateCall), Update(UpdateCall), } - impl ethers::core::abi::AbiDecode for ImageCellCalls { + impl ::ethers::core::abi::AbiDecode for ImageCellContractCalls { fn decode( data: impl AsRef<[u8]>, - ) -> ::std::result::Result { - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(ImageCellCalls::Rollback(decoded)); + ) -> ::core::result::Result { + let data = data.as_ref(); + if let Ok(decoded) = ::decode(data) { + return Ok(Self::Rollback(decoded)); } - if let Ok(decoded) = - ::decode(data.as_ref()) - { - return Ok(ImageCellCalls::SetState(decoded)); + if let Ok(decoded) = ::decode(data) { + return Ok(Self::SetState(decoded)); } - if let Ok(decoded) = ::decode(data.as_ref()) - { - return Ok(ImageCellCalls::Update(decoded)); + if let Ok(decoded) = ::decode(data) { + return Ok(Self::Update(decoded)); } - Err(ethers::core::abi::Error::InvalidData.into()) + Err(::ethers::core::abi::Error::InvalidData.into()) } } - impl ethers::core::abi::AbiEncode for ImageCellCalls { + impl ::ethers::core::abi::AbiEncode for ImageCellContractCalls { fn encode(self) -> Vec { match self { - ImageCellCalls::Rollback(element) => element.encode(), - ImageCellCalls::SetState(element) => element.encode(), - ImageCellCalls::Update(element) => element.encode(), + Self::Rollback(element) => ::ethers::core::abi::AbiEncode::encode(element), + Self::SetState(element) => ::ethers::core::abi::AbiEncode::encode(element), + Self::Update(element) => ::ethers::core::abi::AbiEncode::encode(element), } } } - impl ::std::fmt::Display for ImageCellCalls { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + impl ::core::fmt::Display for ImageCellContractCalls { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { match self { - ImageCellCalls::Rollback(element) => element.fmt(f), - ImageCellCalls::SetState(element) => element.fmt(f), - ImageCellCalls::Update(element) => element.fmt(f), + Self::Rollback(element) => ::core::fmt::Display::fmt(element, f), + Self::SetState(element) => ::core::fmt::Display::fmt(element, f), + Self::Update(element) => ::core::fmt::Display::fmt(element, f), } } } - impl ::std::convert::From for ImageCellCalls { - fn from(var: RollbackCall) -> Self { - ImageCellCalls::Rollback(var) + impl ::core::convert::From for ImageCellContractCalls { + fn from(value: RollbackCall) -> Self { + Self::Rollback(value) } } - impl ::std::convert::From for ImageCellCalls { - fn from(var: SetStateCall) -> Self { - ImageCellCalls::SetState(var) + impl ::core::convert::From for ImageCellContractCalls { + fn from(value: SetStateCall) -> Self { + Self::SetState(value) } } - impl ::std::convert::From for ImageCellCalls { - fn from(var: UpdateCall) -> Self { - ImageCellCalls::Update(var) + impl ::core::convert::From for ImageCellContractCalls { + fn from(value: UpdateCall) -> Self { + Self::Update(value) } } - #[doc = "`CellInfo((bytes32,uint32),(uint64,(bytes32,uint8,bytes),(bytes32,uint8,bytes)[]),bytes)`"] + /// `CellInfo((bytes32,uint32),(uint64,(bytes32,uint8,bytes),(bytes32,uint8, + /// bytes)[]),bytes)` #[derive( Clone, - Debug, + ::ethers::contract::EthAbiType, + ::ethers::contract::EthAbiCodec, Default, - Eq, + Debug, PartialEq, - ethers::contract::EthAbiType, - ethers::contract::EthAbiCodec, + Eq, + Hash, )] pub struct CellInfo { pub out_point: OutPoint, pub output: CellOutput, - pub data: ethers::core::types::Bytes, + pub data: ::ethers::core::types::Bytes, } - #[doc = "`CellOutput(uint64,(bytes32,uint8,bytes),(bytes32,uint8,bytes)[])`"] + /// `CellOutput(uint64,(bytes32,uint8,bytes),(bytes32,uint8,bytes)[])` #[derive( Clone, - Debug, + ::ethers::contract::EthAbiType, + ::ethers::contract::EthAbiCodec, Default, - Eq, + Debug, PartialEq, - ethers::contract::EthAbiType, - ethers::contract::EthAbiCodec, + Eq, + Hash, )] pub struct CellOutput { pub capacity: u64, pub lock: Script, pub type_: ::std::vec::Vec