Skip to content
This repository has been archived by the owner on Nov 6, 2020. It is now read-only.

Opening local dapp #4041

Merged
merged 3 commits into from
Jan 6, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 24 additions & 9 deletions dapps/src/apps/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,16 @@ struct LocalDapp {
info: EndpointInfo,
}

fn local_dapp(name: String, path: PathBuf) -> LocalDapp {
// try to get manifest file
let info = read_manifest(&name, path.clone());
LocalDapp {
id: name,
path: path,
info: info,
}
}

fn local_dapps(dapps_path: String) -> Vec<LocalDapp> {
let files = fs::read_dir(dapps_path.as_str());
if let Err(e) = files {
Expand Down Expand Up @@ -59,15 +69,7 @@ fn local_dapps(dapps_path: String) -> Vec<LocalDapp> {
}
m.ok()
})
.map(|(name, path)| {
// try to get manifest file
let info = read_manifest(&name, path.clone());
LocalDapp {
id: name,
path: path,
info: info,
}
})
.map(|(name, path)| local_dapp(name, path))
.collect()
}

Expand Down Expand Up @@ -97,6 +99,19 @@ fn read_manifest(name: &str, mut path: PathBuf) -> EndpointInfo {
})
}

pub fn local_endpoint(path: String, signer_address: Option<(String, u16)>) -> Option<(String, Box<LocalPageEndpoint>)> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should accept path: PathBuf

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe even local_endpoint<P: AsRef<Path>>(path: P, ...) { ... }

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

let path = PathBuf::from(path);
path.canonicalize().ok().and_then(|path| {
let name = path.file_name().and_then(|name| name.to_str());
name.map(|name| {
let dapp = local_dapp(name.into(), path.clone());
(dapp.id, Box::new(LocalPageEndpoint::new(
dapp.path, dapp.info, PageCache::Disabled, signer_address.clone())
))
})
})
}

pub fn local_endpoints(dapps_path: String, signer_address: Option<(String, u16)>) -> Endpoints {
let mut pages = Endpoints::new();
for dapp in local_dapps(dapps_path) {
Expand Down
8 changes: 8 additions & 0 deletions dapps/src/apps/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,21 @@ pub fn utils() -> Box<Endpoint> {

pub fn all_endpoints<F: Fetch>(
dapps_path: String,
extra_dapps: Vec<String>,
signer_address: Option<(String, u16)>,
web_proxy_tokens: Arc<WebProxyTokens>,
remote: Remote,
fetch: F,
) -> Endpoints {
// fetch fs dapps at first to avoid overwriting builtins
let mut pages = fs::local_endpoints(dapps_path, signer_address.clone());
for path in extra_dapps {
if let Some((id, endpoint)) = fs::local_endpoint(path.clone(), signer_address.clone()) {
pages.insert(id, endpoint);
} else {
warn!(target: "dapps", "Ingoring invalid dapp at {}", path);
}
}

// NOTE [ToDr] Dapps will be currently embeded on 8180
insert::<parity_ui::App>(&mut pages, "ui", Embeddable::Yes(signer_address.clone()));
Expand Down
21 changes: 20 additions & 1 deletion dapps/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ impl<F> WebProxyTokens for F where F: Fn(String) -> bool + Send + Sync {
/// Webapps HTTP+RPC server build.
pub struct ServerBuilder<T: Fetch = FetchClient> {
dapps_path: String,
extra_dapps: Vec<String>,
handler: Arc<IoHandler>,
registrar: Arc<ContractClient>,
sync_status: Arc<SyncStatus>,
Expand All @@ -144,6 +145,7 @@ impl ServerBuilder {
pub fn new(dapps_path: String, registrar: Arc<ContractClient>, remote: Remote) -> Self {
ServerBuilder {
dapps_path: dapps_path,
extra_dapps: vec![],
handler: Arc::new(IoHandler::new()),
registrar: registrar,
sync_status: Arc::new(|| false),
Expand All @@ -160,6 +162,7 @@ impl<T: Fetch> ServerBuilder<T> {
pub fn fetch<X: Fetch>(self, fetch: X) -> ServerBuilder<X> {
ServerBuilder {
dapps_path: self.dapps_path,
extra_dapps: vec![],
handler: self.handler,
registrar: self.registrar,
sync_status: self.sync_status,
Expand Down Expand Up @@ -188,6 +191,12 @@ impl<T: Fetch> ServerBuilder<T> {
self
}

/// Change extra dapps paths (apart from `dapps_path`)
pub fn extra_dapps(mut self, extra_dapps: Vec<String>) -> Self {
self.extra_dapps = extra_dapps;
self
}

/// Asynchronously start server with no authentication,
/// returns result with `Server` handle on success or an error.
pub fn start_unsecured_http(self, addr: &SocketAddr, hosts: Option<Vec<String>>) -> Result<Server, ServerError> {
Expand All @@ -197,6 +206,7 @@ impl<T: Fetch> ServerBuilder<T> {
NoAuth,
self.handler.clone(),
self.dapps_path.clone(),
self.extra_dapps.clone(),
self.signer_address.clone(),
self.registrar.clone(),
self.sync_status.clone(),
Expand All @@ -215,6 +225,7 @@ impl<T: Fetch> ServerBuilder<T> {
HttpBasicAuth::single_user(username, password),
self.handler.clone(),
self.dapps_path.clone(),
self.extra_dapps.clone(),
self.signer_address.clone(),
self.registrar.clone(),
self.sync_status.clone(),
Expand Down Expand Up @@ -271,6 +282,7 @@ impl Server {
authorization: A,
handler: Arc<IoHandler>,
dapps_path: String,
extra_dapps: Vec<String>,
signer_address: Option<(String, u16)>,
registrar: Arc<ContractClient>,
sync_status: Arc<SyncStatus>,
Expand All @@ -287,7 +299,14 @@ impl Server {
remote.clone(),
fetch.clone(),
));
let endpoints = Arc::new(apps::all_endpoints(dapps_path, signer_address.clone(), web_proxy_tokens, remote.clone(), fetch.clone()));
let endpoints = Arc::new(apps::all_endpoints(
dapps_path,
extra_dapps,
signer_address.clone(),
web_proxy_tokens,
remote.clone(),
fetch.clone(),
));
let cors_domains = Self::cors_domains(signer_address.clone());

let special = Arc::new({
Expand Down
2 changes: 2 additions & 0 deletions parity/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ usage! {
cmd_snapshot: bool,
cmd_restore: bool,
cmd_ui: bool,
cmd_dapp: bool,
cmd_tools: bool,
cmd_hash: bool,
cmd_kill: bool,
Expand Down Expand Up @@ -525,6 +526,7 @@ mod tests {
cmd_snapshot: false,
cmd_restore: false,
cmd_ui: false,
cmd_dapp: false,
cmd_tools: false,
cmd_hash: false,
cmd_db: false,
Expand Down
13 changes: 7 additions & 6 deletions parity/cli/usage.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Parity. Ethereum Client.
Usage:
parity [options]
parity ui [options]
parity dapp <path> [options]
parity daemon <pid-file> [options]
parity account (new | list ) [options]
parity account import <path>... [options]
Expand Down Expand Up @@ -36,15 +37,15 @@ Operating Options:
(default: {flag_mode_alarm}).
--auto-update SET Set a releases set to automatically update and
install.
all - All updates in the our release track.
all - All updates in the our release track.
critical - Only consensus/security updates.
none - No updates will be auto-installed.
none - No updates will be auto-installed.
(default: {flag_auto_update}).
--release-track TRACK Set which release track we should use for updates.
stable - Stable releases.
beta - Beta releases.
stable - Stable releases.
beta - Beta releases.
nightly - Nightly releases (unstable).
testing - Testing releases (do not use).
testing - Testing releases (do not use).
current - Whatever track this executable was
released on (default: {flag_release_track}).
--no-download Normally new releases will be downloaded ready for
Expand Down Expand Up @@ -362,7 +363,7 @@ Legacy Options:
--cache MB Equivalent to --cache-size MB.

Internal Options:
--can-restart Executable will auto-restart if exiting with 69.
--can-restart Executable will auto-restart if exiting with 69.

Miscellaneous Options:
-c --config CONFIG Specify a filename containing a configuration file.
Expand Down
42 changes: 39 additions & 3 deletions parity/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
use std::time::Duration;
use std::io::Read;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::cmp::max;
use cli::{Args, ArgsError};
use util::{Hashable, U256, Uint, Bytes, version_data, Secret, Address};
Expand Down Expand Up @@ -335,6 +335,7 @@ impl Configuration {
net_settings: self.network_settings(),
dapps_conf: dapps_conf,
signer_conf: signer_conf,
dapp: self.dapp_to_open()?,
ui: self.args.cmd_ui,
name: self.args.flag_identity,
custom_bootnodes: self.args.flag_bootnodes.is_some(),
Expand Down Expand Up @@ -508,7 +509,25 @@ impl Configuration {
user: self.args.flag_dapps_user.clone(),
pass: self.args.flag_dapps_pass.clone(),
dapps_path: self.directories().dapps,
extra_dapps: if self.args.cmd_dapp {
self.args.arg_path.clone()
} else {
vec![]
},
}
}

fn dapp_to_open(&self) -> Result<Option<String>, String> {
if !self.args.cmd_dapp {
return Ok(None);
}
let path = self.args.arg_path.get(0).map(String::as_str).unwrap_or(".");
let path = Path::new(path).canonicalize()
.map_err(|e| format!("Invalid path: {}. Error: {:?}", path, e))?;
let name = path.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| "Root path is not supported.".to_owned())?;
Ok(Some(name.into()))
}

fn gas_pricer_config(&self) -> Result<GasPricerConfig, String> {
Expand Down Expand Up @@ -690,15 +709,15 @@ impl Configuration {
"none" => UpdateFilter::None,
"critical" => UpdateFilter::Critical,
"all" => UpdateFilter::All,
_ => return Err("Invalid value for `--auto-update`. See `--help` for more information.".into()),
_ => return Err("Invalid value for `--auto-update`. See `--help` for more information.".into()),
},
track: match self.args.flag_release_track.as_ref() {
"stable" => ReleaseTrack::Stable,
"beta" => ReleaseTrack::Beta,
"nightly" => ReleaseTrack::Nightly,
"testing" => ReleaseTrack::Testing,
"current" => ReleaseTrack::Unknown,
_ => return Err("Invalid value for `--releases-track`. See `--help` for more information.".into()),
_ => return Err("Invalid value for `--releases-track`. See `--help` for more information.".into()),
},
path: default_hypervisor_path(),
})
Expand Down Expand Up @@ -1025,6 +1044,7 @@ mod tests {
dapps_conf: Default::default(),
signer_conf: Default::default(),
ui: false,
dapp: None,
name: "".into(),
custom_bootnodes: false,
fat_db: Default::default(),
Expand Down Expand Up @@ -1219,6 +1239,22 @@ mod tests {
});
}

#[test]
fn should_parse_dapp_opening() {
// given
let temp = RandomTempPath::new();
let name = temp.file_name().unwrap().to_str().unwrap();
create_dir(temp.as_str().to_owned()).unwrap();

// when
let conf0 = parse(&["parity", "dapp", temp.to_str().unwrap()]);

// then
assert_eq!(conf0.dapp_to_open(), Ok(Some(name.into())));
let extra_dapps = conf0.dapps_config().extra_dapps;
assert_eq!(extra_dapps, vec![temp.to_str().unwrap().to_owned()]);
}

#[test]
fn should_not_bail_on_empty_line_in_reserved_peers() {
let temp = RandomTempPath::new();
Expand Down
14 changes: 13 additions & 1 deletion parity/dapps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pub struct Configuration {
pub user: Option<String>,
pub pass: Option<String>,
pub dapps_path: String,
pub extra_dapps: Vec<String>,
}

impl Default for Configuration {
Expand All @@ -47,6 +48,7 @@ impl Default for Configuration {
user: None,
pass: None,
dapps_path: replace_home(&data_dir, "$BASE/dapps"),
extra_dapps: vec![],
}
}
}
Expand Down Expand Up @@ -80,7 +82,14 @@ pub fn new(configuration: Configuration, deps: Dependencies) -> Result<Option<We
(username.to_owned(), password)
});

Ok(Some(setup_dapps_server(deps, configuration.dapps_path, &addr, configuration.hosts, auth)?))
Ok(Some(setup_dapps_server(
deps,
configuration.dapps_path,
configuration.extra_dapps,
&addr,
configuration.hosts,
auth
)?))
}

pub use self::server::WebappServer;
Expand All @@ -95,6 +104,7 @@ mod server {
pub fn setup_dapps_server(
_deps: Dependencies,
_dapps_path: String,
_extra_dapps: Vec<String>,
_url: &SocketAddr,
_allowed_hosts: Option<Vec<String>>,
_auth: Option<(String, String)>,
Expand Down Expand Up @@ -123,6 +133,7 @@ mod server {
pub fn setup_dapps_server(
deps: Dependencies,
dapps_path: String,
extra_dapps: Vec<String>,
url: &SocketAddr,
allowed_hosts: Option<Vec<String>>,
auth: Option<(String, String)>,
Expand All @@ -141,6 +152,7 @@ mod server {
.fetch(deps.fetch.clone())
.sync_status(Arc::new(move || is_major_importing(Some(sync.status().state), client.queue_info())))
.web_proxy_tokens(Arc::new(move |token| signer.is_valid_web_proxy_access_token(&token)))
.extra_dapps(extra_dapps)
.signer_address(deps.signer.address());

let server = rpc_apis::setup_rpc(server, deps.apis.clone(), rpc_apis::ApiSet::UnsafeContext);
Expand Down
16 changes: 16 additions & 0 deletions parity/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ pub struct RunCmd {
pub net_settings: NetworkSettings,
pub dapps_conf: dapps::Configuration,
pub signer_conf: signer::Configuration,
pub dapp: Option<String>,
pub ui: bool,
pub name: String,
pub custom_bootnodes: bool,
Expand All @@ -117,6 +118,17 @@ pub fn open_ui(dapps_conf: &dapps::Configuration, signer_conf: &signer::Configur
Ok(())
}

pub fn open_dapp(dapps_conf: &dapps::Configuration, dapp: &str) -> Result<(), String> {
if !dapps_conf.enabled {
return Err("Cannot use DAPP command with Dapps turned off.".into())
}

let url = format!("http://{}:{}/{}/", dapps_conf.interface, dapps_conf.port, dapp);
url::open(&url);
Ok(())
}


pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> Result<bool, String> {
if cmd.ui && cmd.dapps_conf.enabled {
// Check if Parity is already running
Expand Down Expand Up @@ -428,6 +440,10 @@ pub fn execute(cmd: RunCmd, can_restart: bool, logger: Arc<RotatingLogger>) -> R
open_ui(&cmd.dapps_conf, &cmd.signer_conf)?;
}

if let Some(dapp) = cmd.dapp {
open_dapp(&cmd.dapps_conf, &dapp)?;
}

// Handle exit
let restart = wait_for_exit(
panic_handler,
Expand Down