diff --git a/.gitignore b/.gitignore index a3d0a3c9b..a3d3dc5e0 100644 --- a/.gitignore +++ b/.gitignore @@ -38,7 +38,6 @@ node_modules # Build artifacts out/ -parity-clib-examples/cpp/build/ .vscode rls/ diff --git a/Cargo.lock b/Cargo.lock index 71f0cd7d4..7f5363db2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -94,11 +94,6 @@ dependencies = [ "nodrop 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "ascii" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "assert_matches" version = "1.3.0" @@ -316,11 +311,6 @@ name = "cc" version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "cesu8" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "cfg-if" version = "0.1.10" @@ -396,18 +386,6 @@ dependencies = [ "cc 1.0.47 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "combine" -version = "3.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "ascii 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)", - "byteorder 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)", - "either 1.5.3 (registry+https://github.com/rust-lang/crates.io-index)", - "memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "unreachable 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "common-types" version = "0.1.0" @@ -1988,24 +1966,6 @@ dependencies = [ "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "jni" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cesu8 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "combine 3.8.1 (registry+https://github.com/rust-lang/crates.io-index)", - "error-chain 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)", - "jni-sys 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", - "walkdir 2.2.9 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "jni-sys" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "journaldb" version = "0.2.0" @@ -2646,18 +2606,6 @@ name = "parity-bytes" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "parity-clib" -version = "1.12.0" -dependencies = [ - "futures 0.1.29 (registry+https://github.com/rust-lang/crates.io-index)", - "jni 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "panic_hook 0.1.0", - "parity-ethereum 2.5.13", - "tokio 0.1.22 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-current-thread 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "parity-crypto" version = "0.3.1" @@ -4591,14 +4539,6 @@ name = "unicode-xid" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "unreachable" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "untrusted" version = "0.6.2" @@ -4692,11 +4632,6 @@ dependencies = [ "rlp 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "void" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "walkdir" version = "2.2.9" @@ -4900,7 +4835,6 @@ dependencies = [ "checksum app_dirs 1.2.1 (git+https://github.com/paritytech/app-dirs-rs)" = "" "checksum arrayref 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "0d382e583f07208808f6b1249e60848879ba3543f57c32277bf52d69c2f0f0ee" "checksum arrayvec 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)" = "cd9fd44efafa8690358b7408d253adf110036b88f55672a933f01d616ad9b1b9" -"checksum ascii 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)" = "eab1c04a571841102f5345a8fc0f6bb3d31c315dec879b5c6e42e40ce7ffa34e" "checksum assert_matches 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7deb0a829ca7bcfaf5da70b073a8d128619259a7be8216a355e23f00763059e5" "checksum atty 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)" = "1803c647a3ec87095e7ae7acfca019e98de5ec9a7d01343f611cf3152ed71a90" "checksum autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "1d49d90015b3c36167a20fe2810c5cd875ad504b39cff3d4eae7977e6b7c1cb2" @@ -4928,14 +4862,12 @@ dependencies = [ "checksum c2-chacha 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "214238caa1bf3a496ec3392968969cab8549f96ff30652c9e56885329315f6bb" "checksum cast 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "926013f2860c46252efceabb19f4a6b308197505082c609025aa6706c011d427" "checksum cc 1.0.47 (registry+https://github.com/rust-lang/crates.io-index)" = "aa87058dce70a3ff5621797f1506cb837edd02ac4c0ae642b4542dce802908b8" -"checksum cesu8 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" "checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" "checksum chrono 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)" = "e8493056968583b0193c1bb04d6f7684586f3726992d6c573261941a895dbd68" "checksum cid 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "6908948032561f2550467a477f659cdc358320a805237b9b5035c0350c441def" "checksum clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5067f5bb2d80ef5d68b4c87db81601f0b75bca627bc2ef76b141d7b846a3c6d9" "checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" "checksum cmake 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)" = "81fb25b677f8bf1eb325017cb6bb8452f87969db0fedb4f757b297bee78a7c62" -"checksum combine 3.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "da3da6baa321ec19e1cc41d31bf599f00c783d0517095cdaf0332e3fe8d20680" "checksum constant_time_eq 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "995a44c877f9212528ccc74b21a232f66ad69001e40ede5bcee2ac9ef2657120" "checksum criterion 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "0363053954f3e679645fc443321ca128b7b950a6fe288cf5f9335cc22ee58394" "checksum criterion 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "938703e165481c8d612ea3479ac8342e5615185db37765162e762ec3523e2fc6" @@ -5029,8 +4961,6 @@ dependencies = [ "checksum itoa 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "501266b7edd0174f8530248f87f99c88fbe60ca4ef3dd486835b8d8d53136f7f" "checksum jemalloc-sys 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "bfc62c8e50e381768ce8ee0428ee53741929f7ebd73e4d83f669bcf7693e00ae" "checksum jemallocator 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "9f0cd42ac65f758063fea55126b0148b1ce0a6354ff78e07a4d6806bc65c4ab3" -"checksum jni 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "294eca097d1dc0bf59de5ab9f7eafa5f77129e9f6464c957ed3ddeb705fb4292" -"checksum jni-sys 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" "checksum jsonrpc-core 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "34651edf3417637cc45e70ed0182ecfa9ced0b7e8131805fccf7400d989845ca" "checksum jsonrpc-derive 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d5d5c31575cc70a8b21542599028472c80a9248394aeea4d8918a045a0ab08a3" "checksum jsonrpc-http-server 14.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "aa54c4c2d88cb5e04b251a5031ba0f2ee8c6ef30970e31228955b89a80c3b611" @@ -5268,7 +5198,6 @@ dependencies = [ "checksum unicode-width 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "7007dbd421b92cc6e28410fe7362e2e0a2503394908f417b68ec8d1c364c4e20" "checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" "checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" -"checksum unreachable 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "382810877fe448991dfc7f0dd6e3ae5d58088fd0ea5e35189655f84e6814fa56" "checksum untrusted 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "55cd1f4b4e96b46aeb8d4855db4a7a9bd96eeeb5c6a1ab54593328761642ce2f" "checksum url 1.7.2 (registry+https://github.com/rust-lang/crates.io-index)" = "dd4e7c0d531266369519a4aa4f399d748bd37043b00bde1e4ff1f60a120b355a" "checksum url 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "75b414f6c464c879d7f9babf951f23bc3743fb7313c081b2e6ca719067ea9d61" @@ -5278,7 +5207,6 @@ dependencies = [ "checksum vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "05c78687fb1a80548ae3250346c3db86a80a7cdd77bda190189f2d0a0987c81a" "checksum vergen 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8c3365f36c57e5df714a34be40902b27a992eeddb9996eca52d0584611cf885d" "checksum version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd" -"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" "checksum walkdir 2.2.9 (registry+https://github.com/rust-lang/crates.io-index)" = "9658c94fa8b940eab2250bd5a457f9c48b748420d71293b165c8cdbe2f55f71e" "checksum want 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "a05d9d966753fa4b5c8db73fcab5eed4549cfe0e1e4e66911e5564a0085c35d1" "checksum want 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b6395efa4784b027708f7451087e647ec73cc74f5d9bc2e418404248d679a230" diff --git a/Cargo.toml b/Cargo.toml index a65eefd1a..8f069c884 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -135,7 +135,6 @@ members = [ "chainspec", "ethcore/wasm/run", "evmbin", - "parity-clib", "util/triehash-ethereum", "util/keccak-hasher", "util/patricia-trie-ethereum", diff --git a/README.md b/README.md index 6d590e8b5..f2447e131 100644 --- a/README.md +++ b/README.md @@ -296,10 +296,6 @@ Caching, Importing Blocks, and Block Information ```bash ethcore-logger ``` -* C bindings library for the Parity Ethereum client - ```bash - parity-clib - ``` * Parity Ethereum JSON-RPC Servers ```bash parity-rpc diff --git a/parity-clib/Cargo.toml b/parity-clib/Cargo.toml deleted file mode 100644 index ad8a5249a..000000000 --- a/parity-clib/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -description = "C bindings for the Parity Ethereum client" -name = "parity-clib" -version = "1.12.0" -license = "GPL-3.0" -authors = ["Parity Technologies "] - -[lib] -name = "parity" -crate-type = ["cdylib", "staticlib"] - -[dependencies] -futures = "0.1.6" -jni = { version = "0.11", optional = true } -panic_hook = { path = "../util/panic-hook" } -parity-ethereum = { path = "../", default-features = false } -tokio = "0.1.22" -tokio-current-thread = "0.1.3" - -[features] -default = [] -final = ["parity-ethereum/final"] diff --git a/parity-clib/Parity.java b/parity-clib/Parity.java deleted file mode 100644 index 3885cfb1e..000000000 --- a/parity-clib/Parity.java +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2018-2019 Parity Technologies (UK) Ltd. -// This file is part of Parity. - -// Parity is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Parity is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Parity. If not, see . - -package io.parity.ethereum; - -/** - * Interface to the Parity client. - */ -public class Parity { - /** - * Starts the Parity client with the CLI options passed as an array of strings. - * - * Each space-delimited option corresponds to an array entry. - * For example: `["--port", "12345"]` - * - * @param options The CLI options to start Parity with - */ - public Parity(String[] options, String loggerMode, String loggerFile) { - long config = configFromCli(options); - inner = build(config, loggerMode, loggerFile); - } - - /** Performs an asynchronous RPC query by spawning a background thread that is executed until - * either a response is received or the timeout has been expired. - * - * @param query The JSON-encoded RPC query to perform - * @param timeoutMillis The maximum time in milliseconds that the query will run - * @param callback An instance of class which must have a instance method named `callback` that will be - * invoke when the result is ready - */ - public void rpcQuery(String query, long timeoutMillis, Object callback) { - rpcQueryNative(inner, query, timeoutMillis, callback); - } - - /** Subscribes to a specific WebSocket event that will run in a background thread until it is canceled. - * - * @param query The JSON-encoded RPC query to perform - * @param callback An instance of class which must have a instance method named `callback` that will be invoked - * when the result is ready - * - * @return A pointer to the current sessions which can be used to terminate the session later - */ - public long subscribeWebSocket(String query, Object callback) { - return subscribeWebSocketNative(inner, query, callback); - } - - /** Unsubscribes to a specific WebSocket event - * - * @param session Pointer the the session to terminate - */ - public void unsubscribeWebSocket(long session) { - unsubscribeWebSocketNative(session); - } - - // FIXME: `finalize` is deprecated - https://github.com/paritytech/parity-ethereum/issues/10066 - @Override - protected void finalize​() { - destroy(inner); - } - - static { - System.loadLibrary("parity"); - } - - private static native long configFromCli(String[] cliOptions); - private static native long build(long config, String loggerMode, String loggerFile); - private static native void destroy(long inner); - private static native void rpcQueryNative(long inner, String rpc, long timeoutMillis, Object callback); - private static native long subscribeWebSocketNative(long inner, String rpc, Object callback); - private static native void unsubscribeWebSocketNative(long session); - - private long inner; -} diff --git a/parity-clib/examples/cpp/CMakeLists.txt b/parity-clib/examples/cpp/CMakeLists.txt deleted file mode 100644 index 8cc6aef8f..000000000 --- a/parity-clib/examples/cpp/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -include(ExternalProject) -include_directories("${CMAKE_SOURCE_DIR}/../..") -set (CMAKE_CXX_STANDARD 11) # Enfore C++11 -add_executable(parity-example main.cpp) - -ExternalProject_Add( - libparity - DOWNLOAD_COMMAND "" - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - COMMAND cargo build -p parity-clib # Note: use --release in a real project - BINARY_DIR "${CMAKE_SOURCE_DIR}/../../../target" - INSTALL_COMMAND "" - LOG_BUILD ON) - -add_dependencies(parity-example libparity) -target_link_libraries(parity-example "${CMAKE_SOURCE_DIR}/../../../target/debug/${CMAKE_SHARED_LIBRARY_PREFIX}parity${CMAKE_SHARED_LIBRARY_SUFFIX}") diff --git a/parity-clib/examples/cpp/main.cpp b/parity-clib/examples/cpp/main.cpp deleted file mode 100644 index 43b31d793..000000000 --- a/parity-clib/examples/cpp/main.cpp +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright 2015-2019 Parity Technologies (UK) Ltd. -// This file is part of Parity Ethereum. - -// Parity Ethereum is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Parity Ethereum is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Parity Ethereum. If not, see . - -#include -#include -#include -#include -#include - -void* parity_run(std::vector); -int parity_subscribe_to_websocket(void*); -int parity_rpc_queries(void*); - -const int SUBSCRIPTION_ID_LEN = 18; -const size_t TIMEOUT_ONE_MIN_AS_MILLIS = 60 * 1000; -const unsigned int CALLBACK_RPC = 1; -const unsigned int CALLBACK_WS = 2; - -struct Callback { - unsigned int type; - long unsigned int counter; -}; - -// list of rpc queries -const std::vector rpc_queries { - "{\"method\":\"parity_versionInfo\",\"params\":[],\"id\":1,\"jsonrpc\":\"2.0\"}", - "{\"method\":\"eth_getTransactionReceipt\",\"params\":[\"0x444172bef57ad978655171a8af2cfd89baa02a97fcb773067aef7794d6913fff\"],\"id\":1,\"jsonrpc\":\"2.0\"}", - "{\"method\":\"eth_estimateGas\",\"params\":[{\"from\":\"0x0066Dc48bb833d2B59f730F33952B3c29fE926F5\"}],\"id\":1,\"jsonrpc\":\"2.0\"}", - "{\"method\":\"eth_getBalance\",\"params\":[\"0x0066Dc48bb833d2B59f730F33952B3c29fE926F5\"],\"id\":1,\"jsonrpc\":\"2.0\"}" -}; - -// list of subscriptions -const std::vector ws_subscriptions { - "{\"method\":\"parity_subscribe\",\"params\":[\"eth_getBalance\",[\"0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826\",\"latest\"]],\"id\":1,\"jsonrpc\":\"2.0\"}", - "{\"method\":\"parity_subscribe\",\"params\":[\"parity_netPeers\"],\"id\":1,\"jsonrpc\":\"2.0\"}", - "{\"method\":\"eth_subscribe\",\"params\":[\"newHeads\"],\"id\":1,\"jsonrpc\":\"2.0\"}" -}; - -// callback that gets invoked upon an event -void callback(void* user_data, const char* response, size_t _len) { - Callback* cb = static_cast(user_data); - if (cb->type == CALLBACK_RPC) { - cb->counter -= 1; - } else if (cb->type == CALLBACK_WS) { - std::regex is_subscription ("\\{\"jsonrpc\":\"2.0\",\"result\":\"0[xX][a-fA-F0-9]{16}\",\"id\":1\\}"); - if (std::regex_match(response, is_subscription) == true) { - cb->counter -= 1; - } - } -} - -int main() { - // run full-client - { - std::vector config = {"--no-ipc" , "--jsonrpc-apis=all", "--chain", "kovan"}; - void* parity = parity_run(config); - if (parity_rpc_queries(parity)) { - printf("rpc_queries failed\r\n"); - return 1; - } - - if (parity_subscribe_to_websocket(parity)) { - printf("ws_queries failed\r\n"); - return 1; - } - - if (parity != nullptr) { - parity_destroy(parity); - } - } - - // run light-client - { - std::vector light_config = {"--no-ipc", "--light", "--jsonrpc-apis=all", "--chain", "kovan"}; - void* parity = parity_run(light_config); - - if (parity_rpc_queries(parity)) { - printf("rpc_queries failed\r\n"); - return 1; - } - - if (parity_subscribe_to_websocket(parity)) { - printf("ws_queries failed\r\n"); - return 1; - } - - if (parity != nullptr) { - parity_destroy(parity); - } - } - return 0; -} - -int parity_rpc_queries(void* parity) { - if (!parity) { - return 1; - } - - Callback cb { .type = CALLBACK_RPC, .counter = rpc_queries.size() }; - - for (auto query : rpc_queries) { - if (parity_rpc(parity, query.c_str(), query.length(), TIMEOUT_ONE_MIN_AS_MILLIS, callback, &cb) != 0) { - return 1; - } - } - - while(cb.counter != 0); - return 0; -} - - -int parity_subscribe_to_websocket(void* parity) { - if (!parity) { - return 1; - } - - std::vector sessions; - - Callback cb { .type = CALLBACK_WS, .counter = ws_subscriptions.size() }; - - for (auto sub : ws_subscriptions) { - void *const session = parity_subscribe_ws(parity, sub.c_str(), sub.length(), callback, &cb); - if (!session) { - return 1; - } - sessions.push_back(session); - } - - while(cb.counter != 0); - std::this_thread::sleep_for(std::chrono::seconds(60)); - for (auto session : sessions) { - parity_unsubscribe_ws(session); - } - return 0; -} - -void* parity_run(std::vector args) { - ParityParams cfg = { - .configuration = nullptr, - .on_client_restart_cb = callback, - .on_client_restart_cb_custom = nullptr, - .logger = nullptr - }; - - std::vector str_lens; - - for (auto arg: args) { - str_lens.push_back(std::strlen(arg)); - } - - // make sure no out-of-range access happens here - if (args.empty()) { - if (parity_config_from_cli(nullptr, nullptr, 0, &cfg.configuration) != 0) { - return nullptr; - } - } else { - if (parity_config_from_cli(&args[0], &str_lens[0], args.size(), &cfg.configuration) != 0) { - return nullptr; - } - } - - // enable logging but only the `rpc module` and don't write it to a file - char log_mode [] = "rpc=trace"; - parity_set_logger(log_mode, strlen(log_mode), nullptr, 0, &cfg.logger); - - void *parity = nullptr; - if (parity_start(&cfg, &parity) != 0) { - return nullptr; - } - - return parity; -} diff --git a/parity-clib/examples/java/Main.java b/parity-clib/examples/java/Main.java deleted file mode 100644 index c20b9e34d..000000000 --- a/parity-clib/examples/java/Main.java +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2018-2019 Parity Technologies (UK) Ltd. -// This file is part of Parity. - -// Parity is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Parity is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Parity. If not, see . - -import java.util.Vector; -import java.util.concurrent.atomic.AtomicInteger; -import io.parity.ethereum.Parity; - -class Main { - public static final int ONE_MINUTE_AS_MILLIS = 60 * 1000; - - public static final String[] rpc_queries = { - "{\"method\":\"parity_versionInfo\",\"params\":[],\"id\":1,\"jsonrpc\":\"2.0\"}", - "{\"method\":\"eth_getTransactionReceipt\",\"params\":[\"0x444172bef57ad978655171a8af2cfd89baa02a97fcb773067aef7794d6913fff\"],\"id\":1,\"jsonrpc\":\"2.0\"}", - "{\"method\":\"eth_estimateGas\",\"params\":[{\"from\":\"0x0066Dc48bb833d2B59f730F33952B3c29fE926F5\"}],\"id\":1,\"jsonrpc\":\"2.0\"}", - "{\"method\":\"eth_getBalance\",\"params\":[\"0x0066Dc48bb833d2B59f730F33952B3c29fE926F5\"],\"id\":1,\"jsonrpc\":\"2.0\"}" - }; - - public static final String[] ws_queries = { - "{\"method\":\"parity_subscribe\",\"params\":[\"eth_getBalance\",[\"0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826\",\"latest\"]],\"id\":1,\"jsonrpc\":\"2.0\"}", - "{\"method\":\"parity_subscribe\",\"params\":[\"parity_netPeers\"],\"id\":1,\"jsonrpc\":\"2.0\"}", - "{\"method\":\"eth_subscribe\",\"params\":[\"newHeads\"],\"id\":1,\"jsonrpc\":\"2.0\"}" - }; - - public static void runParity(String[] config) { - String loggerMode = "rpc=trace"; - String loggerFile = "foo.log"; - Parity parity = new Parity(config, loggerMode, loggerFile); - - Callback rpcCallback = new Callback(1); - Callback webSocketCallback = new Callback(2); - - for (String query : rpc_queries) { - parity.rpcQuery(query, ONE_MINUTE_AS_MILLIS, rpcCallback); - } - - while (rpcCallback.getNumCallbacks() != 4); - - Vector sessions = new Vector(); - - for (String ws : ws_queries) { - long session = parity.subscribeWebSocket(ws, webSocketCallback); - sessions.add(session); - } - - try { - Thread.sleep(ONE_MINUTE_AS_MILLIS); - } catch (Exception e) { - System.out.println(e); - } - - for (long session : sessions) { - parity.unsubscribeWebSocket(session); - } - - // Force GC to destroy parity - parity = null; - System.gc(); - } - - public static void main(String[] args) { - String[] full = {"--no-ipc" , "--jsonrpc-apis=all", "--chain", "kovan"}; - String[] light = {"--no-ipc", "--light", "--jsonrpc-apis=all", "--chain", "kovan"}; - - runParity(full); - - try { - Thread.sleep(ONE_MINUTE_AS_MILLIS); - } catch (Exception e) { - System.out.println(e); - } - - runParity(light); - } -} - -class Callback { - private AtomicInteger counter; - private final int callbackType; - - public Callback(int type) { - counter = new AtomicInteger(); - callbackType = type; - } - - public void callback(Object response) { - counter.getAndIncrement(); - } - - public int getNumCallbacks() { - return counter.intValue(); - } -} diff --git a/parity-clib/examples/java/README.md b/parity-clib/examples/java/README.md deleted file mode 100644 index ec83905bf..000000000 --- a/parity-clib/examples/java/README.md +++ /dev/null @@ -1,9 +0,0 @@ -parity-clib: Java example -=================================== - -An example Java application to demonstrate how to use `jni` bindings to parity-ethereum. Note, that the example is built in debug-mode to reduce the build time. If you want to use it in real project use release-mode instead to facilitate all compiler optimizations. - -## How to compile and run - -1. Make sure you have installed [JDK](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) -2. Run `run.sh` \ No newline at end of file diff --git a/parity-clib/examples/java/run.sh b/parity-clib/examples/java/run.sh deleted file mode 100755 index 428a7dc75..000000000 --- a/parity-clib/examples/java/run.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env bash - -FLAGS="-Xlint:deprecation" -PARITY_JAVA="../../Parity.java" -# parity-clib must be built with feature `jni` in debug-mode to work -PARITY_LIB=".:../../../target/debug/" - -# build -cd .. -cargo build --features jni -cd - -javac $FLAGS -d $PWD $PARITY_JAVA -javac $FLAGS *.java -# Setup the path `libparity.so` and run -java -Djava.library.path=$PARITY_LIB Main diff --git a/parity-clib/parity.h b/parity-clib/parity.h deleted file mode 100644 index 7bba08e43..000000000 --- a/parity-clib/parity.h +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright 2018-2019 Parity Technologies (UK) Ltd. -// This file is part of Parity. - -// Parity is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Parity is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Parity. If not, see . - -#ifndef _PARITY_H_INCLUDED_ -#define _PARITY_H_INCLUDED_ - -#include - -/// Parameters to pass to `parity_start`. -struct ParityParams { - /// Configuration object, as handled by the `parity_config_*` functions. - /// Note that calling `parity_start` will destroy the configuration object (even on failure). - void *configuration; - - /// Callback function to call when the client receives an RPC request to change its chain spec. - /// - /// Will only be called if you enable the `--can-restart` flag. - /// - /// The first parameter of the callback is the value of `on_client_restart_cb_custom`. - /// The second and third parameters of the callback are the string pointer and length. - void (*on_client_restart_cb)(void* custom, const char* new_chain, size_t new_chain_len); - - /// Custom parameter passed to the `on_client_restart_cb` callback as first parameter. - void *on_client_restart_cb_custom; - - /// Logger object which must be created by the `parity_config_logger` function - void *logger; -}; - -#ifdef __cplusplus -extern "C" { -#endif - -/// Builds a new configuration object by parsing a list of CLI arguments. -/// -/// The first two parameters are string pointers and string lengths. They must have a length equal -/// to `len`. The strings don't need to be zero-terminated. -/// -/// On success, the produced object will be written to the `void*` pointed by `out`. -/// -/// Returns 0 on success, and non-zero on error. -/// -/// # Example -/// -/// ```no_run -/// void* cfg; -/// const char *args[] = {"--light", "--can-restart"}; -/// size_t str_lens[] = {7, 13}; -/// if (parity_config_from_cli(args, str_lens, 2, &cfg) != 0) { -/// return 1; -/// } -/// ``` -/// -int parity_config_from_cli(char const* const* args, size_t const* arg_lens, size_t len, void** out); - -/// Builds a new logger object which should be a member of the `ParityParams struct` -/// -/// - log_mode : String representing the log mode according to `Rust LOG` or nullptr to disable logging. -/// See module documentation for `ethcore-logger` for more info. -/// - log_mode_len : Length of the log_mode or zero to disable logging -/// - log_file : String respresenting the file name to write to log to or nullptr to disable logging to a file -/// - log_mode_len : Length of the log_file or zero to disable logging to a file -/// - logger : Pointer to point to the created `Logger` object - -/// **Important**: This function must only be called exactly once otherwise it will panic. If you want to disable a -/// logging mode or logging to a file make sure that you pass the `length` as zero -/// -/// # Example -/// -/// ```no_run -/// void* cfg; -/// const char *args[] = {"--light", "--can-restart"}; -/// size_t str_lens[] = {7, 13}; -/// if (parity_config_from_cli(args, str_lens, 2, &cfg) != 0) { -/// return 1; -/// } -/// char[] logger_mode = "rpc=trace"; -/// parity_set_logger(logger_mode, strlen(logger_mode), nullptr, 0, &cfg.logger); -/// ``` -/// -int parity_set_logger(const char* log_mode, size_t log_mode_len, const char* log_file, size_t log_file_len, void** logger); - -/// Destroys a configuration object created earlier. -/// -/// **Important**: You probably don't need to call this function. Calling `parity_start` destroys -/// the configuration object as well (even on failure). -void parity_config_destroy(void* cfg); - -/// Starts the parity client in background threads. Returns a pointer to a struct that represents -/// the running client. Can also return NULL if the execution completes instantly. -/// -/// **Important**: The configuration object passed inside `cfg` is destroyed when you -/// call `parity_start` (even on failure). -/// -/// On success, the produced object will be written to the `void*` pointed by `out`. -/// -/// Returns 0 on success, and non-zero on error. -int parity_start(const ParityParams* params, void** out); - -/// Destroys the parity client created with `parity_start`. -/// -/// **Warning**: `parity_start` can return NULL if execution finished instantly, in which case you -/// must not call this function. -void parity_destroy(void* parity); - -/// Performs an asynchronous RPC request running in a background thread for at most X milliseconds -/// -/// - parity : Reference to the running parity client -/// - rpc_query : JSON encoded string representing the RPC request. -/// - len : Length of the RPC query -/// - timeout_ms : Maximum time that request is waiting for a response -/// - response : Callback to invoke when the query gets answered. It will respond with a JSON encoded the string -/// with the result both on success and error. -/// - ud : Specific user defined data that can used in the callback -/// -/// - On success : The function returns 0 -/// - On error : The function returns 1 -/// -int parity_rpc(const void *const parity, const char* rpc_query, size_t rpc_len, size_t timeout_ms, - void (*subscribe)(void* ud, const char* response, size_t len), void* ud); - - -/// Subscribes to a specific websocket event that will run until it is canceled -/// -/// - parity : Reference to the running parity client -/// - ws_query : JSON encoded string representing the websocket event to subscribe to -/// - len : Length of the query -/// - response : Callback to invoke when a websocket event occurs -/// - ud : Specific user defined data that can used in the callback -/// -/// - On success : The function returns an object to the current session -/// which can be used cancel the subscription -/// - On error : The function returns a null pointer -/// -void* parity_subscribe_ws(const void *const parity, const char* ws_query, size_t len, - void (*subscribe)(void* ud, const char* response, size_t len), void* ud); - -/// Unsubscribes from a websocket subscription. Caution this function consumes the session object and must only be -/// used exactly once per session. -/// -/// - session : Pointer to the session to unsubscribe from -/// -int parity_unsubscribe_ws(const void *const session); - -/// Sets a callback to call when a panic happens in the Rust code. -/// -/// The callback takes as parameter the custom param (the one passed to this function), plus the -/// panic message. You are expected to log the panic message somehow, in order to communicate it to -/// the user. A panic always indicates a bug in Parity. -/// -/// Note that this method sets the panic hook for the whole program, and not just for Parity. In -/// other words, if you use multiple Rust libraries at once (and not just Parity), then a panic -/// in any Rust code will call this callback as well. -/// -/// ## Thread safety -/// -/// The callback can be called from any thread and multiple times simultaneously. Make sure that -/// your code is thread safe. -/// -int parity_set_panic_hook(void (*cb)(void* param, const char* msg, size_t msg_len), void* param); - -#ifdef __cplusplus -} -#endif - -#endif // include guard diff --git a/parity-clib/src/java.rs b/parity-clib/src/java.rs deleted file mode 100644 index 1c8751341..000000000 --- a/parity-clib/src/java.rs +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright 2015-2019 Parity Technologies (UK) Ltd. -// This file is part of Parity Ethereum. - -// Parity Ethereum is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Parity Ethereum is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Parity Ethereum. If not, see . - -use std::{ffi::c_void, mem, ptr, sync::Arc}; - -use parity_config_from_cli; -use parity_destroy; -use parity_rpc_worker; -use parity_set_logger; -use parity_start; -use parity_unsubscribe_ws; -use parity_ws_worker; -use Callback; -use ParityParams; - -use jni::{ - objects::{GlobalRef, JClass, JObject, JString, JValue}, - sys::{jlong, jobjectArray, va_list}, - JNIEnv, JavaVM, -}; -use parity_ethereum::RunningClient; - -type CheckedQuery<'a> = (&'a RunningClient, String, JavaVM, GlobalRef); - -// Creates a Java callback to a static method named `void callback(Object)` -struct JavaCallback<'a> { - jvm: JavaVM, - callback: GlobalRef, - method_name: &'a str, - method_descriptor: &'a str, -} - -impl<'a> JavaCallback<'a> { - fn new(jvm: JavaVM, callback: GlobalRef) -> Self { - Self { - jvm, - callback, - method_name: "callback", - method_descriptor: "(Ljava/lang/Object;)V", - } - } -} - -impl<'a> Callback for JavaCallback<'a> { - fn call(&self, msg: &str) { - let env = self - .jvm - .attach_current_thread() - .expect("JavaVM should have an environment; qed"); - let java_str = env - .new_string(msg.to_string()) - .expect("Rust String is valid JString; qed"); - let val = &[JValue::Object(JObject::from(java_str))]; - env.call_method( - self.callback.as_obj(), - self.method_name, - self.method_descriptor, - val, - ) - .expect( - "The callback must be an instance method and be named \"void callback(Object)\"; qed)", - ); - } -} - -#[no_mangle] -pub unsafe extern "system" fn Java_io_parity_ethereum_Parity_configFromCli( - env: JNIEnv, - _: JClass, - cli: jobjectArray, -) -> jlong { - let cli_len = env.get_array_length(cli).expect("invalid Java bindings") as usize; - - let mut jni_strings = Vec::with_capacity(cli_len); - let mut opts = Vec::with_capacity(cli_len); - let mut opts_lens = Vec::with_capacity(cli_len); - - for n in 0..cli_len as i32 { - let elem = env - .get_object_array_element(cli, n) - .expect("invalid Java bindings"); - let elem_str: JString = elem.into(); - match env.get_string(elem_str) { - Ok(s) => { - opts.push(s.as_ptr()); - opts_lens.push(s.to_bytes().len()); - jni_strings.push(s); - } - Err(err) => { - let _ = env.throw_new("java/lang/Exception", err.to_string()); - return 0; - } - }; - } - - let mut out = ptr::null_mut(); - match parity_config_from_cli(opts.as_ptr(), opts_lens.as_ptr(), cli_len, &mut out) { - 0 => out as jlong, - _ => { - let _ = env.throw_new("java/lang/Exception", "failed to create config object"); - 0 - } - } -} - -#[no_mangle] -pub unsafe extern "system" fn Java_io_parity_ethereum_Parity_build( - env: JNIEnv, - _: JClass, - config: va_list, - logger_mode: JString, - logger_file: JString, -) -> jlong { - let mut params = ParityParams { - configuration: config, - ..mem::zeroed() - }; - - let logger_mode: String = env - .get_string(logger_mode) - .expect("valid JString; qed") - .into(); - let logger_file: String = env - .get_string(logger_file) - .expect("valid JString; qed") - .into(); - - parity_set_logger( - logger_mode.as_ptr(), - logger_mode.as_bytes().len(), - logger_file.as_ptr(), - logger_file.as_bytes().len(), - &mut params.logger, - ); - - let mut out = ptr::null_mut(); - match parity_start(¶ms, &mut out) { - 0 => out as jlong, - _ => { - let _ = env.throw_new("java/lang/Exception", "failed to start Parity"); - 0 - } - } -} - -#[no_mangle] -pub unsafe extern "system" fn Java_io_parity_ethereum_Parity_destroy( - _env: JNIEnv, - _: JClass, - parity: va_list, -) { - parity_destroy(parity); -} - -unsafe fn java_query_checker<'a>( - client: va_list, - rpc: JString, - callback: JObject, - env: &JNIEnv<'a>, -) -> Result, String> { - let query: String = env - .get_string(rpc) - .map(Into::into) - .map_err(|e| e.to_string())?; - - let client: &RunningClient = &*(client as *const RunningClient); - let jvm = env.get_java_vm().map_err(|e| e.to_string())?; - let global_ref = env.new_global_ref(callback).map_err(|e| e.to_string())?; - Ok((client, query, jvm, global_ref)) -} - -#[no_mangle] -pub unsafe extern "system" fn Java_io_parity_ethereum_Parity_rpcQueryNative( - env: JNIEnv, - _: JClass, - parity: va_list, - rpc: JString, - timeout_ms: jlong, - callback: JObject, -) { - let _ = java_query_checker(parity, rpc, callback, &env) - .map(|(client, query, jvm, global_ref)| { - let callback = Arc::new(JavaCallback::new(jvm, global_ref)); - parity_rpc_worker(client, &query, callback, timeout_ms as u64); - }) - .map_err(|e| { - let _ = env.throw_new("java/lang/Exception", e); - }); -} - -#[no_mangle] -pub unsafe extern "system" fn Java_io_parity_ethereum_Parity_subscribeWebSocketNative( - env: JNIEnv, - _: JClass, - parity: va_list, - rpc: JString, - callback: JObject, -) -> va_list { - java_query_checker(parity, rpc, callback, &env) - .map(move |(client, query, jvm, global_ref)| { - let callback = Arc::new(JavaCallback::new(jvm, global_ref)); - parity_ws_worker(client, &query, callback) as va_list - }) - .unwrap_or_else(|e| { - let _ = env.throw_new("java/lang/Exception", e); - ptr::null_mut() - }) -} - -#[no_mangle] -pub unsafe extern "system" fn Java_io_parity_ethereum_Parity_unsubscribeWebSocketNative( - _: JNIEnv, - _: JClass, - session: va_list, -) { - parity_unsubscribe_ws(session as *const c_void); -} diff --git a/parity-clib/src/lib.rs b/parity-clib/src/lib.rs deleted file mode 100644 index 0d18bccfa..000000000 --- a/parity-clib/src/lib.rs +++ /dev/null @@ -1,342 +0,0 @@ -// Copyright 2015-2019 Parity Technologies (UK) Ltd. -// This file is part of Parity Ethereum. - -// Parity Ethereum is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Parity Ethereum is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Parity Ethereum. If not, see . - -//! Note that all the structs and functions here are documented in `parity.h`, to avoid -//! duplicating documentation. - -extern crate futures; -extern crate panic_hook; -extern crate parity_ethereum; -extern crate tokio; -extern crate tokio_current_thread; - -#[cfg(feature = "jni")] -extern crate jni; - -#[cfg(feature = "jni")] -mod java; - -use std::{ - ffi::CString, - os::raw::{c_char, c_int, c_void}, - panic, ptr, slice, str, - sync::Arc, - thread, - time::Duration, -}; - -use futures::{sync::mpsc, Future, Stream}; -use parity_ethereum::{PubSubSession, RunningClient}; -use tokio_current_thread::CurrentThread; - -type CCallback = Option; -type CheckedQuery<'a> = (&'a RunningClient, &'static str); - -pub mod error { - pub const EMPTY: &str = r#"{"jsonrpc":"2.0","result":"null","id":1}"#; - pub const TIMEOUT: &str = r#"{"jsonrpc":"2.0","result":"timeout","id":1}"#; - pub const SUBSCRIBE: &str = r#"{"jsonrpc":"2.0","result":"subcribe_fail","id":1}"#; -} - -#[repr(C)] -pub struct ParityParams { - pub configuration: *mut c_void, - pub on_client_restart_cb: CCallback, - pub on_client_restart_cb_custom: *mut c_void, - pub logger: *mut c_void, -} - -/// Trait representing a callback that passes a string -pub(crate) trait Callback: Send + Sync { - fn call(&self, msg: &str); -} - -// Internal structure for handling callbacks that get passed a string. -struct CallbackStr { - user_data: *mut c_void, - function: CCallback, -} - -unsafe impl Send for CallbackStr {} -unsafe impl Sync for CallbackStr {} -impl Callback for CallbackStr { - fn call(&self, msg: &str) { - if let Some(ref cb) = self.function { - let cstr = CString::new(msg) - .expect("valid string with no nul bytes in the middle; qed") - .into_raw(); - cb(self.user_data, cstr, msg.len()) - } - } -} - -#[no_mangle] -pub unsafe extern "C" fn parity_config_from_cli( - args: *const *const c_char, - args_lens: *const usize, - len: usize, - output: *mut *mut c_void, -) -> c_int { - panic::catch_unwind(|| { - *output = ptr::null_mut(); - - let args = { - let arg_ptrs = slice::from_raw_parts(args, len); - let arg_lens = slice::from_raw_parts(args_lens, len); - - let mut args = Vec::with_capacity(len + 1); - args.push("parity".to_owned()); - - for (&arg, &len) in arg_ptrs.iter().zip(arg_lens.iter()) { - let string = slice::from_raw_parts(arg as *const u8, len); - match String::from_utf8(string.to_owned()) { - Ok(a) => args.push(a), - Err(_) => return 1, - }; - } - args - }; - - match parity_ethereum::Configuration::parse_cli(&args) { - Ok(mut cfg) => { - // Always disable the auto-updater when used as a library. - cfg.args.arg_auto_update = "none".to_owned(); - - let cfg = Box::into_raw(Box::new(cfg)); - *output = cfg as *mut _; - 0 - } - Err(_) => 1, - } - }) - .unwrap_or(1) -} - -#[no_mangle] -pub unsafe extern "C" fn parity_config_destroy(cfg: *mut c_void) { - let _ = panic::catch_unwind(|| { - let _cfg = Box::from_raw(cfg as *mut parity_ethereum::Configuration); - }); -} - -#[no_mangle] -pub unsafe extern "C" fn parity_start(cfg: *const ParityParams, output: *mut *mut c_void) -> c_int { - panic::catch_unwind(|| { - *output = ptr::null_mut(); - let cfg: &ParityParams = &*cfg; - let logger = Arc::from_raw(cfg.logger as *mut parity_ethereum::RotatingLogger); - let config = Box::from_raw(cfg.configuration as *mut parity_ethereum::Configuration); - - let on_client_restart_cb = { - let cb = CallbackStr { - user_data: cfg.on_client_restart_cb_custom, - function: cfg.on_client_restart_cb, - }; - move |new_chain: String| { - cb.call(&new_chain); - } - }; - - let action = match parity_ethereum::start(*config, logger, on_client_restart_cb, || {}) { - Ok(action) => action, - Err(_) => return 1, - }; - - match action { - parity_ethereum::ExecutionAction::Instant(Some(s)) => { - println!("{}", s); - 0 - } - parity_ethereum::ExecutionAction::Instant(None) => 0, - parity_ethereum::ExecutionAction::Running(client) => { - *output = Box::into_raw(Box::new(client)) as *mut c_void; - 0 - } - } - }) - .unwrap_or(1) -} - -#[no_mangle] -pub unsafe extern "C" fn parity_destroy(client: *mut c_void) { - let _ = panic::catch_unwind(|| { - let client = Box::from_raw(client as *mut RunningClient); - client.shutdown(); - }); -} - -#[no_mangle] -pub unsafe extern "C" fn parity_rpc( - client: *const c_void, - query: *const c_char, - len: usize, - timeout_ms: usize, - callback: CCallback, - user_data: *mut c_void, -) -> c_int { - panic::catch_unwind(|| { - if let Some((client, query)) = parity_rpc_query_checker(client, query, len) { - let callback = Arc::new(CallbackStr { - user_data, - function: callback, - }); - parity_rpc_worker(client, query, callback, timeout_ms as u64); - 0 - } else { - 1 - } - }) - .unwrap_or(1) -} - -#[no_mangle] -pub unsafe extern "C" fn parity_subscribe_ws( - client: *const c_void, - query: *const c_char, - len: usize, - callback: CCallback, - user_data: *mut c_void, -) -> *const c_void { - panic::catch_unwind(|| { - if let Some((client, query)) = parity_rpc_query_checker(client, query, len) { - let callback = Arc::new(CallbackStr { - user_data, - function: callback, - }); - parity_ws_worker(client, query, callback) - } else { - ptr::null() - } - }) - .unwrap_or(ptr::null()) -} - -#[no_mangle] -pub unsafe extern "C" fn parity_unsubscribe_ws(session: *const c_void) { - let _ = panic::catch_unwind(|| { - let _session = Arc::from_raw(session as *const PubSubSession); - }); -} - -#[no_mangle] -pub extern "C" fn parity_set_panic_hook(callback: CCallback, param: *mut c_void) { - let cb = CallbackStr { - user_data: param, - function: callback, - }; - panic_hook::set_with(move |panic_msg| { - cb.call(panic_msg); - }); -} - -#[no_mangle] -pub unsafe extern "C" fn parity_set_logger( - logger_mode: *const u8, - logger_mode_len: usize, - log_file: *const u8, - log_file_len: usize, - logger: *mut *mut c_void, -) { - let mut logger_cfg = parity_ethereum::LoggerConfig::default(); - logger_cfg.mode = - String::from_utf8(slice::from_raw_parts(logger_mode, logger_mode_len).to_owned()).ok(); - - // Make sure an empty string is not constructed as file name (to prevent panic) - if log_file_len != 0 && !log_file.is_null() { - logger_cfg.file = - String::from_utf8(slice::from_raw_parts(log_file, log_file_len).to_owned()).ok(); - } - - *logger = Arc::into_raw( - parity_ethereum::setup_log(&logger_cfg).expect("Logger initialized only once; qed"), - ) as *mut _; -} - -// WebSocket event loop -fn parity_ws_worker( - client: &RunningClient, - query: &str, - callback: Arc, -) -> *const c_void { - let (tx, mut rx) = mpsc::channel(1); - let session = Arc::new(PubSubSession::new(tx)); - let query_future = client.rpc_query(query, Some(session.clone())); - let weak_session = Arc::downgrade(&session); - let _handle = thread::Builder::new() - .name("ws-subscriber".into()) - .spawn(move || { - // Wait for subscription ID - // Note this may block forever and be can't destroyed using the session object - // However, this will likely timeout or be catched the RPC layer - if let Ok(Some(response)) = query_future.wait() { - callback.call(&response); - } else { - callback.call(error::SUBSCRIBE); - return; - } - - while weak_session - .upgrade() - .map_or(0, |session| Arc::strong_count(&session)) - > 1 - { - for response in rx.by_ref().wait() { - if let Ok(r) = response { - callback.call(&r); - } - } - } - }) - .expect("rpc-subscriber thread shouldn't fail; qed"); - Arc::into_raw(session) as *const c_void -} - -// RPC event loop that runs for at most `timeout_ms` -fn parity_rpc_worker( - client: &RunningClient, - query: &str, - callback: Arc, - timeout_ms: u64, -) { - let cb = callback.clone(); - let query = client.rpc_query(query, None).map(move |response| { - let response = response.unwrap_or_else(|| error::EMPTY.to_string()); - callback.call(&response); - }); - - let _handle = thread::Builder::new() - .name("rpc_query".to_string()) - .spawn(move || { - let mut current_thread = CurrentThread::new(); - current_thread.spawn(query); - let _ = current_thread - .run_timeout(Duration::from_millis(timeout_ms)) - .map_err(|_e| { - cb.call(error::TIMEOUT); - }); - }) - .expect("rpc-query thread shouldn't fail; qed"); -} - -unsafe fn parity_rpc_query_checker<'a>( - client: *const c_void, - query: *const c_char, - len: usize, -) -> Option> { - let query_str = str::from_utf8(slice::from_raw_parts(query as *const u8, len)).ok()?; - let client: &RunningClient = &*(client as *const RunningClient); - Some((client, query_str)) -}