2018-06-04 10:19:50 +02:00
|
|
|
// Copyright 2015-2018 Parity Technologies (UK) Ltd.
|
2016-12-11 19:15:58 +01:00
|
|
|
// 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 <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
//! Hash-addressed content resolver & fetcher.
|
|
|
|
|
|
|
|
use std::{io, fs};
|
2016-12-22 18:26:39 +01:00
|
|
|
use std::io::Write;
|
2016-12-11 19:15:58 +01:00
|
|
|
use std::sync::Arc;
|
|
|
|
use std::path::PathBuf;
|
|
|
|
|
2017-08-31 11:35:41 +02:00
|
|
|
use hash::keccak_buffer;
|
2018-03-14 13:40:54 +01:00
|
|
|
use fetch::{self, Fetch};
|
2018-02-09 09:32:06 +01:00
|
|
|
use futures::{Future, IntoFuture};
|
2018-10-22 09:40:50 +02:00
|
|
|
use parity_runtime::Executor;
|
2018-03-12 21:46:27 +01:00
|
|
|
use urlhint::{URLHintContract, URLHint, URLHintResult};
|
|
|
|
use registrar::{RegistrarClient, Asynchronous};
|
2018-01-10 13:35:18 +01:00
|
|
|
use ethereum_types::H256;
|
2016-12-11 19:15:58 +01:00
|
|
|
|
|
|
|
/// API for fetching by hash.
|
|
|
|
pub trait HashFetch: Send + Sync + 'static {
|
|
|
|
/// Fetch hash-addressed content.
|
|
|
|
/// Parameters:
|
|
|
|
/// 1. `hash` - content hash
|
|
|
|
/// 2. `on_done` - callback function invoked when the content is ready (or there was error during fetch)
|
|
|
|
///
|
|
|
|
/// This function may fail immediately when fetch cannot be initialized or content cannot be resolved.
|
2018-03-14 13:40:54 +01:00
|
|
|
fn fetch(&self, hash: H256, abort: fetch::Abort, on_done: Box<Fn(Result<PathBuf, Error>) + Send>);
|
2016-12-11 19:15:58 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Hash-fetching error.
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub enum Error {
|
|
|
|
/// Hash could not be resolved to a valid content address.
|
|
|
|
NoResolution,
|
|
|
|
/// Downloaded content hash does not match.
|
|
|
|
HashMismatch {
|
|
|
|
/// Expected hash
|
|
|
|
expected: H256,
|
|
|
|
/// Computed hash
|
|
|
|
got: H256,
|
|
|
|
},
|
2017-02-20 16:30:14 +01:00
|
|
|
/// Server didn't respond with OK status.
|
|
|
|
InvalidStatus,
|
2016-12-11 19:15:58 +01:00
|
|
|
/// IO Error while validating hash.
|
|
|
|
IO(io::Error),
|
|
|
|
/// Error during fetch.
|
2018-03-14 13:40:54 +01:00
|
|
|
Fetch(fetch::Error),
|
2016-12-11 19:15:58 +01:00
|
|
|
}
|
|
|
|
|
2017-02-20 16:30:14 +01:00
|
|
|
#[cfg(test)]
|
|
|
|
impl PartialEq for Error {
|
|
|
|
fn eq(&self, other: &Self) -> bool {
|
|
|
|
use Error::*;
|
|
|
|
match (self, other) {
|
|
|
|
(&HashMismatch { expected, got }, &HashMismatch { expected: e, got: g }) => {
|
|
|
|
expected == e && got == g
|
|
|
|
},
|
|
|
|
(&NoResolution, &NoResolution) => true,
|
|
|
|
(&InvalidStatus, &InvalidStatus) => true,
|
|
|
|
(&IO(_), &IO(_)) => true,
|
|
|
|
(&Fetch(_), &Fetch(_)) => true,
|
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-14 13:40:54 +01:00
|
|
|
impl From<fetch::Error> for Error {
|
|
|
|
fn from(error: fetch::Error) -> Self {
|
2016-12-11 19:15:58 +01:00
|
|
|
Error::Fetch(error)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<io::Error> for Error {
|
|
|
|
fn from(error: io::Error) -> Self {
|
|
|
|
Error::IO(error)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-14 13:40:54 +01:00
|
|
|
fn validate_hash(path: PathBuf, hash: H256, body: fetch::BodyReader) -> Result<PathBuf, Error> {
|
2017-05-18 12:44:09 +02:00
|
|
|
// Read the response
|
2018-03-14 13:40:54 +01:00
|
|
|
let mut reader = io::BufReader::new(body);
|
2017-05-18 12:44:09 +02:00
|
|
|
let mut writer = io::BufWriter::new(fs::File::create(&path)?);
|
|
|
|
io::copy(&mut reader, &mut writer)?;
|
|
|
|
writer.flush()?;
|
|
|
|
|
|
|
|
// And validate the hash
|
|
|
|
let mut file_reader = io::BufReader::new(fs::File::open(&path)?);
|
2017-08-31 11:35:41 +02:00
|
|
|
let content_hash = keccak_buffer(&mut file_reader)?;
|
2017-05-18 12:44:09 +02:00
|
|
|
if content_hash != hash {
|
|
|
|
Err(Error::HashMismatch{ got: content_hash, expected: hash })
|
|
|
|
} else {
|
|
|
|
Ok(path)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-11 19:15:58 +01:00
|
|
|
/// Default Hash-fetching client using on-chain contract to resolve hashes to URLs.
|
2018-03-14 13:40:54 +01:00
|
|
|
pub struct Client<F: Fetch + 'static = fetch::Client> {
|
2016-12-11 19:15:58 +01:00
|
|
|
contract: URLHintContract,
|
2016-12-22 18:26:39 +01:00
|
|
|
fetch: F,
|
2018-10-22 09:40:50 +02:00
|
|
|
executor: Executor,
|
2017-04-12 15:04:53 +02:00
|
|
|
random_path: Arc<Fn() -> PathBuf + Sync + Send>,
|
2016-12-11 19:15:58 +01:00
|
|
|
}
|
|
|
|
|
2016-12-22 18:26:39 +01:00
|
|
|
impl<F: Fetch + 'static> Client<F> {
|
|
|
|
/// Creates new instance of the `Client` given on-chain contract client, fetch service and task runner.
|
2018-10-22 09:40:50 +02:00
|
|
|
pub fn with_fetch(contract: Arc<RegistrarClient<Call=Asynchronous>>, fetch: F, executor: Executor) -> Self {
|
2016-12-11 19:15:58 +01:00
|
|
|
Client {
|
|
|
|
contract: URLHintContract::new(contract),
|
2016-12-22 18:26:39 +01:00
|
|
|
fetch: fetch,
|
2018-10-22 09:40:50 +02:00
|
|
|
executor: executor,
|
2017-04-12 15:04:53 +02:00
|
|
|
random_path: Arc::new(random_temp_path),
|
2016-12-11 19:15:58 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-22 18:26:39 +01:00
|
|
|
impl<F: Fetch + 'static> HashFetch for Client<F> {
|
2018-03-14 13:40:54 +01:00
|
|
|
fn fetch(&self, hash: H256, abort: fetch::Abort, on_done: Box<Fn(Result<PathBuf, Error>) + Send>) {
|
2016-12-11 19:15:58 +01:00
|
|
|
debug!(target: "fetch", "Fetching: {:?}", hash);
|
|
|
|
|
2017-05-18 12:44:09 +02:00
|
|
|
let random_path = self.random_path.clone();
|
|
|
|
let remote_fetch = self.fetch.clone();
|
2018-02-09 09:32:06 +01:00
|
|
|
let future = self.contract.resolve(hash)
|
2017-05-18 12:44:09 +02:00
|
|
|
.map_err(|e| { warn!("Error resolving URL: {}", e); Error::NoResolution })
|
|
|
|
.and_then(|maybe_url| maybe_url.ok_or(Error::NoResolution))
|
|
|
|
.map(|content| match content {
|
|
|
|
URLHintResult::Dapp(dapp) => {
|
|
|
|
dapp.url()
|
|
|
|
},
|
2017-12-13 07:56:35 +01:00
|
|
|
URLHintResult::GithubDapp(content) => {
|
|
|
|
content.url
|
|
|
|
},
|
2017-05-18 12:44:09 +02:00
|
|
|
URLHintResult::Content(content) => {
|
|
|
|
content.url
|
|
|
|
},
|
|
|
|
})
|
2018-02-09 09:32:06 +01:00
|
|
|
.into_future()
|
2017-05-18 12:44:09 +02:00
|
|
|
.and_then(move |url| {
|
|
|
|
debug!(target: "fetch", "Resolved {:?} to {:?}. Fetching...", hash, url);
|
2018-04-09 16:14:33 +02:00
|
|
|
remote_fetch.get(&url, abort).from_err()
|
2018-03-14 13:40:54 +01:00
|
|
|
})
|
|
|
|
.and_then(move |response| {
|
|
|
|
if !response.is_success() {
|
|
|
|
Err(Error::InvalidStatus)
|
|
|
|
} else {
|
|
|
|
Ok(response)
|
|
|
|
}
|
2017-05-18 12:44:09 +02:00
|
|
|
})
|
2018-10-22 09:40:50 +02:00
|
|
|
.and_then(move |response| {
|
2018-03-14 13:40:54 +01:00
|
|
|
debug!(target: "fetch", "Content fetched, validating hash ({:?})", hash);
|
|
|
|
let path = random_path();
|
|
|
|
let res = validate_hash(path.clone(), hash, fetch::BodyReader::new(response));
|
|
|
|
if let Err(ref err) = res {
|
|
|
|
trace!(target: "fetch", "Error: {:?}", err);
|
|
|
|
// Remove temporary file in case of error
|
|
|
|
let _ = fs::remove_file(&path);
|
|
|
|
}
|
|
|
|
res
|
2018-10-22 09:40:50 +02:00
|
|
|
})
|
2017-05-18 12:44:09 +02:00
|
|
|
.then(move |res| { on_done(res); Ok(()) as Result<(), ()> });
|
|
|
|
|
2018-10-22 09:40:50 +02:00
|
|
|
self.executor.spawn(future);
|
2016-12-11 19:15:58 +01:00
|
|
|
}
|
|
|
|
}
|
2016-12-22 18:26:39 +01:00
|
|
|
|
|
|
|
fn random_temp_path() -> PathBuf {
|
|
|
|
use ::rand::Rng;
|
|
|
|
use ::std::env;
|
|
|
|
|
|
|
|
let mut rng = ::rand::OsRng::new().expect("Reliable random source is required to work.");
|
|
|
|
let file: String = rng.gen_ascii_chars().take(12).collect();
|
|
|
|
|
|
|
|
let mut path = env::temp_dir();
|
|
|
|
path.push(file);
|
|
|
|
path
|
|
|
|
}
|
2017-02-20 16:30:14 +01:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2018-04-11 11:59:04 +02:00
|
|
|
use fake_fetch::FakeFetch;
|
2017-07-29 17:12:07 +02:00
|
|
|
use rustc_hex::FromHex;
|
2017-02-20 16:30:14 +01:00
|
|
|
use std::sync::{Arc, mpsc};
|
2017-09-02 20:09:13 +02:00
|
|
|
use parking_lot::Mutex;
|
2018-10-22 09:40:50 +02:00
|
|
|
use parity_runtime::Executor;
|
2017-02-20 16:30:14 +01:00
|
|
|
use urlhint::tests::{FakeRegistrar, URLHINT};
|
2017-04-12 15:04:53 +02:00
|
|
|
use super::{Error, Client, HashFetch, random_temp_path};
|
2017-02-20 16:30:14 +01:00
|
|
|
|
|
|
|
fn registrar() -> FakeRegistrar {
|
|
|
|
let mut registrar = FakeRegistrar::new();
|
|
|
|
registrar.responses = Mutex::new(vec![
|
|
|
|
Ok(format!("000000000000000000000000{}", URLHINT).from_hex().unwrap()),
|
2017-05-18 12:44:09 +02:00
|
|
|
Ok("00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000deadcafebeefbeefcafedeaddeedfeedffffffff000000000000000000000000000000000000000000000000000000000000003c68747470733a2f2f7061726974792e696f2f6173736574732f696d616765732f657468636f72652d626c61636b2d686f72697a6f6e74616c2e706e6700000000".from_hex().unwrap()),
|
2017-02-20 16:30:14 +01:00
|
|
|
]);
|
|
|
|
registrar
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn should_return_error_if_hash_not_found() {
|
|
|
|
// given
|
|
|
|
let contract = Arc::new(FakeRegistrar::new());
|
2018-04-11 11:59:04 +02:00
|
|
|
let fetch = FakeFetch::new(None::<usize>);
|
2018-10-22 09:40:50 +02:00
|
|
|
let client = Client::with_fetch(contract.clone(), fetch, Executor::new_sync());
|
2017-02-20 16:30:14 +01:00
|
|
|
|
|
|
|
// when
|
|
|
|
let (tx, rx) = mpsc::channel();
|
2018-03-14 13:40:54 +01:00
|
|
|
client.fetch(2.into(), Default::default(), Box::new(move |result| {
|
2017-02-20 16:30:14 +01:00
|
|
|
tx.send(result).unwrap();
|
|
|
|
}));
|
|
|
|
|
|
|
|
// then
|
|
|
|
let result = rx.recv().unwrap();
|
|
|
|
assert_eq!(result.unwrap_err(), Error::NoResolution);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn should_return_error_if_response_is_not_successful() {
|
|
|
|
// given
|
|
|
|
let registrar = Arc::new(registrar());
|
2018-04-11 11:59:04 +02:00
|
|
|
let fetch = FakeFetch::new(None::<usize>);
|
2018-10-22 09:40:50 +02:00
|
|
|
let client = Client::with_fetch(registrar.clone(), fetch, Executor::new_sync());
|
2017-02-20 16:30:14 +01:00
|
|
|
|
|
|
|
// when
|
|
|
|
let (tx, rx) = mpsc::channel();
|
2018-03-14 13:40:54 +01:00
|
|
|
client.fetch(2.into(), Default::default(), Box::new(move |result| {
|
2017-02-20 16:30:14 +01:00
|
|
|
tx.send(result).unwrap();
|
|
|
|
}));
|
|
|
|
|
|
|
|
// then
|
|
|
|
let result = rx.recv().unwrap();
|
|
|
|
assert_eq!(result.unwrap_err(), Error::InvalidStatus);
|
|
|
|
}
|
2017-04-12 15:04:53 +02:00
|
|
|
|
2017-02-20 16:30:14 +01:00
|
|
|
#[test]
|
|
|
|
fn should_return_hash_mismatch() {
|
|
|
|
// given
|
|
|
|
let registrar = Arc::new(registrar());
|
2018-04-11 11:59:04 +02:00
|
|
|
let fetch = FakeFetch::new(Some(1));
|
2018-10-22 09:40:50 +02:00
|
|
|
let mut client = Client::with_fetch(registrar.clone(), fetch, Executor::new_sync());
|
2017-04-12 15:04:53 +02:00
|
|
|
let path = random_temp_path();
|
|
|
|
let path2 = path.clone();
|
|
|
|
client.random_path = Arc::new(move || path2.clone());
|
2017-02-20 16:30:14 +01:00
|
|
|
|
|
|
|
// when
|
|
|
|
let (tx, rx) = mpsc::channel();
|
2018-03-14 13:40:54 +01:00
|
|
|
client.fetch(2.into(), Default::default(), Box::new(move |result| {
|
2017-02-20 16:30:14 +01:00
|
|
|
tx.send(result).unwrap();
|
|
|
|
}));
|
|
|
|
|
|
|
|
// then
|
|
|
|
let result = rx.recv().unwrap();
|
2018-04-11 11:59:04 +02:00
|
|
|
let hash = "0x2be00befcf008bc0e7d9cdefc194db9c75352e8632f48498b5a6bfce9f02c88e".into();
|
2017-02-20 16:30:14 +01:00
|
|
|
assert_eq!(result.unwrap_err(), Error::HashMismatch { expected: 2.into(), got: hash });
|
2017-04-12 15:04:53 +02:00
|
|
|
assert!(!path.exists(), "Temporary file should be removed.");
|
2017-02-20 16:30:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn should_return_path_if_hash_matches() {
|
|
|
|
// given
|
|
|
|
let registrar = Arc::new(registrar());
|
2018-04-11 11:59:04 +02:00
|
|
|
let fetch = FakeFetch::new(Some(1));
|
2018-10-22 09:40:50 +02:00
|
|
|
let client = Client::with_fetch(registrar.clone(), fetch, Executor::new_sync());
|
2017-02-20 16:30:14 +01:00
|
|
|
|
|
|
|
// when
|
|
|
|
let (tx, rx) = mpsc::channel();
|
2018-04-11 11:59:04 +02:00
|
|
|
client.fetch("0x2be00befcf008bc0e7d9cdefc194db9c75352e8632f48498b5a6bfce9f02c88e".into(),
|
2018-03-14 13:40:54 +01:00
|
|
|
Default::default(),
|
|
|
|
Box::new(move |result| { tx.send(result).unwrap(); }));
|
2017-02-20 16:30:14 +01:00
|
|
|
|
|
|
|
// then
|
|
|
|
let result = rx.recv().unwrap();
|
|
|
|
assert!(result.is_ok(), "Should return path, got: {:?}", result);
|
|
|
|
}
|
|
|
|
}
|