openethereum/miner/price-info/src/lib.rs

216 lines
5.4 KiB
Rust
Raw Normal View History

// 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 <http://www.gnu.org/licenses/>.
#![warn(missing_docs)]
//! A simple client to get the current ETH price using an external API.
extern crate futures;
extern crate serde_json;
extern crate parity_runtime;
#[macro_use]
extern crate log;
#[cfg(test)]
extern crate fake_fetch;
pub extern crate fetch;
2017-08-04 13:06:01 +02:00
use std::cmp;
use std::fmt;
use std::io;
use std::str;
2017-08-04 13:06:01 +02:00
use fetch::{Client as FetchClient, Fetch};
use futures::{Future, Stream};
use futures::future::{self, Either};
2017-08-04 13:06:01 +02:00
use serde_json::Value;
use parity_runtime::Executor;
2017-08-04 13:06:01 +02:00
/// Current ETH price information.
#[derive(Debug)]
pub struct PriceInfo {
/// Current ETH price in USD.
pub ethusd: f32,
}
/// Price info error.
#[derive(Debug)]
pub enum Error {
2017-08-04 13:39:57 +02:00
/// The API returned an unexpected status code.
StatusCode(&'static str),
/// The API returned an unexpected status content.
UnexpectedResponse(Option<String>),
2017-08-04 13:06:01 +02:00
/// There was an error when trying to reach the API.
Fetch(fetch::Error),
/// IO error when reading API response.
Io(io::Error),
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self { Error::Io(err) }
}
impl From<fetch::Error> for Error {
fn from(err: fetch::Error) -> Self { Error::Fetch(err) }
}
/// A client to get the current ETH price using an external API.
pub struct Client<F = FetchClient> {
pool: Executor,
2017-08-04 13:06:01 +02:00
api_endpoint: String,
fetch: F,
}
impl<F> fmt::Debug for Client<F> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("price_info::Client")
.field("api_endpoint", &self.api_endpoint)
.finish()
}
}
impl<F> cmp::PartialEq for Client<F> {
fn eq(&self, other: &Client<F>) -> bool {
self.api_endpoint == other.api_endpoint
}
}
impl<F: Fetch> Client<F> {
/// Creates a new instance of the `Client` given a `fetch::Client`.
pub fn new(fetch: F, pool: Executor) -> Client<F> {
let api_endpoint = "https://api.etherscan.io/api?module=stats&action=ethprice".to_owned();
Client { pool, api_endpoint, fetch }
2017-08-04 13:06:01 +02:00
}
/// Gets the current ETH price and calls `set_price` with the result.
New Transaction Queue implementation (#8074) * Implementation of Verifier, Scoring and Ready. * Queue in progress. * TransactionPool. * Prepare for txpool release. * Miner refactor [WiP] * WiP reworking miner. * Make it compile. * Add some docs. * Split blockchain access to a separate file. * Work on miner API. * Fix ethcore tests. * Refactor miner interface for sealing/work packages. * Implement next nonce. * RPC compiles. * Implement couple of missing methdods for RPC. * Add transaction queue listeners. * Compiles! * Clean-up and parallelize. * Get rid of RefCell in header. * Revert "Get rid of RefCell in header." This reverts commit 0f2424c9b7319a786e1565ea2a8a6d801a21b4fb. * Override Sync requirement. * Fix status display. * Unify logging. * Extract some cheap checks. * Measurements and optimizations. * Fix scoring bug, heap size of bug and add cache * Disable tx queueing and parallel verification. * Make ethcore and ethcore-miner compile again. * Make RPC compile again. * Bunch of txpool tests. * Migrate transaction queue tests. * Nonce Cap * Nonce cap cache and tests. * Remove stale future transactions from the queue. * Optimize scoring and write some tests. * Simple penalization. * Clean up and support for different scoring algorithms. * Add CLI parameters for the new queue. * Remove banning queue. * Disable debug build. * Change per_sender limit to be 1% instead of 5% * Avoid cloning when propagating transactions. * Remove old todo. * Post-review fixes. * Fix miner options default. * Implement back ready transactions for light client. * Get rid of from_pending_block * Pass rejection reason. * Add more details to drop. * Rollback heap size of. * Avoid cloning hashes when propagating and include more details on rejection. * Fix tests. * Introduce nonces cache. * Remove uneccessary hashes allocation. * Lower the mem limit. * Re-enable parallel verification. * Add miner log. Don't check the type if not below min_gas_price. * Add more traces, fix disabling miner. * Fix creating pending blocks twice on AuRa authorities. * Fix tests. * re-use pending blocks in AuRa * Use reseal_min_period to prevent too frequent update_sealing. * Fix log to contain hash not sender. * Optimize local transactions. * Fix aura tests. * Update locks comments. * Get rid of unsafe Sync impl. * Review fixes. * Remove excessive matches. * Fix compilation errors. * Use new pool in private transactions. * Fix private-tx test. * Fix secret store tests. * Actually use gas_floor_target * Fix config tests. * Fix pool tests. * Address grumbles.
2018-04-13 17:34:27 +02:00
pub fn get<G: FnOnce(PriceInfo) + Sync + Send + 'static>(&self, set_price: G) {
Private transactions integration pr (#6422) * Private transaction message added * Empty line removed * Private transactions logic removed from client into the separate module * Fixed compilation after merge with head * Signed private transaction message added as well * Comments after the review fixed * Private tx execution * Test update * Renamed some methods * Fixed some tests * Reverted submodules * Fixed build * Private transaction message added * Empty line removed * Private transactions logic removed from client into the separate module * Fixed compilation after merge with head * Signed private transaction message added as well * Comments after the review fixed * Encrypted private transaction message and signed reply added * Private tx execution * Test update * Main scenario completed * Merged with the latest head * Private transactions API * Comments after review fixed * Parameters for private transactions added to parity arguments * New files added * New API methods added * Do not process packets from unconfirmed peers * Merge with ptm_ss branch * Encryption and permissioning with key server added * Fixed compilation after merge * Version of Parity protocol incremented in order to support private transactions * Doc strings for constants added * Proper format for doc string added * fixed some encryptor.rs grumbles * Private transactions functionality moved to the separate crate * Refactoring in order to remove late initialisation * Tests fixed after moving to the separate crate * Fetch method removed * Sync test helpers refactored * Interaction with encryptor refactored * Contract address retrieving via substate removed * Sensible gas limit for private transactions implemented * New private contract with nonces added * Parsing of the response from key server fixed * Build fixed after the merge, native contracts removed * Crate renamed * Tests moved to the separate directory * Handling of errors reworked in order to use error chain * Encodable macro added, new constructor replaced with default * Native ethabi usage removed * Couple conversions optimized * Interactions with client reworked * Errors omitting removed * Fix after merge * Fix after the merge * private transactions improvements in progress * private_transactions -> ethcore/private-tx * making private transactions more idiomatic * private-tx encryptor uses shared FetchClient and is more idiomatic * removed redundant tests, moved integration tests to tests/ dir * fixed failing service test * reenable add_notify on private tx provider * removed private_tx tests from sync module * removed commented out code * Use plain password instead of unlocking account manager * remove dead code * Link to the contract changed * Transaction signature chain replay protection module created * Redundant type conversion removed * Contract address returned by private provider * Test fixed * Addressing grumbles in PrivateTransactions (#8249) * Tiny fixes part 1. * A bunch of additional comments and todos. * Fix ethsync tests. * resolved merge conflicts * final private tx pr (#8318) * added cli option that enables private transactions * fixed failing test * fixed failing test * fixed failing test * fixed failing test
2018-04-09 16:14:33 +02:00
let future = self.fetch.get(&self.api_endpoint, fetch::Abort::default())
.from_err()
.and_then(|response| {
2017-08-04 13:39:57 +02:00
if !response.is_success() {
let s = Error::StatusCode(response.status().canonical_reason().unwrap_or("unknown"));
return Either::A(future::err(s));
2017-08-04 13:39:57 +02:00
}
Either::B(response.concat2().from_err())
})
.and_then(move |body| {
let body_str = str::from_utf8(&body).ok();
let value: Option<Value> = body_str.and_then(|s| serde_json::from_str(s).ok());
2017-08-04 13:06:01 +02:00
2017-08-04 13:39:57 +02:00
let ethusd = value
.as_ref()
.and_then(|value| value.pointer("/result/ethusd"))
.and_then(|obj| obj.as_str())
.and_then(|s| s.parse().ok());
match ethusd {
Some(ethusd) => {
set_price(PriceInfo { ethusd });
Ok(())
},
None => Err(Error::UnexpectedResponse(body_str.map(From::from))),
2017-08-04 13:39:57 +02:00
}
2017-08-04 13:06:01 +02:00
})
.map_err(|err| {
warn!("Failed to auto-update latest ETH price: {:?}", err);
});
self.pool.spawn(future)
2017-08-04 13:06:01 +02:00
}
}
#[cfg(test)]
mod test {
use std::sync::Arc;
use parity_runtime::{Runtime, Executor};
2017-08-04 13:06:01 +02:00
use Client;
use std::sync::atomic::{AtomicBool, Ordering};
use fake_fetch::FakeFetch;
2017-08-04 13:06:01 +02:00
fn price_info_ok(response: &str, executor: Executor) -> Client<FakeFetch<String>> {
Client::new(FakeFetch::new(Some(response.to_owned())), executor)
2017-08-04 13:06:01 +02:00
}
fn price_info_not_found(executor: Executor) -> Client<FakeFetch<String>> {
Client::new(FakeFetch::new(None::<String>), executor)
2017-08-04 13:06:01 +02:00
}
#[test]
fn should_get_price_info() {
let runtime = Runtime::with_thread_count(1);
2017-08-04 13:06:01 +02:00
// given
let response = r#"{
"status": "1",
"message": "OK",
"result": {
"ethbtc": "0.0891",
"ethbtc_timestamp": "1499894236",
"ethusd": "209.55",
"ethusd_timestamp": "1499894229"
}
}"#;
let price_info = price_info_ok(response, runtime.executor());
2017-08-04 13:06:01 +02:00
// when
price_info.get(|price| {
// then
assert_eq!(price.ethusd, 209.55);
});
}
#[test]
fn should_not_call_set_price_if_response_is_malformed() {
let runtime = Runtime::with_thread_count(1);
2017-08-04 13:06:01 +02:00
// given
let response = "{}";
let price_info = price_info_ok(response, runtime.executor());
2017-08-04 13:06:01 +02:00
let b = Arc::new(AtomicBool::new(false));
// when
let bb = b.clone();
price_info.get(move |_| {
bb.store(true, Ordering::Relaxed);
});
// then
assert_eq!(b.load(Ordering::Relaxed), false);
}
#[test]
fn should_not_call_set_price_if_response_is_invalid() {
let runtime = Runtime::with_thread_count(1);
2017-08-04 13:06:01 +02:00
// given
let price_info = price_info_not_found(runtime.executor());
2017-08-04 13:06:01 +02:00
let b = Arc::new(AtomicBool::new(false));
// when
let bb = b.clone();
price_info.get(move |_| {
bb.store(true, Ordering::Relaxed);
});
// then
assert_eq!(b.load(Ordering::Relaxed), false);
}
}