Merge branch 'master' into client-provider
This commit is contained in:
commit
3c7533831e
2
Cargo.lock
generated
2
Cargo.lock
generated
@ -1250,7 +1250,7 @@ dependencies = [
|
|||||||
[[package]]
|
[[package]]
|
||||||
name = "parity-ui-precompiled"
|
name = "parity-ui-precompiled"
|
||||||
version = "1.4.0"
|
version = "1.4.0"
|
||||||
source = "git+https://github.com/ethcore/js-precompiled.git#90bee2d692c71301ad7266d2d9667cba1a93e9f6"
|
source = "git+https://github.com/ethcore/js-precompiled.git#bf33dd4aabd2adb2178576db5a4d23b8902d39b8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"parity-dapps-glue 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
"parity-dapps-glue 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
]
|
]
|
||||||
|
@ -47,7 +47,7 @@ pub struct ContentFetcher<R: URLHint = URLHintContract> {
|
|||||||
resolver: R,
|
resolver: R,
|
||||||
cache: Arc<Mutex<ContentCache>>,
|
cache: Arc<Mutex<ContentCache>>,
|
||||||
sync: Arc<SyncStatus>,
|
sync: Arc<SyncStatus>,
|
||||||
embeddable_at: Option<u16>,
|
embeddable_on: Option<(String, u16)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R: URLHint> Drop for ContentFetcher<R> {
|
impl<R: URLHint> Drop for ContentFetcher<R> {
|
||||||
@ -59,7 +59,7 @@ impl<R: URLHint> Drop for ContentFetcher<R> {
|
|||||||
|
|
||||||
impl<R: URLHint> ContentFetcher<R> {
|
impl<R: URLHint> ContentFetcher<R> {
|
||||||
|
|
||||||
pub fn new(resolver: R, sync_status: Arc<SyncStatus>, embeddable_at: Option<u16>) -> Self {
|
pub fn new(resolver: R, sync_status: Arc<SyncStatus>, embeddable_on: Option<(String, u16)>) -> Self {
|
||||||
let mut dapps_path = env::temp_dir();
|
let mut dapps_path = env::temp_dir();
|
||||||
dapps_path.push(random_filename());
|
dapps_path.push(random_filename());
|
||||||
|
|
||||||
@ -68,17 +68,17 @@ impl<R: URLHint> ContentFetcher<R> {
|
|||||||
resolver: resolver,
|
resolver: resolver,
|
||||||
sync: sync_status,
|
sync: sync_status,
|
||||||
cache: Arc::new(Mutex::new(ContentCache::default())),
|
cache: Arc::new(Mutex::new(ContentCache::default())),
|
||||||
embeddable_at: embeddable_at,
|
embeddable_on: embeddable_on,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn still_syncing(port: Option<u16>) -> Box<Handler> {
|
fn still_syncing(address: Option<(String, u16)>) -> Box<Handler> {
|
||||||
Box::new(ContentHandler::error(
|
Box::new(ContentHandler::error(
|
||||||
StatusCode::ServiceUnavailable,
|
StatusCode::ServiceUnavailable,
|
||||||
"Sync In Progress",
|
"Sync In Progress",
|
||||||
"Your node is still syncing. We cannot resolve any content before it's fully synced.",
|
"Your node is still syncing. We cannot resolve any content before it's fully synced.",
|
||||||
Some("<a href=\"javascript:window.location.reload()\">Refresh</a>"),
|
Some("<a href=\"javascript:window.location.reload()\">Refresh</a>"),
|
||||||
port,
|
address,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -145,7 +145,7 @@ impl<R: URLHint> ContentFetcher<R> {
|
|||||||
match content {
|
match content {
|
||||||
// Don't serve dapps if we are still syncing (but serve content)
|
// Don't serve dapps if we are still syncing (but serve content)
|
||||||
Some(URLHintResult::Dapp(_)) if self.sync.is_major_importing() => {
|
Some(URLHintResult::Dapp(_)) if self.sync.is_major_importing() => {
|
||||||
(None, Self::still_syncing(self.embeddable_at))
|
(None, Self::still_syncing(self.embeddable_on.clone()))
|
||||||
},
|
},
|
||||||
Some(URLHintResult::Dapp(dapp)) => {
|
Some(URLHintResult::Dapp(dapp)) => {
|
||||||
let (handler, fetch_control) = ContentFetcherHandler::new(
|
let (handler, fetch_control) = ContentFetcherHandler::new(
|
||||||
@ -155,9 +155,9 @@ impl<R: URLHint> ContentFetcher<R> {
|
|||||||
id: content_id.clone(),
|
id: content_id.clone(),
|
||||||
dapps_path: self.dapps_path.clone(),
|
dapps_path: self.dapps_path.clone(),
|
||||||
on_done: Box::new(on_done),
|
on_done: Box::new(on_done),
|
||||||
embeddable_at: self.embeddable_at,
|
embeddable_on: self.embeddable_on.clone(),
|
||||||
},
|
},
|
||||||
self.embeddable_at,
|
self.embeddable_on.clone(),
|
||||||
);
|
);
|
||||||
|
|
||||||
(Some(ContentStatus::Fetching(fetch_control)), Box::new(handler) as Box<Handler>)
|
(Some(ContentStatus::Fetching(fetch_control)), Box::new(handler) as Box<Handler>)
|
||||||
@ -172,13 +172,13 @@ impl<R: URLHint> ContentFetcher<R> {
|
|||||||
content_path: self.dapps_path.clone(),
|
content_path: self.dapps_path.clone(),
|
||||||
on_done: Box::new(on_done),
|
on_done: Box::new(on_done),
|
||||||
},
|
},
|
||||||
self.embeddable_at,
|
self.embeddable_on.clone(),
|
||||||
);
|
);
|
||||||
|
|
||||||
(Some(ContentStatus::Fetching(fetch_control)), Box::new(handler) as Box<Handler>)
|
(Some(ContentStatus::Fetching(fetch_control)), Box::new(handler) as Box<Handler>)
|
||||||
},
|
},
|
||||||
None if self.sync.is_major_importing() => {
|
None if self.sync.is_major_importing() => {
|
||||||
(None, Self::still_syncing(self.embeddable_at))
|
(None, Self::still_syncing(self.embeddable_on.clone()))
|
||||||
},
|
},
|
||||||
None => {
|
None => {
|
||||||
// This may happen when sync status changes in between
|
// This may happen when sync status changes in between
|
||||||
@ -188,7 +188,7 @@ impl<R: URLHint> ContentFetcher<R> {
|
|||||||
"Resource Not Found",
|
"Resource Not Found",
|
||||||
"Requested resource was not found.",
|
"Requested resource was not found.",
|
||||||
None,
|
None,
|
||||||
self.embeddable_at,
|
self.embeddable_on.clone(),
|
||||||
)) as Box<Handler>)
|
)) as Box<Handler>)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@ -293,7 +293,7 @@ struct DappInstaller {
|
|||||||
id: String,
|
id: String,
|
||||||
dapps_path: PathBuf,
|
dapps_path: PathBuf,
|
||||||
on_done: Box<Fn(String, Option<LocalPageEndpoint>) + Send>,
|
on_done: Box<Fn(String, Option<LocalPageEndpoint>) + Send>,
|
||||||
embeddable_at: Option<u16>,
|
embeddable_on: Option<(String, u16)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DappInstaller {
|
impl DappInstaller {
|
||||||
@ -386,7 +386,7 @@ impl ContentValidator for DappInstaller {
|
|||||||
try!(manifest_file.write_all(manifest_str.as_bytes()));
|
try!(manifest_file.write_all(manifest_str.as_bytes()));
|
||||||
|
|
||||||
// Create endpoint
|
// Create endpoint
|
||||||
let app = LocalPageEndpoint::new(target, manifest.clone().into(), PageCache::Enabled, self.embeddable_at);
|
let app = LocalPageEndpoint::new(target, manifest.clone().into(), PageCache::Enabled, self.embeddable_on.clone());
|
||||||
|
|
||||||
// Return modified app manifest
|
// Return modified app manifest
|
||||||
Ok((manifest.id.clone(), app))
|
Ok((manifest.id.clone(), app))
|
||||||
|
@ -97,12 +97,12 @@ fn read_manifest(name: &str, mut path: PathBuf) -> EndpointInfo {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn local_endpoints(dapps_path: String, signer_port: Option<u16>) -> Endpoints {
|
pub fn local_endpoints(dapps_path: String, signer_address: Option<(String, u16)>) -> Endpoints {
|
||||||
let mut pages = Endpoints::new();
|
let mut pages = Endpoints::new();
|
||||||
for dapp in local_dapps(dapps_path) {
|
for dapp in local_dapps(dapps_path) {
|
||||||
pages.insert(
|
pages.insert(
|
||||||
dapp.id,
|
dapp.id,
|
||||||
Box::new(LocalPageEndpoint::new(dapp.path, dapp.info, PageCache::Disabled, signer_port))
|
Box::new(LocalPageEndpoint::new(dapp.path, dapp.info, PageCache::Disabled, signer_address.clone()))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
pages
|
pages
|
||||||
|
@ -37,26 +37,26 @@ pub fn utils() -> Box<Endpoint> {
|
|||||||
Box::new(PageEndpoint::with_prefix(parity_ui::App::default(), UTILS_PATH.to_owned()))
|
Box::new(PageEndpoint::with_prefix(parity_ui::App::default(), UTILS_PATH.to_owned()))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn all_endpoints(dapps_path: String, signer_port: Option<u16>) -> Endpoints {
|
pub fn all_endpoints(dapps_path: String, signer_address: Option<(String, u16)>) -> Endpoints {
|
||||||
// fetch fs dapps at first to avoid overwriting builtins
|
// fetch fs dapps at first to avoid overwriting builtins
|
||||||
let mut pages = fs::local_endpoints(dapps_path, signer_port);
|
let mut pages = fs::local_endpoints(dapps_path, signer_address.clone());
|
||||||
|
|
||||||
// NOTE [ToDr] Dapps will be currently embeded on 8180
|
// NOTE [ToDr] Dapps will be currently embeded on 8180
|
||||||
insert::<parity_ui::App>(&mut pages, "ui", Embeddable::Yes(signer_port));
|
insert::<parity_ui::App>(&mut pages, "ui", Embeddable::Yes(signer_address.clone()));
|
||||||
pages.insert("proxy".into(), ProxyPac::boxed(signer_port));
|
pages.insert("proxy".into(), ProxyPac::boxed(signer_address));
|
||||||
|
|
||||||
pages
|
pages
|
||||||
}
|
}
|
||||||
|
|
||||||
fn insert<T : WebApp + Default + 'static>(pages: &mut Endpoints, id: &str, embed_at: Embeddable) {
|
fn insert<T : WebApp + Default + 'static>(pages: &mut Endpoints, id: &str, embed_at: Embeddable) {
|
||||||
pages.insert(id.to_owned(), Box::new(match embed_at {
|
pages.insert(id.to_owned(), Box::new(match embed_at {
|
||||||
Embeddable::Yes(port) => PageEndpoint::new_safe_to_embed(T::default(), port),
|
Embeddable::Yes(address) => PageEndpoint::new_safe_to_embed(T::default(), address),
|
||||||
Embeddable::No => PageEndpoint::new(T::default()),
|
Embeddable::No => PageEndpoint::new(T::default()),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
enum Embeddable {
|
enum Embeddable {
|
||||||
Yes(Option<u16>),
|
Yes(Option<(String, u16)>),
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
No,
|
No,
|
||||||
}
|
}
|
||||||
|
@ -32,7 +32,7 @@ pub struct ContentHandler {
|
|||||||
content: String,
|
content: String,
|
||||||
mimetype: Mime,
|
mimetype: Mime,
|
||||||
write_pos: usize,
|
write_pos: usize,
|
||||||
safe_to_embed_at_port: Option<u16>,
|
safe_to_embed_on: Option<(String, u16)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ContentHandler {
|
impl ContentHandler {
|
||||||
@ -44,31 +44,31 @@ impl ContentHandler {
|
|||||||
Self::new(StatusCode::NotFound, content, mimetype)
|
Self::new(StatusCode::NotFound, content, mimetype)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn html(code: StatusCode, content: String, embeddable_at: Option<u16>) -> Self {
|
pub fn html(code: StatusCode, content: String, embeddable_on: Option<(String, u16)>) -> Self {
|
||||||
Self::new_embeddable(code, content, mime!(Text/Html), embeddable_at)
|
Self::new_embeddable(code, content, mime!(Text/Html), embeddable_on)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn error(code: StatusCode, title: &str, message: &str, details: Option<&str>, embeddable_at: Option<u16>) -> Self {
|
pub fn error(code: StatusCode, title: &str, message: &str, details: Option<&str>, embeddable_on: Option<(String, u16)>) -> Self {
|
||||||
Self::html(code, format!(
|
Self::html(code, format!(
|
||||||
include_str!("../error_tpl.html"),
|
include_str!("../error_tpl.html"),
|
||||||
title=title,
|
title=title,
|
||||||
message=message,
|
message=message,
|
||||||
details=details.unwrap_or_else(|| ""),
|
details=details.unwrap_or_else(|| ""),
|
||||||
version=version(),
|
version=version(),
|
||||||
), embeddable_at)
|
), embeddable_on)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn new(code: StatusCode, content: String, mimetype: Mime) -> Self {
|
pub fn new(code: StatusCode, content: String, mimetype: Mime) -> Self {
|
||||||
Self::new_embeddable(code, content, mimetype, None)
|
Self::new_embeddable(code, content, mimetype, None)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn new_embeddable(code: StatusCode, content: String, mimetype: Mime, embeddable_at: Option<u16>) -> Self {
|
pub fn new_embeddable(code: StatusCode, content: String, mimetype: Mime, embeddable_on: Option<(String, u16)>) -> Self {
|
||||||
ContentHandler {
|
ContentHandler {
|
||||||
code: code,
|
code: code,
|
||||||
content: content,
|
content: content,
|
||||||
mimetype: mimetype,
|
mimetype: mimetype,
|
||||||
write_pos: 0,
|
write_pos: 0,
|
||||||
safe_to_embed_at_port: embeddable_at,
|
safe_to_embed_on: embeddable_on,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -85,7 +85,7 @@ impl server::Handler<HttpStream> for ContentHandler {
|
|||||||
fn on_response(&mut self, res: &mut server::Response) -> Next {
|
fn on_response(&mut self, res: &mut server::Response) -> Next {
|
||||||
res.set_status(self.code);
|
res.set_status(self.code);
|
||||||
res.headers_mut().set(header::ContentType(self.mimetype.clone()));
|
res.headers_mut().set(header::ContentType(self.mimetype.clone()));
|
||||||
add_security_headers(&mut res.headers_mut(), self.safe_to_embed_at_port.clone());
|
add_security_headers(&mut res.headers_mut(), self.safe_to_embed_on.clone());
|
||||||
Next::write()
|
Next::write()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -138,7 +138,7 @@ pub struct ContentFetcherHandler<H: ContentValidator> {
|
|||||||
client: Option<Client>,
|
client: Option<Client>,
|
||||||
installer: H,
|
installer: H,
|
||||||
request_url: Option<Url>,
|
request_url: Option<Url>,
|
||||||
embeddable_at: Option<u16>,
|
embeddable_on: Option<(String, u16)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<H: ContentValidator> Drop for ContentFetcherHandler<H> {
|
impl<H: ContentValidator> Drop for ContentFetcherHandler<H> {
|
||||||
@ -157,7 +157,7 @@ impl<H: ContentValidator> ContentFetcherHandler<H> {
|
|||||||
url: String,
|
url: String,
|
||||||
control: Control,
|
control: Control,
|
||||||
handler: H,
|
handler: H,
|
||||||
embeddable_at: Option<u16>,
|
embeddable_on: Option<(String, u16)>,
|
||||||
) -> (Self, Arc<FetchControl>) {
|
) -> (Self, Arc<FetchControl>) {
|
||||||
|
|
||||||
let fetch_control = Arc::new(FetchControl::default());
|
let fetch_control = Arc::new(FetchControl::default());
|
||||||
@ -169,7 +169,7 @@ impl<H: ContentValidator> ContentFetcherHandler<H> {
|
|||||||
status: FetchState::NotStarted(url),
|
status: FetchState::NotStarted(url),
|
||||||
installer: handler,
|
installer: handler,
|
||||||
request_url: None,
|
request_url: None,
|
||||||
embeddable_at: embeddable_at,
|
embeddable_on: embeddable_on,
|
||||||
};
|
};
|
||||||
|
|
||||||
(handler, fetch_control)
|
(handler, fetch_control)
|
||||||
@ -208,7 +208,7 @@ impl<H: ContentValidator> server::Handler<HttpStream> for ContentFetcherHandler<
|
|||||||
"Unable To Start Dapp Download",
|
"Unable To Start Dapp Download",
|
||||||
"Could not initialize download of the dapp. It might be a problem with the remote server.",
|
"Could not initialize download of the dapp. It might be a problem with the remote server.",
|
||||||
Some(&format!("{}", e)),
|
Some(&format!("{}", e)),
|
||||||
self.embeddable_at,
|
self.embeddable_on.clone(),
|
||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@ -218,7 +218,7 @@ impl<H: ContentValidator> server::Handler<HttpStream> for ContentFetcherHandler<
|
|||||||
"Method Not Allowed",
|
"Method Not Allowed",
|
||||||
"Only <code>GET</code> requests are allowed.",
|
"Only <code>GET</code> requests are allowed.",
|
||||||
None,
|
None,
|
||||||
self.embeddable_at,
|
self.embeddable_on.clone(),
|
||||||
)),
|
)),
|
||||||
})
|
})
|
||||||
} else { None };
|
} else { None };
|
||||||
@ -241,7 +241,7 @@ impl<H: ContentValidator> server::Handler<HttpStream> for ContentFetcherHandler<
|
|||||||
"Download Timeout",
|
"Download Timeout",
|
||||||
&format!("Could not fetch content within {} seconds.", FETCH_TIMEOUT),
|
&format!("Could not fetch content within {} seconds.", FETCH_TIMEOUT),
|
||||||
None,
|
None,
|
||||||
self.embeddable_at,
|
self.embeddable_on.clone(),
|
||||||
);
|
);
|
||||||
Self::close_client(&mut self.client);
|
Self::close_client(&mut self.client);
|
||||||
(Some(FetchState::Error(timeout)), Next::write())
|
(Some(FetchState::Error(timeout)), Next::write())
|
||||||
@ -263,7 +263,7 @@ impl<H: ContentValidator> server::Handler<HttpStream> for ContentFetcherHandler<
|
|||||||
"Invalid Dapp",
|
"Invalid Dapp",
|
||||||
"Downloaded bundle does not contain a valid content.",
|
"Downloaded bundle does not contain a valid content.",
|
||||||
Some(&format!("{:?}", e)),
|
Some(&format!("{:?}", e)),
|
||||||
self.embeddable_at,
|
self.embeddable_on.clone(),
|
||||||
))
|
))
|
||||||
},
|
},
|
||||||
Ok((id, result)) => {
|
Ok((id, result)) => {
|
||||||
@ -284,7 +284,7 @@ impl<H: ContentValidator> server::Handler<HttpStream> for ContentFetcherHandler<
|
|||||||
"Download Error",
|
"Download Error",
|
||||||
"There was an error when fetching the content.",
|
"There was an error when fetching the content.",
|
||||||
Some(&format!("{:?}", e)),
|
Some(&format!("{:?}", e)),
|
||||||
self.embeddable_at,
|
self.embeddable_on.clone(),
|
||||||
);
|
);
|
||||||
(Some(FetchState::Error(error)), Next::write())
|
(Some(FetchState::Error(error)), Next::write())
|
||||||
},
|
},
|
||||||
|
@ -30,18 +30,18 @@ pub use self::fetch::{ContentFetcherHandler, ContentValidator, FetchControl};
|
|||||||
|
|
||||||
use url::Url;
|
use url::Url;
|
||||||
use hyper::{server, header, net, uri};
|
use hyper::{server, header, net, uri};
|
||||||
use signer_address;
|
use address;
|
||||||
|
|
||||||
/// Adds security-related headers to the Response.
|
/// Adds security-related headers to the Response.
|
||||||
pub fn add_security_headers(headers: &mut header::Headers, embeddable_at: Option<u16>) {
|
pub fn add_security_headers(headers: &mut header::Headers, embeddable_on: Option<(String, u16)>) {
|
||||||
headers.set_raw("X-XSS-Protection", vec![b"1; mode=block".to_vec()]);
|
headers.set_raw("X-XSS-Protection", vec![b"1; mode=block".to_vec()]);
|
||||||
headers.set_raw("X-Content-Type-Options", vec![b"nosniff".to_vec()]);
|
headers.set_raw("X-Content-Type-Options", vec![b"nosniff".to_vec()]);
|
||||||
|
|
||||||
// Embedding header:
|
// Embedding header:
|
||||||
if let Some(port) = embeddable_at {
|
if let Some(embeddable_on) = embeddable_on {
|
||||||
headers.set_raw(
|
headers.set_raw(
|
||||||
"X-Frame-Options",
|
"X-Frame-Options",
|
||||||
vec![format!("ALLOW-FROM http://{}", signer_address(port)).into_bytes()]
|
vec![format!("ALLOW-FROM http://{}", address(embeddable_on)).into_bytes()]
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
// TODO [ToDr] Should we be more strict here (DENY?)?
|
// TODO [ToDr] Should we be more strict here (DENY?)?
|
||||||
|
@ -112,7 +112,7 @@ pub struct ServerBuilder {
|
|||||||
handler: Arc<IoHandler>,
|
handler: Arc<IoHandler>,
|
||||||
registrar: Arc<ContractClient>,
|
registrar: Arc<ContractClient>,
|
||||||
sync_status: Arc<SyncStatus>,
|
sync_status: Arc<SyncStatus>,
|
||||||
signer_port: Option<u16>,
|
signer_address: Option<(String, u16)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Extendable for ServerBuilder {
|
impl Extendable for ServerBuilder {
|
||||||
@ -129,7 +129,7 @@ impl ServerBuilder {
|
|||||||
handler: Arc::new(IoHandler::new()),
|
handler: Arc::new(IoHandler::new()),
|
||||||
registrar: registrar,
|
registrar: registrar,
|
||||||
sync_status: Arc::new(|| false),
|
sync_status: Arc::new(|| false),
|
||||||
signer_port: None,
|
signer_address: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -139,8 +139,8 @@ impl ServerBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Change default signer port.
|
/// Change default signer port.
|
||||||
pub fn with_signer_port(&mut self, signer_port: Option<u16>) {
|
pub fn with_signer_address(&mut self, signer_address: Option<(String, u16)>) {
|
||||||
self.signer_port = signer_port;
|
self.signer_address = signer_address;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Asynchronously start server with no authentication,
|
/// Asynchronously start server with no authentication,
|
||||||
@ -152,7 +152,7 @@ impl ServerBuilder {
|
|||||||
NoAuth,
|
NoAuth,
|
||||||
self.handler.clone(),
|
self.handler.clone(),
|
||||||
self.dapps_path.clone(),
|
self.dapps_path.clone(),
|
||||||
self.signer_port.clone(),
|
self.signer_address.clone(),
|
||||||
self.registrar.clone(),
|
self.registrar.clone(),
|
||||||
self.sync_status.clone(),
|
self.sync_status.clone(),
|
||||||
)
|
)
|
||||||
@ -167,7 +167,7 @@ impl ServerBuilder {
|
|||||||
HttpBasicAuth::single_user(username, password),
|
HttpBasicAuth::single_user(username, password),
|
||||||
self.handler.clone(),
|
self.handler.clone(),
|
||||||
self.dapps_path.clone(),
|
self.dapps_path.clone(),
|
||||||
self.signer_port.clone(),
|
self.signer_address.clone(),
|
||||||
self.registrar.clone(),
|
self.registrar.clone(),
|
||||||
self.sync_status.clone(),
|
self.sync_status.clone(),
|
||||||
)
|
)
|
||||||
@ -197,11 +197,11 @@ impl Server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a list of CORS domains for API endpoint.
|
/// Returns a list of CORS domains for API endpoint.
|
||||||
fn cors_domains(signer_port: Option<u16>) -> Vec<String> {
|
fn cors_domains(signer_address: Option<(String, u16)>) -> Vec<String> {
|
||||||
match signer_port {
|
match signer_address {
|
||||||
Some(port) => vec![
|
Some(signer_address) => vec![
|
||||||
format!("http://{}{}", HOME_PAGE, DAPPS_DOMAIN),
|
format!("http://{}{}", HOME_PAGE, DAPPS_DOMAIN),
|
||||||
format!("http://{}", signer_address(port)),
|
format!("http://{}", address(signer_address)),
|
||||||
],
|
],
|
||||||
None => vec![],
|
None => vec![],
|
||||||
}
|
}
|
||||||
@ -213,15 +213,15 @@ impl Server {
|
|||||||
authorization: A,
|
authorization: A,
|
||||||
handler: Arc<IoHandler>,
|
handler: Arc<IoHandler>,
|
||||||
dapps_path: String,
|
dapps_path: String,
|
||||||
signer_port: Option<u16>,
|
signer_address: Option<(String, u16)>,
|
||||||
registrar: Arc<ContractClient>,
|
registrar: Arc<ContractClient>,
|
||||||
sync_status: Arc<SyncStatus>,
|
sync_status: Arc<SyncStatus>,
|
||||||
) -> Result<Server, ServerError> {
|
) -> Result<Server, ServerError> {
|
||||||
let panic_handler = Arc::new(Mutex::new(None));
|
let panic_handler = Arc::new(Mutex::new(None));
|
||||||
let authorization = Arc::new(authorization);
|
let authorization = Arc::new(authorization);
|
||||||
let content_fetcher = Arc::new(apps::fetcher::ContentFetcher::new(apps::urlhint::URLHintContract::new(registrar), sync_status, signer_port));
|
let content_fetcher = Arc::new(apps::fetcher::ContentFetcher::new(apps::urlhint::URLHintContract::new(registrar), sync_status, signer_address.clone()));
|
||||||
let endpoints = Arc::new(apps::all_endpoints(dapps_path, signer_port.clone()));
|
let endpoints = Arc::new(apps::all_endpoints(dapps_path, signer_address.clone()));
|
||||||
let cors_domains = Self::cors_domains(signer_port);
|
let cors_domains = Self::cors_domains(signer_address.clone());
|
||||||
|
|
||||||
let special = Arc::new({
|
let special = Arc::new({
|
||||||
let mut special = HashMap::new();
|
let mut special = HashMap::new();
|
||||||
@ -238,7 +238,7 @@ impl Server {
|
|||||||
try!(hyper::Server::http(addr))
|
try!(hyper::Server::http(addr))
|
||||||
.handle(move |ctrl| router::Router::new(
|
.handle(move |ctrl| router::Router::new(
|
||||||
ctrl,
|
ctrl,
|
||||||
signer_port.clone(),
|
signer_address.clone(),
|
||||||
content_fetcher.clone(),
|
content_fetcher.clone(),
|
||||||
endpoints.clone(),
|
endpoints.clone(),
|
||||||
special.clone(),
|
special.clone(),
|
||||||
@ -302,8 +302,8 @@ pub fn random_filename() -> String {
|
|||||||
rng.gen_ascii_chars().take(12).collect()
|
rng.gen_ascii_chars().take(12).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signer_address(port: u16) -> String {
|
fn address(address: (String, u16)) -> String {
|
||||||
format!("127.0.0.1:{}", port)
|
format!("{}:{}", address.0, address.1)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@ -332,7 +332,7 @@ mod util_tests {
|
|||||||
|
|
||||||
// when
|
// when
|
||||||
let none = Server::cors_domains(None);
|
let none = Server::cors_domains(None);
|
||||||
let some = Server::cors_domains(Some(18180));
|
let some = Server::cors_domains(Some(("127.0.0.1".into(), 18180)));
|
||||||
|
|
||||||
// then
|
// then
|
||||||
assert_eq!(none, Vec::<String>::new());
|
assert_eq!(none, Vec::<String>::new());
|
||||||
|
@ -25,7 +25,7 @@ pub struct PageEndpoint<T : WebApp + 'static> {
|
|||||||
/// Prefix to strip from the path (when `None` deducted from `app_id`)
|
/// Prefix to strip from the path (when `None` deducted from `app_id`)
|
||||||
pub prefix: Option<String>,
|
pub prefix: Option<String>,
|
||||||
/// Safe to be loaded in frame by other origin. (use wisely!)
|
/// Safe to be loaded in frame by other origin. (use wisely!)
|
||||||
safe_to_embed_at_port: Option<u16>,
|
safe_to_embed_on: Option<(String, u16)>,
|
||||||
info: EndpointInfo,
|
info: EndpointInfo,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,7 +36,7 @@ impl<T: WebApp + 'static> PageEndpoint<T> {
|
|||||||
PageEndpoint {
|
PageEndpoint {
|
||||||
app: Arc::new(app),
|
app: Arc::new(app),
|
||||||
prefix: None,
|
prefix: None,
|
||||||
safe_to_embed_at_port: None,
|
safe_to_embed_on: None,
|
||||||
info: EndpointInfo::from(info),
|
info: EndpointInfo::from(info),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -49,7 +49,7 @@ impl<T: WebApp + 'static> PageEndpoint<T> {
|
|||||||
PageEndpoint {
|
PageEndpoint {
|
||||||
app: Arc::new(app),
|
app: Arc::new(app),
|
||||||
prefix: Some(prefix),
|
prefix: Some(prefix),
|
||||||
safe_to_embed_at_port: None,
|
safe_to_embed_on: None,
|
||||||
info: EndpointInfo::from(info),
|
info: EndpointInfo::from(info),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -57,12 +57,12 @@ impl<T: WebApp + 'static> PageEndpoint<T> {
|
|||||||
/// Creates new `PageEndpoint` which can be safely used in iframe
|
/// Creates new `PageEndpoint` which can be safely used in iframe
|
||||||
/// even from different origin. It might be dangerous (clickjacking).
|
/// even from different origin. It might be dangerous (clickjacking).
|
||||||
/// Use wisely!
|
/// Use wisely!
|
||||||
pub fn new_safe_to_embed(app: T, port: Option<u16>) -> Self {
|
pub fn new_safe_to_embed(app: T, address: Option<(String, u16)>) -> Self {
|
||||||
let info = app.info();
|
let info = app.info();
|
||||||
PageEndpoint {
|
PageEndpoint {
|
||||||
app: Arc::new(app),
|
app: Arc::new(app),
|
||||||
prefix: None,
|
prefix: None,
|
||||||
safe_to_embed_at_port: port,
|
safe_to_embed_on: address,
|
||||||
info: EndpointInfo::from(info),
|
info: EndpointInfo::from(info),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -79,9 +79,9 @@ impl<T: WebApp> Endpoint for PageEndpoint<T> {
|
|||||||
app: BuiltinDapp::new(self.app.clone()),
|
app: BuiltinDapp::new(self.app.clone()),
|
||||||
prefix: self.prefix.clone(),
|
prefix: self.prefix.clone(),
|
||||||
path: path,
|
path: path,
|
||||||
file: handler::ServedFile::new(self.safe_to_embed_at_port.clone()),
|
file: handler::ServedFile::new(self.safe_to_embed_on.clone()),
|
||||||
cache: PageCache::Disabled,
|
cache: PageCache::Disabled,
|
||||||
safe_to_embed_at_port: self.safe_to_embed_at_port.clone(),
|
safe_to_embed_on: self.safe_to_embed_on.clone(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -60,13 +60,13 @@ pub enum ServedFile<T: Dapp> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Dapp> ServedFile<T> {
|
impl<T: Dapp> ServedFile<T> {
|
||||||
pub fn new(embeddable_at: Option<u16>) -> Self {
|
pub fn new(embeddable_on: Option<(String, u16)>) -> Self {
|
||||||
ServedFile::Error(ContentHandler::error(
|
ServedFile::Error(ContentHandler::error(
|
||||||
StatusCode::NotFound,
|
StatusCode::NotFound,
|
||||||
"404 Not Found",
|
"404 Not Found",
|
||||||
"Requested dapp resource was not found.",
|
"Requested dapp resource was not found.",
|
||||||
None,
|
None,
|
||||||
embeddable_at,
|
embeddable_on,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -97,7 +97,7 @@ pub struct PageHandler<T: Dapp> {
|
|||||||
/// Requested path.
|
/// Requested path.
|
||||||
pub path: EndpointPath,
|
pub path: EndpointPath,
|
||||||
/// Flag indicating if the file can be safely embeded (put in iframe).
|
/// Flag indicating if the file can be safely embeded (put in iframe).
|
||||||
pub safe_to_embed_at_port: Option<u16>,
|
pub safe_to_embed_on: Option<(String, u16)>,
|
||||||
/// Cache settings for this page.
|
/// Cache settings for this page.
|
||||||
pub cache: PageCache,
|
pub cache: PageCache,
|
||||||
}
|
}
|
||||||
@ -133,7 +133,7 @@ impl<T: Dapp> server::Handler<HttpStream> for PageHandler<T> {
|
|||||||
self.app.file(&self.extract_path(url.path()))
|
self.app.file(&self.extract_path(url.path()))
|
||||||
},
|
},
|
||||||
_ => None,
|
_ => None,
|
||||||
}.map_or_else(|| ServedFile::new(self.safe_to_embed_at_port.clone()), |f| ServedFile::File(f));
|
}.map_or_else(|| ServedFile::new(self.safe_to_embed_on.clone()), |f| ServedFile::File(f));
|
||||||
Next::write()
|
Next::write()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -162,7 +162,7 @@ impl<T: Dapp> server::Handler<HttpStream> for PageHandler<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Security headers:
|
// Security headers:
|
||||||
add_security_headers(&mut res.headers_mut(), self.safe_to_embed_at_port);
|
add_security_headers(&mut res.headers_mut(), self.safe_to_embed_on.clone());
|
||||||
Next::write()
|
Next::write()
|
||||||
},
|
},
|
||||||
ServedFile::Error(ref mut handler) => {
|
ServedFile::Error(ref mut handler) => {
|
||||||
@ -246,7 +246,7 @@ fn should_extract_path_with_appid() {
|
|||||||
},
|
},
|
||||||
file: ServedFile::new(None),
|
file: ServedFile::new(None),
|
||||||
cache: Default::default(),
|
cache: Default::default(),
|
||||||
safe_to_embed_at_port: None,
|
safe_to_embed_on: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
// when
|
// when
|
||||||
|
@ -27,17 +27,17 @@ pub struct LocalPageEndpoint {
|
|||||||
mime: Option<String>,
|
mime: Option<String>,
|
||||||
info: Option<EndpointInfo>,
|
info: Option<EndpointInfo>,
|
||||||
cache: PageCache,
|
cache: PageCache,
|
||||||
embeddable_at: Option<u16>,
|
embeddable_on: Option<(String, u16)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl LocalPageEndpoint {
|
impl LocalPageEndpoint {
|
||||||
pub fn new(path: PathBuf, info: EndpointInfo, cache: PageCache, embeddable_at: Option<u16>) -> Self {
|
pub fn new(path: PathBuf, info: EndpointInfo, cache: PageCache, embeddable_on: Option<(String, u16)>) -> Self {
|
||||||
LocalPageEndpoint {
|
LocalPageEndpoint {
|
||||||
path: path,
|
path: path,
|
||||||
mime: None,
|
mime: None,
|
||||||
info: Some(info),
|
info: Some(info),
|
||||||
cache: cache,
|
cache: cache,
|
||||||
embeddable_at: embeddable_at,
|
embeddable_on: embeddable_on,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -47,7 +47,7 @@ impl LocalPageEndpoint {
|
|||||||
mime: Some(mime),
|
mime: Some(mime),
|
||||||
info: None,
|
info: None,
|
||||||
cache: cache,
|
cache: cache,
|
||||||
embeddable_at: None,
|
embeddable_on: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -68,7 +68,7 @@ impl Endpoint for LocalPageEndpoint {
|
|||||||
prefix: None,
|
prefix: None,
|
||||||
path: path,
|
path: path,
|
||||||
file: handler::ServedFile::new(None),
|
file: handler::ServedFile::new(None),
|
||||||
safe_to_embed_at_port: self.embeddable_at,
|
safe_to_embed_on: self.embeddable_on.clone(),
|
||||||
cache: self.cache,
|
cache: self.cache,
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
@ -77,7 +77,7 @@ impl Endpoint for LocalPageEndpoint {
|
|||||||
prefix: None,
|
prefix: None,
|
||||||
path: path,
|
path: path,
|
||||||
file: handler::ServedFile::new(None),
|
file: handler::ServedFile::new(None),
|
||||||
safe_to_embed_at_port: self.embeddable_at,
|
safe_to_embed_on: self.embeddable_on.clone(),
|
||||||
cache: self.cache,
|
cache: self.cache,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -19,24 +19,24 @@
|
|||||||
use endpoint::{Endpoint, Handler, EndpointPath};
|
use endpoint::{Endpoint, Handler, EndpointPath};
|
||||||
use handlers::ContentHandler;
|
use handlers::ContentHandler;
|
||||||
use apps::{HOME_PAGE, DAPPS_DOMAIN};
|
use apps::{HOME_PAGE, DAPPS_DOMAIN};
|
||||||
use signer_address;
|
use address;
|
||||||
|
|
||||||
pub struct ProxyPac {
|
pub struct ProxyPac {
|
||||||
signer_port: Option<u16>,
|
signer_address: Option<(String, u16)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ProxyPac {
|
impl ProxyPac {
|
||||||
pub fn boxed(signer_port: Option<u16>) -> Box<Endpoint> {
|
pub fn boxed(signer_address: Option<(String, u16)>) -> Box<Endpoint> {
|
||||||
Box::new(ProxyPac {
|
Box::new(ProxyPac {
|
||||||
signer_port: signer_port
|
signer_address: signer_address
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Endpoint for ProxyPac {
|
impl Endpoint for ProxyPac {
|
||||||
fn to_handler(&self, path: EndpointPath) -> Box<Handler> {
|
fn to_handler(&self, path: EndpointPath) -> Box<Handler> {
|
||||||
let signer = self.signer_port
|
let signer = self.signer_address.clone()
|
||||||
.map(signer_address)
|
.map(address)
|
||||||
.unwrap_or_else(|| format!("{}:{}", path.host, path.port));
|
.unwrap_or_else(|| format!("{}:{}", path.host, path.port));
|
||||||
|
|
||||||
let content = format!(
|
let content = format!(
|
||||||
|
@ -20,7 +20,7 @@
|
|||||||
pub mod auth;
|
pub mod auth;
|
||||||
mod host_validation;
|
mod host_validation;
|
||||||
|
|
||||||
use signer_address;
|
use address;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use url::{Url, Host};
|
use url::{Url, Host};
|
||||||
@ -43,7 +43,7 @@ pub enum SpecialEndpoint {
|
|||||||
|
|
||||||
pub struct Router<A: Authorization + 'static> {
|
pub struct Router<A: Authorization + 'static> {
|
||||||
control: Option<Control>,
|
control: Option<Control>,
|
||||||
signer_port: Option<u16>,
|
signer_address: Option<(String, u16)>,
|
||||||
endpoints: Arc<Endpoints>,
|
endpoints: Arc<Endpoints>,
|
||||||
fetch: Arc<ContentFetcher>,
|
fetch: Arc<ContentFetcher>,
|
||||||
special: Arc<HashMap<SpecialEndpoint, Box<Endpoint>>>,
|
special: Arc<HashMap<SpecialEndpoint, Box<Endpoint>>>,
|
||||||
@ -117,22 +117,22 @@ impl<A: Authorization + 'static> server::Handler<HttpStream> for Router<A> {
|
|||||||
"404 Not Found",
|
"404 Not Found",
|
||||||
"Requested content was not found.",
|
"Requested content was not found.",
|
||||||
None,
|
None,
|
||||||
self.signer_port,
|
self.signer_address.clone(),
|
||||||
))
|
))
|
||||||
},
|
},
|
||||||
// Redirect any other GET request to signer.
|
// Redirect any other GET request to signer.
|
||||||
_ if *req.method() == hyper::Method::Get => {
|
_ if *req.method() == hyper::Method::Get => {
|
||||||
if let Some(port) = self.signer_port {
|
if let Some(signer_address) = self.signer_address.clone() {
|
||||||
trace!(target: "dapps", "Redirecting to signer interface.");
|
trace!(target: "dapps", "Redirecting to signer interface.");
|
||||||
Redirection::boxed(&format!("http://{}", signer_address(port)))
|
Redirection::boxed(&format!("http://{}", address(signer_address)))
|
||||||
} else {
|
} else {
|
||||||
trace!(target: "dapps", "Signer disabled, returning 404.");
|
trace!(target: "dapps", "Signer disabled, returning 404.");
|
||||||
Box::new(ContentHandler::error(
|
Box::new(ContentHandler::error(
|
||||||
StatusCode::NotFound,
|
StatusCode::NotFound,
|
||||||
"404 Not Found",
|
"404 Not Found",
|
||||||
"Your homepage is not available when Trusted Signer is disabled.",
|
"Your homepage is not available when Trusted Signer is disabled.",
|
||||||
Some("You can still access dapps by writing a correct address, though. Re-enabled Signer to get your homepage back."),
|
Some("You can still access dapps by writing a correct address, though. Re-enable Signer to get your homepage back."),
|
||||||
self.signer_port,
|
self.signer_address.clone(),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@ -168,7 +168,7 @@ impl<A: Authorization + 'static> server::Handler<HttpStream> for Router<A> {
|
|||||||
impl<A: Authorization> Router<A> {
|
impl<A: Authorization> Router<A> {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
control: Control,
|
control: Control,
|
||||||
signer_port: Option<u16>,
|
signer_address: Option<(String, u16)>,
|
||||||
content_fetcher: Arc<ContentFetcher>,
|
content_fetcher: Arc<ContentFetcher>,
|
||||||
endpoints: Arc<Endpoints>,
|
endpoints: Arc<Endpoints>,
|
||||||
special: Arc<HashMap<SpecialEndpoint, Box<Endpoint>>>,
|
special: Arc<HashMap<SpecialEndpoint, Box<Endpoint>>>,
|
||||||
@ -181,7 +181,7 @@ impl<A: Authorization> Router<A> {
|
|||||||
.to_handler(EndpointPath::default());
|
.to_handler(EndpointPath::default());
|
||||||
Router {
|
Router {
|
||||||
control: Some(control),
|
control: Some(control),
|
||||||
signer_port: signer_port,
|
signer_address: signer_address,
|
||||||
endpoints: endpoints,
|
endpoints: endpoints,
|
||||||
fetch: content_fetcher,
|
fetch: content_fetcher,
|
||||||
special: special,
|
special: special,
|
||||||
|
@ -76,7 +76,7 @@ pub fn init_server(hosts: Option<Vec<String>>, is_syncing: bool) -> (Server, Arc
|
|||||||
dapps_path.push("non-existent-dir-to-prevent-fs-files-from-loading");
|
dapps_path.push("non-existent-dir-to-prevent-fs-files-from-loading");
|
||||||
let mut builder = ServerBuilder::new(dapps_path.to_str().unwrap().into(), registrar.clone());
|
let mut builder = ServerBuilder::new(dapps_path.to_str().unwrap().into(), registrar.clone());
|
||||||
builder.with_sync_status(Arc::new(move || is_syncing));
|
builder.with_sync_status(Arc::new(move || is_syncing));
|
||||||
builder.with_signer_port(Some(SIGNER_PORT));
|
builder.with_signer_address(Some(("127.0.0.1".into(), SIGNER_PORT)));
|
||||||
(
|
(
|
||||||
builder.start_unsecured_http(&"127.0.0.1:0".parse().unwrap(), hosts).unwrap(),
|
builder.start_unsecured_http(&"127.0.0.1:0".parse().unwrap(), hosts).unwrap(),
|
||||||
registrar,
|
registrar,
|
||||||
@ -89,7 +89,7 @@ pub fn serve_with_auth(user: &str, pass: &str) -> Server {
|
|||||||
let mut dapps_path = env::temp_dir();
|
let mut dapps_path = env::temp_dir();
|
||||||
dapps_path.push("non-existent-dir-to-prevent-fs-files-from-loading");
|
dapps_path.push("non-existent-dir-to-prevent-fs-files-from-loading");
|
||||||
let mut builder = ServerBuilder::new(dapps_path.to_str().unwrap().into(), registrar);
|
let mut builder = ServerBuilder::new(dapps_path.to_str().unwrap().into(), registrar);
|
||||||
builder.with_signer_port(Some(SIGNER_PORT));
|
builder.with_signer_address(Some(("127.0.0.1".into(), SIGNER_PORT)));
|
||||||
builder.start_basic_auth_http(&"127.0.0.1:0".parse().unwrap(), None, user, pass).unwrap()
|
builder.start_basic_auth_http(&"127.0.0.1:0".parse().unwrap(), None, user, pass).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -14,6 +14,7 @@
|
|||||||
// You should have received a copy of the GNU General Public License
|
// You should have received a copy of the GNU General Public License
|
||||||
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
use std::thread;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
use std::str::{self, Lines};
|
use std::str::{self, Lines};
|
||||||
@ -42,8 +43,28 @@ pub fn read_block(lines: &mut Lines, all: bool) -> String {
|
|||||||
block
|
block
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn connect(address: &SocketAddr) -> TcpStream {
|
||||||
|
let mut retries = 0;
|
||||||
|
let mut last_error = None;
|
||||||
|
while retries < 10 {
|
||||||
|
retries += 1;
|
||||||
|
|
||||||
|
let res = TcpStream::connect(address);
|
||||||
|
match res {
|
||||||
|
Ok(stream) => {
|
||||||
|
return stream;
|
||||||
|
},
|
||||||
|
Err(e) => {
|
||||||
|
last_error = Some(e);
|
||||||
|
thread::sleep(Duration::from_millis(retries * 10));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panic!("Unable to connect to the server. Last error: {:?}", last_error);
|
||||||
|
}
|
||||||
|
|
||||||
pub fn request(address: &SocketAddr, request: &str) -> Response {
|
pub fn request(address: &SocketAddr, request: &str) -> Response {
|
||||||
let mut req = TcpStream::connect(address).unwrap();
|
let mut req = connect(address);
|
||||||
req.set_read_timeout(Some(Duration::from_secs(1))).unwrap();
|
req.set_read_timeout(Some(Duration::from_secs(1))).unwrap();
|
||||||
req.write_all(request.as_bytes()).unwrap();
|
req.write_all(request.as_bytes()).unwrap();
|
||||||
|
|
||||||
|
@ -131,10 +131,10 @@
|
|||||||
"0x807640a13483f8ac783c557fcdf27be11ea4ac7a"
|
"0x807640a13483f8ac783c557fcdf27be11ea4ac7a"
|
||||||
],
|
],
|
||||||
"eip150Transition": "0x259518",
|
"eip150Transition": "0x259518",
|
||||||
"eip155Transition": 2642462,
|
"eip155Transition": "0x7fffffffffffffff",
|
||||||
"eip160Transition": 2642462,
|
"eip160Transition": "0x7fffffffffffffff",
|
||||||
"eip161abcTransition": 2642462,
|
"eip161abcTransition": "0x7fffffffffffffff",
|
||||||
"eip161dTransition": 2642462
|
"eip161dTransition": "0x7fffffffffffffff"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@ -176,7 +176,13 @@
|
|||||||
"enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@52.16.188.185:30303",
|
"enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@52.16.188.185:30303",
|
||||||
"enode://de471bccee3d042261d52e9bff31458daecc406142b401d4cd848f677479f73104b9fdeb090af9583d3391b7f10cb2ba9e26865dd5fca4fcdc0fb1e3b723c786@54.94.239.50:30303",
|
"enode://de471bccee3d042261d52e9bff31458daecc406142b401d4cd848f677479f73104b9fdeb090af9583d3391b7f10cb2ba9e26865dd5fca4fcdc0fb1e3b723c786@54.94.239.50:30303",
|
||||||
"enode://1118980bf48b0a3640bdba04e0fe78b1add18e1cd99bf22d53daac1fd9972ad650df52176e7c7d89d1114cfef2bc23a2959aa54998a46afcf7d91809f0855082@52.74.57.123:30303",
|
"enode://1118980bf48b0a3640bdba04e0fe78b1add18e1cd99bf22d53daac1fd9972ad650df52176e7c7d89d1114cfef2bc23a2959aa54998a46afcf7d91809f0855082@52.74.57.123:30303",
|
||||||
"enode://4cd540b2c3292e17cff39922e864094bf8b0741fcc8c5dcea14957e389d7944c70278d872902e3d0345927f621547efa659013c400865485ab4bfa0c6596936f@138.201.144.135:30303"
|
"enode://4cd540b2c3292e17cff39922e864094bf8b0741fcc8c5dcea14957e389d7944c70278d872902e3d0345927f621547efa659013c400865485ab4bfa0c6596936f@138.201.144.135:30303",
|
||||||
|
|
||||||
|
"enode://89d5dc2a81e574c19d0465f497c1af96732d1b61a41de89c2a37f35707689ac416529fae1038809852b235c2d30fd325abdc57c122feeefbeaaf802cc7e9580d@45.55.33.62:30303",
|
||||||
|
"enode://605e04a43b1156966b3a3b66b980c87b7f18522f7f712035f84576016be909a2798a438b2b17b1a8c58db314d88539a77419ca4be36148c086900fba487c9d39@188.166.255.12:30303",
|
||||||
|
"enode://016b20125f447a3b203a3cae953b2ede8ffe51290c071e7599294be84317635730c397b8ff74404d6be412d539ee5bb5c3c700618723d3b53958c92bd33eaa82@159.203.210.80:30303",
|
||||||
|
"enode://01f76fa0561eca2b9a7e224378dd854278735f1449793c46ad0c4e79e8775d080c21dcc455be391e90a98153c3b05dcc8935c8440de7b56fe6d67251e33f4e3c@10.6.6.117:30303",
|
||||||
|
"enode://fe11ef89fc5ac9da358fc160857855f25bbf9e332c79b9ca7089330c02b728b2349988c6062f10982041702110745e203d26975a6b34bcc97144f9fe439034e8@10.1.72.117:30303"
|
||||||
],
|
],
|
||||||
"accounts": {
|
"accounts": {
|
||||||
"0000000000000000000000000000000000000001": { "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } },
|
"0000000000000000000000000000000000000001": { "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } },
|
||||||
|
@ -95,6 +95,7 @@ impl KeyDirectory for NullDir {
|
|||||||
struct AddressBook {
|
struct AddressBook {
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
cache: HashMap<Address, AccountMeta>,
|
cache: HashMap<Address, AccountMeta>,
|
||||||
|
transient: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AddressBook {
|
impl AddressBook {
|
||||||
@ -106,11 +107,18 @@ impl AddressBook {
|
|||||||
let mut r = AddressBook {
|
let mut r = AddressBook {
|
||||||
path: path,
|
path: path,
|
||||||
cache: HashMap::new(),
|
cache: HashMap::new(),
|
||||||
|
transient: false,
|
||||||
};
|
};
|
||||||
r.revert();
|
r.revert();
|
||||||
r
|
r
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn transient() -> Self {
|
||||||
|
let mut book = AddressBook::new(Default::default());
|
||||||
|
book.transient = true;
|
||||||
|
book
|
||||||
|
}
|
||||||
|
|
||||||
pub fn get(&self) -> HashMap<Address, AccountMeta> {
|
pub fn get(&self) -> HashMap<Address, AccountMeta> {
|
||||||
self.cache.clone()
|
self.cache.clone()
|
||||||
}
|
}
|
||||||
@ -134,6 +142,7 @@ impl AddressBook {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn revert(&mut self) {
|
fn revert(&mut self) {
|
||||||
|
if self.transient { return; }
|
||||||
trace!(target: "addressbook", "revert");
|
trace!(target: "addressbook", "revert");
|
||||||
let _ = fs::File::open(self.path.clone())
|
let _ = fs::File::open(self.path.clone())
|
||||||
.map_err(|e| trace!(target: "addressbook", "Couldn't open address book: {}", e))
|
.map_err(|e| trace!(target: "addressbook", "Couldn't open address book: {}", e))
|
||||||
@ -144,6 +153,7 @@ impl AddressBook {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn save(&mut self) {
|
fn save(&mut self) {
|
||||||
|
if self.transient { return; }
|
||||||
trace!(target: "addressbook", "save");
|
trace!(target: "addressbook", "save");
|
||||||
let _ = fs::File::create(self.path.clone())
|
let _ = fs::File::create(self.path.clone())
|
||||||
.map_err(|e| warn!(target: "addressbook", "Couldn't open address book for writing: {}", e))
|
.map_err(|e| warn!(target: "addressbook", "Couldn't open address book for writing: {}", e))
|
||||||
@ -175,7 +185,7 @@ impl AccountProvider {
|
|||||||
pub fn transient_provider() -> Self {
|
pub fn transient_provider() -> Self {
|
||||||
AccountProvider {
|
AccountProvider {
|
||||||
unlocked: Mutex::new(HashMap::new()),
|
unlocked: Mutex::new(HashMap::new()),
|
||||||
address_book: Mutex::new(AddressBook::new(Default::default())),
|
address_book: Mutex::new(AddressBook::transient()),
|
||||||
sstore: Box::new(EthStore::open(Box::new(NullDir::default()))
|
sstore: Box::new(EthStore::open(Box::new(NullDir::default()))
|
||||||
.expect("NullDir load always succeeds; qed"))
|
.expect("NullDir load always succeeds; qed"))
|
||||||
}
|
}
|
||||||
|
@ -89,7 +89,7 @@ impl From<ethjson::blockchain::Account> for PodAccount {
|
|||||||
let key: U256 = key.into();
|
let key: U256 = key.into();
|
||||||
let value: U256 = value.into();
|
let value: U256 = value.into();
|
||||||
(H256::from(key), H256::from(value))
|
(H256::from(key), H256::from(value))
|
||||||
}).collect()
|
}).collect(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -99,8 +99,12 @@ impl From<ethjson::spec::Account> for PodAccount {
|
|||||||
PodAccount {
|
PodAccount {
|
||||||
balance: a.balance.map_or_else(U256::zero, Into::into),
|
balance: a.balance.map_or_else(U256::zero, Into::into),
|
||||||
nonce: a.nonce.map_or_else(U256::zero, Into::into),
|
nonce: a.nonce.map_or_else(U256::zero, Into::into),
|
||||||
code: a.code.map(Into::into).or_else(|| Some(Vec::new())),
|
code: Some(a.code.map_or_else(Vec::new, Into::into)),
|
||||||
storage: BTreeMap::new()
|
storage: a.storage.map_or_else(BTreeMap::new, |s| s.into_iter().map(|(key, value)| {
|
||||||
|
let key: U256 = key.into();
|
||||||
|
let value: U256 = value.into();
|
||||||
|
(H256::from(key), H256::from(value))
|
||||||
|
}).collect()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -112,7 +116,7 @@ impl fmt::Display for PodAccount {
|
|||||||
self.nonce,
|
self.nonce,
|
||||||
self.code.as_ref().map_or(0, |c| c.len()),
|
self.code.as_ref().map_or(0, |c| c.len()),
|
||||||
self.code.as_ref().map_or_else(H256::new, |c| c.sha3()),
|
self.code.as_ref().map_or_else(H256::new, |c| c.sha3()),
|
||||||
self.storage.len()
|
self.storage.len(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -45,6 +45,8 @@ pub enum Error {
|
|||||||
MissingCode(Vec<H256>),
|
MissingCode(Vec<H256>),
|
||||||
/// Unrecognized code encoding.
|
/// Unrecognized code encoding.
|
||||||
UnrecognizedCodeState(u8),
|
UnrecognizedCodeState(u8),
|
||||||
|
/// Restoration aborted.
|
||||||
|
RestorationAborted,
|
||||||
/// Trie error.
|
/// Trie error.
|
||||||
Trie(TrieError),
|
Trie(TrieError),
|
||||||
/// Decoder error.
|
/// Decoder error.
|
||||||
@ -67,6 +69,7 @@ impl fmt::Display for Error {
|
|||||||
a pruned database. Please re-run with the --pruning archive flag."),
|
a pruned database. Please re-run with the --pruning archive flag."),
|
||||||
Error::MissingCode(ref missing) => write!(f, "Incomplete snapshot: {} contract codes not found.", missing.len()),
|
Error::MissingCode(ref missing) => write!(f, "Incomplete snapshot: {} contract codes not found.", missing.len()),
|
||||||
Error::UnrecognizedCodeState(state) => write!(f, "Unrecognized code encoding ({})", state),
|
Error::UnrecognizedCodeState(state) => write!(f, "Unrecognized code encoding ({})", state),
|
||||||
|
Error::RestorationAborted => write!(f, "Snapshot restoration aborted."),
|
||||||
Error::Io(ref err) => err.fmt(f),
|
Error::Io(ref err) => err.fmt(f),
|
||||||
Error::Decoder(ref err) => err.fmt(f),
|
Error::Decoder(ref err) => err.fmt(f),
|
||||||
Error::Trie(ref err) => err.fmt(f),
|
Error::Trie(ref err) => err.fmt(f),
|
||||||
|
@ -407,30 +407,28 @@ impl StateRebuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Feed an uncompressed state chunk into the rebuilder.
|
/// Feed an uncompressed state chunk into the rebuilder.
|
||||||
pub fn feed(&mut self, chunk: &[u8]) -> Result<(), ::error::Error> {
|
pub fn feed(&mut self, chunk: &[u8], flag: &AtomicBool) -> Result<(), ::error::Error> {
|
||||||
let rlp = UntrustedRlp::new(chunk);
|
let rlp = UntrustedRlp::new(chunk);
|
||||||
let empty_rlp = StateAccount::new_basic(U256::zero(), U256::zero()).rlp();
|
let empty_rlp = StateAccount::new_basic(U256::zero(), U256::zero()).rlp();
|
||||||
let account_fat_rlps: Vec<_> = rlp.iter().map(|r| r.as_raw()).collect();
|
|
||||||
let mut pairs = Vec::with_capacity(rlp.item_count());
|
let mut pairs = Vec::with_capacity(rlp.item_count());
|
||||||
|
|
||||||
// initialize the pairs vector with empty values so we have slots to write into.
|
// initialize the pairs vector with empty values so we have slots to write into.
|
||||||
pairs.resize(rlp.item_count(), (H256::new(), Vec::new()));
|
pairs.resize(rlp.item_count(), (H256::new(), Vec::new()));
|
||||||
|
|
||||||
let chunk_size = account_fat_rlps.len() / ::num_cpus::get() + 1;
|
let status = try!(rebuild_accounts(
|
||||||
|
self.db.as_hashdb_mut(),
|
||||||
|
rlp,
|
||||||
|
&mut pairs,
|
||||||
|
&self.code_map,
|
||||||
|
flag
|
||||||
|
));
|
||||||
|
|
||||||
// new code contained within this chunk.
|
for (addr_hash, code_hash) in status.missing_code {
|
||||||
let mut chunk_code = HashMap::new();
|
self.missing_code.entry(code_hash).or_insert_with(Vec::new).push(addr_hash);
|
||||||
|
|
||||||
for (account_chunk, out_pairs_chunk) in account_fat_rlps.chunks(chunk_size).zip(pairs.chunks_mut(chunk_size)) {
|
|
||||||
let code_map = &self.code_map;
|
|
||||||
let status = try!(rebuild_accounts(self.db.as_hashdb_mut(), account_chunk, out_pairs_chunk, code_map));
|
|
||||||
chunk_code.extend(status.new_code);
|
|
||||||
for (addr_hash, code_hash) in status.missing_code {
|
|
||||||
self.missing_code.entry(code_hash).or_insert_with(Vec::new).push(addr_hash);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// patch up all missing code. must be done after collecting all new missing code entries.
|
// patch up all missing code. must be done after collecting all new missing code entries.
|
||||||
for (code_hash, code) in chunk_code {
|
for (code_hash, code) in status.new_code {
|
||||||
for addr_hash in self.missing_code.remove(&code_hash).unwrap_or_else(Vec::new) {
|
for addr_hash in self.missing_code.remove(&code_hash).unwrap_or_else(Vec::new) {
|
||||||
let mut db = AccountDBMut::from_hash(self.db.as_hashdb_mut(), addr_hash);
|
let mut db = AccountDBMut::from_hash(self.db.as_hashdb_mut(), addr_hash);
|
||||||
db.emplace(code_hash, DBValue::from_slice(&code));
|
db.emplace(code_hash, DBValue::from_slice(&code));
|
||||||
@ -450,6 +448,8 @@ impl StateRebuilder {
|
|||||||
};
|
};
|
||||||
|
|
||||||
for (hash, thin_rlp) in pairs {
|
for (hash, thin_rlp) in pairs {
|
||||||
|
if !flag.load(Ordering::SeqCst) { return Err(Error::RestorationAborted.into()) }
|
||||||
|
|
||||||
if &thin_rlp[..] != &empty_rlp[..] {
|
if &thin_rlp[..] != &empty_rlp[..] {
|
||||||
self.bloom.set(&*hash);
|
self.bloom.set(&*hash);
|
||||||
}
|
}
|
||||||
@ -487,17 +487,18 @@ struct RebuiltStatus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// rebuild a set of accounts and their storage.
|
// rebuild a set of accounts and their storage.
|
||||||
// returns
|
// returns a status detailing newly-loaded code and accounts missing code.
|
||||||
fn rebuild_accounts(
|
fn rebuild_accounts(
|
||||||
db: &mut HashDB,
|
db: &mut HashDB,
|
||||||
account_chunk: &[&[u8]],
|
account_fat_rlps: UntrustedRlp,
|
||||||
out_chunk: &mut [(H256, Bytes)],
|
out_chunk: &mut [(H256, Bytes)],
|
||||||
code_map: &HashMap<H256, Bytes>
|
code_map: &HashMap<H256, Bytes>,
|
||||||
|
abort_flag: &AtomicBool
|
||||||
) -> Result<RebuiltStatus, ::error::Error>
|
) -> Result<RebuiltStatus, ::error::Error>
|
||||||
{
|
{
|
||||||
let mut status = RebuiltStatus::default();
|
let mut status = RebuiltStatus::default();
|
||||||
for (account_pair, out) in account_chunk.into_iter().zip(out_chunk) {
|
for (account_rlp, out) in account_fat_rlps.into_iter().zip(out_chunk) {
|
||||||
let account_rlp = UntrustedRlp::new(account_pair);
|
if !abort_flag.load(Ordering::SeqCst) { return Err(Error::RestorationAborted.into()) }
|
||||||
|
|
||||||
let hash: H256 = try!(account_rlp.val_at(0));
|
let hash: H256 = try!(account_rlp.val_at(0));
|
||||||
let fat_rlp = try!(account_rlp.at(1));
|
let fat_rlp = try!(account_rlp.at(1));
|
||||||
@ -580,7 +581,7 @@ impl BlockRebuilder {
|
|||||||
|
|
||||||
/// Feed the rebuilder an uncompressed block chunk.
|
/// Feed the rebuilder an uncompressed block chunk.
|
||||||
/// Returns the number of blocks fed or any errors.
|
/// Returns the number of blocks fed or any errors.
|
||||||
pub fn feed(&mut self, chunk: &[u8], engine: &Engine) -> Result<u64, ::error::Error> {
|
pub fn feed(&mut self, chunk: &[u8], engine: &Engine, abort_flag: &AtomicBool) -> Result<u64, ::error::Error> {
|
||||||
use basic_types::Seal::With;
|
use basic_types::Seal::With;
|
||||||
use util::U256;
|
use util::U256;
|
||||||
use util::triehash::ordered_trie_root;
|
use util::triehash::ordered_trie_root;
|
||||||
@ -601,6 +602,8 @@ impl BlockRebuilder {
|
|||||||
let parent_total_difficulty = try!(rlp.val_at::<U256>(2));
|
let parent_total_difficulty = try!(rlp.val_at::<U256>(2));
|
||||||
|
|
||||||
for idx in 3..item_count {
|
for idx in 3..item_count {
|
||||||
|
if !abort_flag.load(Ordering::SeqCst) { return Err(Error::RestorationAborted.into()) }
|
||||||
|
|
||||||
let pair = try!(rlp.at(idx));
|
let pair = try!(rlp.at(idx));
|
||||||
let abridged_rlp = try!(pair.at(0)).as_raw().to_owned();
|
let abridged_rlp = try!(pair.at(0)).as_raw().to_owned();
|
||||||
let abridged_block = AbridgedBlock::from_raw(abridged_rlp);
|
let abridged_block = AbridgedBlock::from_raw(abridged_rlp);
|
||||||
|
@ -118,12 +118,12 @@ impl Restoration {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// feeds a state chunk
|
// feeds a state chunk, aborts early if `flag` becomes false.
|
||||||
fn feed_state(&mut self, hash: H256, chunk: &[u8]) -> Result<(), Error> {
|
fn feed_state(&mut self, hash: H256, chunk: &[u8], flag: &AtomicBool) -> Result<(), Error> {
|
||||||
if self.state_chunks_left.remove(&hash) {
|
if self.state_chunks_left.remove(&hash) {
|
||||||
let len = try!(snappy::decompress_into(chunk, &mut self.snappy_buffer));
|
let len = try!(snappy::decompress_into(chunk, &mut self.snappy_buffer));
|
||||||
|
|
||||||
try!(self.state.feed(&self.snappy_buffer[..len]));
|
try!(self.state.feed(&self.snappy_buffer[..len], flag));
|
||||||
|
|
||||||
if let Some(ref mut writer) = self.writer.as_mut() {
|
if let Some(ref mut writer) = self.writer.as_mut() {
|
||||||
try!(writer.write_state_chunk(hash, chunk));
|
try!(writer.write_state_chunk(hash, chunk));
|
||||||
@ -134,11 +134,11 @@ impl Restoration {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// feeds a block chunk
|
// feeds a block chunk
|
||||||
fn feed_blocks(&mut self, hash: H256, chunk: &[u8], engine: &Engine) -> Result<(), Error> {
|
fn feed_blocks(&mut self, hash: H256, chunk: &[u8], engine: &Engine, flag: &AtomicBool) -> Result<(), Error> {
|
||||||
if self.block_chunks_left.remove(&hash) {
|
if self.block_chunks_left.remove(&hash) {
|
||||||
let len = try!(snappy::decompress_into(chunk, &mut self.snappy_buffer));
|
let len = try!(snappy::decompress_into(chunk, &mut self.snappy_buffer));
|
||||||
|
|
||||||
try!(self.blocks.feed(&self.snappy_buffer[..len], engine));
|
try!(self.blocks.feed(&self.snappy_buffer[..len], engine, flag));
|
||||||
if let Some(ref mut writer) = self.writer.as_mut() {
|
if let Some(ref mut writer) = self.writer.as_mut() {
|
||||||
try!(writer.write_block_chunk(hash, chunk));
|
try!(writer.write_block_chunk(hash, chunk));
|
||||||
}
|
}
|
||||||
@ -224,6 +224,7 @@ pub struct Service {
|
|||||||
db_restore: Arc<DatabaseRestore>,
|
db_restore: Arc<DatabaseRestore>,
|
||||||
progress: super::Progress,
|
progress: super::Progress,
|
||||||
taking_snapshot: AtomicBool,
|
taking_snapshot: AtomicBool,
|
||||||
|
restoring_snapshot: AtomicBool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Service {
|
impl Service {
|
||||||
@ -244,6 +245,7 @@ impl Service {
|
|||||||
db_restore: params.db_restore,
|
db_restore: params.db_restore,
|
||||||
progress: Default::default(),
|
progress: Default::default(),
|
||||||
taking_snapshot: AtomicBool::new(false),
|
taking_snapshot: AtomicBool::new(false),
|
||||||
|
restoring_snapshot: AtomicBool::new(false),
|
||||||
};
|
};
|
||||||
|
|
||||||
// create the root snapshot dir if it doesn't exist.
|
// create the root snapshot dir if it doesn't exist.
|
||||||
@ -436,6 +438,8 @@ impl Service {
|
|||||||
state_chunks_done: self.state_chunks.load(Ordering::SeqCst) as u32,
|
state_chunks_done: self.state_chunks.load(Ordering::SeqCst) as u32,
|
||||||
block_chunks_done: self.block_chunks.load(Ordering::SeqCst) as u32,
|
block_chunks_done: self.block_chunks.load(Ordering::SeqCst) as u32,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
self.restoring_snapshot.store(true, Ordering::SeqCst);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -490,8 +494,8 @@ impl Service {
|
|||||||
};
|
};
|
||||||
|
|
||||||
(match is_state {
|
(match is_state {
|
||||||
true => rest.feed_state(hash, chunk),
|
true => rest.feed_state(hash, chunk, &self.restoring_snapshot),
|
||||||
false => rest.feed_blocks(hash, chunk, &*self.engine),
|
false => rest.feed_blocks(hash, chunk, &*self.engine, &self.restoring_snapshot),
|
||||||
}.map(|_| rest.is_done()), rest.db.clone())
|
}.map(|_| rest.is_done()), rest.db.clone())
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -573,6 +577,7 @@ impl SnapshotService for Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn abort_restore(&self) {
|
fn abort_restore(&self) {
|
||||||
|
self.restoring_snapshot.store(false, Ordering::SeqCst);
|
||||||
*self.restoration.lock() = None;
|
*self.restoration.lock() = None;
|
||||||
*self.status.lock() = RestorationStatus::Inactive;
|
*self.status.lock() = RestorationStatus::Inactive;
|
||||||
}
|
}
|
||||||
|
@ -17,10 +17,11 @@
|
|||||||
//! Block chunker and rebuilder tests.
|
//! Block chunker and rebuilder tests.
|
||||||
|
|
||||||
use devtools::RandomTempPath;
|
use devtools::RandomTempPath;
|
||||||
|
use error::Error;
|
||||||
|
|
||||||
use blockchain::generator::{ChainGenerator, ChainIterator, BlockFinalizer};
|
use blockchain::generator::{ChainGenerator, ChainIterator, BlockFinalizer};
|
||||||
use blockchain::BlockChain;
|
use blockchain::BlockChain;
|
||||||
use snapshot::{chunk_blocks, BlockRebuilder, Progress};
|
use snapshot::{chunk_blocks, BlockRebuilder, Error as SnapshotError, Progress};
|
||||||
use snapshot::io::{PackedReader, PackedWriter, SnapshotReader, SnapshotWriter};
|
use snapshot::io::{PackedReader, PackedWriter, SnapshotReader, SnapshotWriter};
|
||||||
|
|
||||||
use util::{Mutex, snappy};
|
use util::{Mutex, snappy};
|
||||||
@ -28,6 +29,7 @@ use util::kvdb::{Database, DatabaseConfig};
|
|||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::AtomicBool;
|
||||||
|
|
||||||
fn chunk_and_restore(amount: u64) {
|
fn chunk_and_restore(amount: u64) {
|
||||||
let mut canon_chain = ChainGenerator::default();
|
let mut canon_chain = ChainGenerator::default();
|
||||||
@ -75,10 +77,11 @@ fn chunk_and_restore(amount: u64) {
|
|||||||
let mut rebuilder = BlockRebuilder::new(new_chain, new_db.clone(), &manifest).unwrap();
|
let mut rebuilder = BlockRebuilder::new(new_chain, new_db.clone(), &manifest).unwrap();
|
||||||
let reader = PackedReader::new(&snapshot_path).unwrap().unwrap();
|
let reader = PackedReader::new(&snapshot_path).unwrap().unwrap();
|
||||||
let engine = ::engines::NullEngine::new(Default::default(), Default::default());
|
let engine = ::engines::NullEngine::new(Default::default(), Default::default());
|
||||||
|
let flag = AtomicBool::new(true);
|
||||||
for chunk_hash in &reader.manifest().block_hashes {
|
for chunk_hash in &reader.manifest().block_hashes {
|
||||||
let compressed = reader.chunk(*chunk_hash).unwrap();
|
let compressed = reader.chunk(*chunk_hash).unwrap();
|
||||||
let chunk = snappy::decompress(&compressed).unwrap();
|
let chunk = snappy::decompress(&compressed).unwrap();
|
||||||
rebuilder.feed(&chunk, &engine).unwrap();
|
rebuilder.feed(&chunk, &engine, &flag).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
rebuilder.finalize(HashMap::new()).unwrap();
|
rebuilder.finalize(HashMap::new()).unwrap();
|
||||||
@ -93,3 +96,46 @@ fn chunk_and_restore_500() { chunk_and_restore(500) }
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn chunk_and_restore_40k() { chunk_and_restore(40000) }
|
fn chunk_and_restore_40k() { chunk_and_restore(40000) }
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn checks_flag() {
|
||||||
|
use ::rlp::{RlpStream, Stream};
|
||||||
|
use util::H256;
|
||||||
|
|
||||||
|
let mut stream = RlpStream::new_list(5);
|
||||||
|
|
||||||
|
stream.append(&100u64)
|
||||||
|
.append(&H256::default())
|
||||||
|
.append(&(!0u64));
|
||||||
|
|
||||||
|
stream.append_empty_data().append_empty_data();
|
||||||
|
|
||||||
|
let genesis = {
|
||||||
|
let mut canon_chain = ChainGenerator::default();
|
||||||
|
let mut finalizer = BlockFinalizer::default();
|
||||||
|
canon_chain.generate(&mut finalizer).unwrap()
|
||||||
|
};
|
||||||
|
|
||||||
|
let chunk = stream.out();
|
||||||
|
let path = RandomTempPath::create_dir();
|
||||||
|
|
||||||
|
let db_cfg = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
|
||||||
|
let db = Arc::new(Database::open(&db_cfg, path.as_str()).unwrap());
|
||||||
|
let chain = BlockChain::new(Default::default(), &genesis, db.clone());
|
||||||
|
let engine = ::engines::NullEngine::new(Default::default(), Default::default());
|
||||||
|
|
||||||
|
let manifest = ::snapshot::ManifestData {
|
||||||
|
state_hashes: Vec::new(),
|
||||||
|
block_hashes: Vec::new(),
|
||||||
|
state_root: ::util::sha3::SHA3_NULL_RLP,
|
||||||
|
block_number: 102,
|
||||||
|
block_hash: H256::default(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut rebuilder = BlockRebuilder::new(chain, db.clone(), &manifest).unwrap();
|
||||||
|
|
||||||
|
match rebuilder.feed(&chunk, &engine, &AtomicBool::new(false)) {
|
||||||
|
Err(Error::Snapshot(SnapshotError::RestorationAborted)) => {}
|
||||||
|
_ => panic!("Wrong result on abort flag set")
|
||||||
|
}
|
||||||
|
}
|
@ -16,10 +16,12 @@
|
|||||||
|
|
||||||
//! State snapshotting tests.
|
//! State snapshotting tests.
|
||||||
|
|
||||||
use snapshot::{chunk_state, Progress, StateRebuilder};
|
use snapshot::{chunk_state, Error as SnapshotError, Progress, StateRebuilder};
|
||||||
use snapshot::io::{PackedReader, PackedWriter, SnapshotReader, SnapshotWriter};
|
use snapshot::io::{PackedReader, PackedWriter, SnapshotReader, SnapshotWriter};
|
||||||
use super::helpers::{compare_dbs, StateProducer};
|
use super::helpers::{compare_dbs, StateProducer};
|
||||||
|
|
||||||
|
use error::Error;
|
||||||
|
|
||||||
use rand::{XorShiftRng, SeedableRng};
|
use rand::{XorShiftRng, SeedableRng};
|
||||||
use util::hash::H256;
|
use util::hash::H256;
|
||||||
use util::journaldb::{self, Algorithm};
|
use util::journaldb::{self, Algorithm};
|
||||||
@ -29,6 +31,7 @@ use util::Mutex;
|
|||||||
use devtools::RandomTempPath;
|
use devtools::RandomTempPath;
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::AtomicBool;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn snap_and_restore() {
|
fn snap_and_restore() {
|
||||||
@ -65,11 +68,13 @@ fn snap_and_restore() {
|
|||||||
let mut rebuilder = StateRebuilder::new(new_db.clone(), Algorithm::Archive);
|
let mut rebuilder = StateRebuilder::new(new_db.clone(), Algorithm::Archive);
|
||||||
let reader = PackedReader::new(&snap_file).unwrap().unwrap();
|
let reader = PackedReader::new(&snap_file).unwrap().unwrap();
|
||||||
|
|
||||||
|
let flag = AtomicBool::new(true);
|
||||||
|
|
||||||
for chunk_hash in &reader.manifest().state_hashes {
|
for chunk_hash in &reader.manifest().state_hashes {
|
||||||
let raw = reader.chunk(*chunk_hash).unwrap();
|
let raw = reader.chunk(*chunk_hash).unwrap();
|
||||||
let chunk = ::util::snappy::decompress(&raw).unwrap();
|
let chunk = ::util::snappy::decompress(&raw).unwrap();
|
||||||
|
|
||||||
rebuilder.feed(&chunk).unwrap();
|
rebuilder.feed(&chunk, &flag).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
assert_eq!(rebuilder.state_root(), state_root);
|
assert_eq!(rebuilder.state_root(), state_root);
|
||||||
@ -82,3 +87,52 @@ fn snap_and_restore() {
|
|||||||
|
|
||||||
compare_dbs(&old_db, new_db.as_hashdb());
|
compare_dbs(&old_db, new_db.as_hashdb());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn checks_flag() {
|
||||||
|
let mut producer = StateProducer::new();
|
||||||
|
let mut rng = XorShiftRng::from_seed([5, 6, 7, 8]);
|
||||||
|
let mut old_db = MemoryDB::new();
|
||||||
|
let db_cfg = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
|
||||||
|
|
||||||
|
for _ in 0..10 {
|
||||||
|
producer.tick(&mut rng, &mut old_db);
|
||||||
|
}
|
||||||
|
|
||||||
|
let snap_dir = RandomTempPath::create_dir();
|
||||||
|
let mut snap_file = snap_dir.as_path().to_owned();
|
||||||
|
snap_file.push("SNAP");
|
||||||
|
|
||||||
|
let state_root = producer.state_root();
|
||||||
|
let writer = Mutex::new(PackedWriter::new(&snap_file).unwrap());
|
||||||
|
|
||||||
|
let state_hashes = chunk_state(&old_db, &state_root, &writer, &Progress::default()).unwrap();
|
||||||
|
|
||||||
|
writer.into_inner().finish(::snapshot::ManifestData {
|
||||||
|
state_hashes: state_hashes,
|
||||||
|
block_hashes: Vec::new(),
|
||||||
|
state_root: state_root,
|
||||||
|
block_number: 0,
|
||||||
|
block_hash: H256::default(),
|
||||||
|
}).unwrap();
|
||||||
|
|
||||||
|
let mut db_path = snap_dir.as_path().to_owned();
|
||||||
|
db_path.push("db");
|
||||||
|
{
|
||||||
|
let new_db = Arc::new(Database::open(&db_cfg, &db_path.to_string_lossy()).unwrap());
|
||||||
|
let mut rebuilder = StateRebuilder::new(new_db.clone(), Algorithm::Archive);
|
||||||
|
let reader = PackedReader::new(&snap_file).unwrap().unwrap();
|
||||||
|
|
||||||
|
let flag = AtomicBool::new(false);
|
||||||
|
|
||||||
|
for chunk_hash in &reader.manifest().state_hashes {
|
||||||
|
let raw = reader.chunk(*chunk_hash).unwrap();
|
||||||
|
let chunk = ::util::snappy::decompress(&raw).unwrap();
|
||||||
|
|
||||||
|
match rebuilder.feed(&chunk, &flag) {
|
||||||
|
Err(Error::Snapshot(SnapshotError::RestorationAborted)) => {},
|
||||||
|
_ => panic!("unexpected result when feeding with flag off"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -162,7 +162,7 @@ impl Spec {
|
|||||||
/// Get the configured Network ID.
|
/// Get the configured Network ID.
|
||||||
pub fn network_id(&self) -> usize { self.params.network_id }
|
pub fn network_id(&self) -> usize { self.params.network_id }
|
||||||
|
|
||||||
/// Get the configured Network ID.
|
/// Get the configured subprotocol name.
|
||||||
pub fn subprotocol_name(&self) -> String { self.params.subprotocol_name.clone() }
|
pub fn subprotocol_name(&self) -> String { self.params.subprotocol_name.clone() }
|
||||||
|
|
||||||
/// Get the configured network fork block.
|
/// Get the configured network fork block.
|
||||||
|
1
js/.gitignore
vendored
1
js/.gitignore
vendored
@ -6,3 +6,4 @@ build
|
|||||||
.dist
|
.dist
|
||||||
.happypack
|
.happypack
|
||||||
.npmjs
|
.npmjs
|
||||||
|
.eslintcache
|
||||||
|
@ -7,6 +7,6 @@ JavaScript APIs and UIs for Parity.
|
|||||||
0. Install [Node](https://nodejs.org/) if not already available
|
0. Install [Node](https://nodejs.org/) if not already available
|
||||||
0. Change to the `js` directory inside `parity/`
|
0. Change to the `js` directory inside `parity/`
|
||||||
0. Install the npm modules via `npm install`
|
0. Install the npm modules via `npm install`
|
||||||
0. Parity should be run with `parity --signer-no-validation [...options]` (where `options` can be `--chain testnet`)
|
0. Parity should be run with `parity --ui-no-validation [...options]` (where `options` can be `--chain testnet`)
|
||||||
0. Start the development environment via `npm start`
|
0. Start the development environment via `npm start`
|
||||||
0. Connect to the [UI](http://localhost:3000)
|
0. Connect to the [UI](http://localhost:3000)
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "parity.js",
|
"name": "parity.js",
|
||||||
"version": "0.2.23",
|
"version": "0.2.37",
|
||||||
"main": "release/index.js",
|
"main": "release/index.js",
|
||||||
"jsnext:main": "src/index.js",
|
"jsnext:main": "src/index.js",
|
||||||
"author": "Parity Team <admin@parity.io>",
|
"author": "Parity Team <admin@parity.io>",
|
||||||
@ -39,9 +39,11 @@
|
|||||||
"clean": "rm -rf ./build ./coverage",
|
"clean": "rm -rf ./build ./coverage",
|
||||||
"coveralls": "npm run testCoverage && coveralls < coverage/lcov.info",
|
"coveralls": "npm run testCoverage && coveralls < coverage/lcov.info",
|
||||||
"lint": "eslint --ignore-path .gitignore ./src/",
|
"lint": "eslint --ignore-path .gitignore ./src/",
|
||||||
|
"lint:cached": "eslint --cache --ignore-path .gitignore ./src/",
|
||||||
"test": "mocha 'src/**/*.spec.js'",
|
"test": "mocha 'src/**/*.spec.js'",
|
||||||
"test:coverage": "istanbul cover _mocha -- 'src/**/*.spec.js'",
|
"test:coverage": "istanbul cover _mocha -- 'src/**/*.spec.js'",
|
||||||
"test:e2e": "mocha 'src/**/*.e2e.js'"
|
"test:e2e": "mocha 'src/**/*.e2e.js'",
|
||||||
|
"prepush": "npm run lint:cached"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"babel-cli": "^6.10.1",
|
"babel-cli": "^6.10.1",
|
||||||
@ -84,6 +86,7 @@
|
|||||||
"happypack": "^2.2.1",
|
"happypack": "^2.2.1",
|
||||||
"history": "^2.0.0",
|
"history": "^2.0.0",
|
||||||
"html-loader": "^0.4.4",
|
"html-loader": "^0.4.4",
|
||||||
|
"husky": "^0.11.9",
|
||||||
"ignore-styles": "2.0.0",
|
"ignore-styles": "2.0.0",
|
||||||
"image-webpack-loader": "^1.8.0",
|
"image-webpack-loader": "^1.8.0",
|
||||||
"istanbul": "^1.0.0-alpha.2",
|
"istanbul": "^1.0.0-alpha.2",
|
||||||
@ -97,6 +100,7 @@
|
|||||||
"postcss-loader": "^0.8.1",
|
"postcss-loader": "^0.8.1",
|
||||||
"postcss-nested": "^1.0.0",
|
"postcss-nested": "^1.0.0",
|
||||||
"postcss-simple-vars": "^3.0.0",
|
"postcss-simple-vars": "^3.0.0",
|
||||||
|
"raw-loader": "^0.5.1",
|
||||||
"react-addons-test-utils": "^15.3.0",
|
"react-addons-test-utils": "^15.3.0",
|
||||||
"react-copy-to-clipboard": "^4.2.3",
|
"react-copy-to-clipboard": "^4.2.3",
|
||||||
"react-hot-loader": "^1.3.0",
|
"react-hot-loader": "^1.3.0",
|
||||||
@ -115,9 +119,11 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"bignumber.js": "^2.3.0",
|
"bignumber.js": "^2.3.0",
|
||||||
"blockies": "0.0.2",
|
"blockies": "0.0.2",
|
||||||
|
"brace": "^0.9.0",
|
||||||
"bytes": "^2.4.0",
|
"bytes": "^2.4.0",
|
||||||
"chart.js": "^2.3.0",
|
"chart.js": "^2.3.0",
|
||||||
"es6-promise": "^3.2.1",
|
"es6-promise": "^3.2.1",
|
||||||
|
"ethereumjs-tx": "^1.1.2",
|
||||||
"file-saver": "^1.3.3",
|
"file-saver": "^1.3.3",
|
||||||
"format-json": "^1.0.3",
|
"format-json": "^1.0.3",
|
||||||
"format-number": "^2.0.1",
|
"format-number": "^2.0.1",
|
||||||
@ -134,9 +140,11 @@
|
|||||||
"moment": "^2.14.1",
|
"moment": "^2.14.1",
|
||||||
"qs": "^6.3.0",
|
"qs": "^6.3.0",
|
||||||
"react": "^15.2.1",
|
"react": "^15.2.1",
|
||||||
|
"react-ace": "^4.0.0",
|
||||||
"react-addons-css-transition-group": "^15.2.1",
|
"react-addons-css-transition-group": "^15.2.1",
|
||||||
"react-chartjs-2": "^1.5.0",
|
"react-chartjs-2": "^1.5.0",
|
||||||
"react-dom": "^15.2.1",
|
"react-dom": "^15.2.1",
|
||||||
|
"react-dropzone": "^3.7.3",
|
||||||
"react-redux": "^4.4.5",
|
"react-redux": "^4.4.5",
|
||||||
"react-router": "^2.6.1",
|
"react-router": "^2.6.1",
|
||||||
"react-router-redux": "^4.0.5",
|
"react-router-redux": "^4.0.5",
|
||||||
@ -147,10 +155,14 @@
|
|||||||
"redux-actions": "^0.10.1",
|
"redux-actions": "^0.10.1",
|
||||||
"redux-thunk": "^2.1.0",
|
"redux-thunk": "^2.1.0",
|
||||||
"rlp": "^2.0.0",
|
"rlp": "^2.0.0",
|
||||||
|
"scryptsy": "^2.0.0",
|
||||||
|
"solc": "ngotchac/solc-js",
|
||||||
"store": "^1.3.20",
|
"store": "^1.3.20",
|
||||||
"utf8": "^2.1.1",
|
"utf8": "^2.1.1",
|
||||||
|
"valid-url": "^1.0.9",
|
||||||
"validator": "^5.7.0",
|
"validator": "^5.7.0",
|
||||||
"web3": "^0.17.0-beta",
|
"web3": "^0.17.0-beta",
|
||||||
"whatwg-fetch": "^1.0.0"
|
"whatwg-fetch": "^1.0.0",
|
||||||
|
"worker-loader": "^0.7.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -63,7 +63,7 @@ if [ "$BRANCH" == "master" ]; then
|
|||||||
|
|
||||||
echo "*** Publishing $PACKAGE to npmjs"
|
echo "*** Publishing $PACKAGE to npmjs"
|
||||||
cd .npmjs
|
cd .npmjs
|
||||||
npm publish --access public
|
npm publish --access public || true
|
||||||
cd ../..
|
cd ../..
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
@ -34,7 +34,7 @@ describe('api/Api', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('interface', () => {
|
describe('interface', () => {
|
||||||
const api = new Api(new Api.Transport.Http(TEST_HTTP_URL));
|
const api = new Api(new Api.Transport.Http(TEST_HTTP_URL, -1));
|
||||||
|
|
||||||
Object.keys(ethereumRpc).sort().forEach((endpoint) => {
|
Object.keys(ethereumRpc).sort().forEach((endpoint) => {
|
||||||
describe(endpoint, () => {
|
describe(endpoint, () => {
|
||||||
|
@ -136,27 +136,30 @@ export default class Contract {
|
|||||||
}
|
}
|
||||||
|
|
||||||
parseEventLogs (logs) {
|
parseEventLogs (logs) {
|
||||||
return logs.map((log) => {
|
return logs
|
||||||
const signature = log.topics[0].substr(2);
|
.map((log) => {
|
||||||
const event = this.events.find((evt) => evt.signature === signature);
|
const signature = log.topics[0].substr(2);
|
||||||
|
const event = this.events.find((evt) => evt.signature === signature);
|
||||||
|
|
||||||
if (!event) {
|
if (!event) {
|
||||||
throw new Error(`Unable to find event matching signature ${signature}`);
|
console.warn(`Unable to find event matching signature ${signature}`);
|
||||||
}
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
const decoded = event.decodeLog(log.topics, log.data);
|
const decoded = event.decodeLog(log.topics, log.data);
|
||||||
|
|
||||||
log.params = {};
|
log.params = {};
|
||||||
log.event = event.name;
|
log.event = event.name;
|
||||||
|
|
||||||
decoded.params.forEach((param) => {
|
decoded.params.forEach((param) => {
|
||||||
const { type, value } = param.token;
|
const { type, value } = param.token;
|
||||||
|
|
||||||
log.params[param.name] = { type, value };
|
log.params[param.name] = { type, value };
|
||||||
});
|
});
|
||||||
|
|
||||||
return log;
|
return log;
|
||||||
});
|
})
|
||||||
|
.filter((log) => log);
|
||||||
}
|
}
|
||||||
|
|
||||||
parseTransactionEvents (receipt) {
|
parseTransactionEvents (receipt) {
|
||||||
@ -306,7 +309,6 @@ export default class Contract {
|
|||||||
try {
|
try {
|
||||||
subscriptions[idx].callback(null, this.parseEventLogs(logs));
|
subscriptions[idx].callback(null, this.parseEventLogs(logs));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.unsubscribe(idx);
|
|
||||||
console.error('_sendSubscriptionChanges', error);
|
console.error('_sendSubscriptionChanges', error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
@ -25,7 +25,7 @@ import Api from '../api';
|
|||||||
import Contract from './contract';
|
import Contract from './contract';
|
||||||
import { isInstanceOf, isFunction } from '../util/types';
|
import { isInstanceOf, isFunction } from '../util/types';
|
||||||
|
|
||||||
const transport = new Api.Transport.Http(TEST_HTTP_URL);
|
const transport = new Api.Transport.Http(TEST_HTTP_URL, -1);
|
||||||
const eth = new Api(transport);
|
const eth = new Api(transport);
|
||||||
|
|
||||||
describe('api/contract/Contract', () => {
|
describe('api/contract/Contract', () => {
|
||||||
@ -119,19 +119,6 @@ describe('api/contract/Contract', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('parseTransactionEvents', () => {
|
describe('parseTransactionEvents', () => {
|
||||||
it('checks for unmatched signatures', () => {
|
|
||||||
const contract = new Contract(eth, [{ anonymous: false, name: 'Message', type: 'event' }]);
|
|
||||||
expect(() => contract.parseTransactionEvents({
|
|
||||||
logs: [{
|
|
||||||
data: '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000063cf90d3f0410092fc0fca41846f5962239791950000000000000000000000000000000000000000000000000000000056e6c85f0000000000000000000000000000000000000000000000000001000000004fcd00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000d706f7374286d6573736167652900000000000000000000000000000000000000',
|
|
||||||
topics: [
|
|
||||||
'0x954ba6c157daf8a26539574ffa64203c044691aa57251af95f4b48d85ec00dd5',
|
|
||||||
'0x0000000000000000000000000000000000000000000000000001000000004fe0'
|
|
||||||
]
|
|
||||||
}]
|
|
||||||
})).to.throw(/event matching signature/);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('parses a transaction log into the data', () => {
|
it('parses a transaction log into the data', () => {
|
||||||
const contract = new Contract(eth, [
|
const contract = new Contract(eth, [
|
||||||
{
|
{
|
||||||
|
@ -93,6 +93,10 @@ export function inFilter (options) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function inHex (str) {
|
export function inHex (str) {
|
||||||
|
if (str && str.toString) {
|
||||||
|
str = str.toString(16);
|
||||||
|
}
|
||||||
|
|
||||||
if (str && str.substr(0, 2) === '0x') {
|
if (str && str.substr(0, 2) === '0x') {
|
||||||
return str.toLowerCase();
|
return str.toLowerCase();
|
||||||
}
|
}
|
||||||
|
@ -19,7 +19,7 @@ import { TEST_HTTP_URL, mockHttp } from '../../../../test/mockRpc';
|
|||||||
import Http from '../../transport/http';
|
import Http from '../../transport/http';
|
||||||
import Db from './db';
|
import Db from './db';
|
||||||
|
|
||||||
const instance = new Db(new Http(TEST_HTTP_URL));
|
const instance = new Db(new Http(TEST_HTTP_URL, -1));
|
||||||
|
|
||||||
describe('api/rpc/Db', () => {
|
describe('api/rpc/Db', () => {
|
||||||
let scope;
|
let scope;
|
||||||
|
@ -20,7 +20,7 @@ import { isBigNumber } from '../../../../test/types';
|
|||||||
import Http from '../../transport/http';
|
import Http from '../../transport/http';
|
||||||
import Eth from './eth';
|
import Eth from './eth';
|
||||||
|
|
||||||
const instance = new Eth(new Http(TEST_HTTP_URL));
|
const instance = new Eth(new Http(TEST_HTTP_URL, -1));
|
||||||
|
|
||||||
describe('rpc/Eth', () => {
|
describe('rpc/Eth', () => {
|
||||||
const address = '0x63Cf90D3f0410092FC0fca41846f596223979195';
|
const address = '0x63Cf90D3f0410092FC0fca41846f596223979195';
|
||||||
|
@ -20,7 +20,7 @@ import { isBigNumber } from '../../../../test/types';
|
|||||||
import Http from '../../transport/http';
|
import Http from '../../transport/http';
|
||||||
import Net from './net';
|
import Net from './net';
|
||||||
|
|
||||||
const instance = new Net(new Http(TEST_HTTP_URL));
|
const instance = new Net(new Http(TEST_HTTP_URL, -1));
|
||||||
|
|
||||||
describe('api/rpc/Net', () => {
|
describe('api/rpc/Net', () => {
|
||||||
describe('peerCount', () => {
|
describe('peerCount', () => {
|
||||||
|
@ -60,6 +60,11 @@ export default class Parity {
|
|||||||
.then(outNumber);
|
.then(outNumber);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
dappsInterface () {
|
||||||
|
return this._transport
|
||||||
|
.execute('parity_dappsInterface');
|
||||||
|
}
|
||||||
|
|
||||||
defaultExtraData () {
|
defaultExtraData () {
|
||||||
return this._transport
|
return this._transport
|
||||||
.execute('parity_defaultExtraData');
|
.execute('parity_defaultExtraData');
|
||||||
@ -176,6 +181,12 @@ export default class Parity {
|
|||||||
.then(outAddress);
|
.then(outAddress);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
nextNonce (account) {
|
||||||
|
return this._transport
|
||||||
|
.execute('parity_nextNonce', inAddress(account))
|
||||||
|
.then(outNumber);
|
||||||
|
}
|
||||||
|
|
||||||
nodeName () {
|
nodeName () {
|
||||||
return this._transport
|
return this._transport
|
||||||
.execute('parity_nodeName');
|
.execute('parity_nodeName');
|
||||||
|
@ -20,7 +20,7 @@ import { isBigNumber } from '../../../../test/types';
|
|||||||
import Http from '../../transport/http';
|
import Http from '../../transport/http';
|
||||||
import Parity from './parity';
|
import Parity from './parity';
|
||||||
|
|
||||||
const instance = new Parity(new Http(TEST_HTTP_URL));
|
const instance = new Parity(new Http(TEST_HTTP_URL, -1));
|
||||||
|
|
||||||
describe('api/rpc/parity', () => {
|
describe('api/rpc/parity', () => {
|
||||||
describe('accountsInfo', () => {
|
describe('accountsInfo', () => {
|
||||||
|
@ -19,7 +19,7 @@ import { TEST_HTTP_URL, mockHttp } from '../../../../test/mockRpc';
|
|||||||
import Http from '../../transport/http';
|
import Http from '../../transport/http';
|
||||||
import Personal from './personal';
|
import Personal from './personal';
|
||||||
|
|
||||||
const instance = new Personal(new Http(TEST_HTTP_URL));
|
const instance = new Personal(new Http(TEST_HTTP_URL, -1));
|
||||||
|
|
||||||
describe('rpc/Personal', () => {
|
describe('rpc/Personal', () => {
|
||||||
const account = '0x63cf90d3f0410092fc0fca41846f596223979195';
|
const account = '0x63cf90d3f0410092fc0fca41846f596223979195';
|
||||||
|
@ -14,7 +14,7 @@
|
|||||||
// You should have received a copy of the GNU General Public License
|
// You should have received a copy of the GNU General Public License
|
||||||
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
import { inNumber16 } from '../../format/input';
|
import { inNumber16, inData } from '../../format/input';
|
||||||
import { outSignerRequest } from '../../format/output';
|
import { outSignerRequest } from '../../format/output';
|
||||||
|
|
||||||
export default class Signer {
|
export default class Signer {
|
||||||
@ -27,6 +27,11 @@ export default class Signer {
|
|||||||
.execute('signer_confirmRequest', inNumber16(requestId), options, password);
|
.execute('signer_confirmRequest', inNumber16(requestId), options, password);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
confirmRequestRaw (requestId, data) {
|
||||||
|
return this._transport
|
||||||
|
.execute('signer_confirmRequestRaw', inNumber16(requestId), inData(data));
|
||||||
|
}
|
||||||
|
|
||||||
generateAuthorizationToken () {
|
generateAuthorizationToken () {
|
||||||
return this._transport
|
return this._transport
|
||||||
.execute('signer_generateAuthorizationToken');
|
.execute('signer_generateAuthorizationToken');
|
||||||
|
@ -19,7 +19,7 @@ import { TEST_HTTP_URL, mockHttp } from '../../../../test/mockRpc';
|
|||||||
import Http from '../../transport/http';
|
import Http from '../../transport/http';
|
||||||
import Trace from './trace';
|
import Trace from './trace';
|
||||||
|
|
||||||
const instance = new Trace(new Http(TEST_HTTP_URL));
|
const instance = new Trace(new Http(TEST_HTTP_URL, -1));
|
||||||
|
|
||||||
describe('api/rpc/Trace', () => {
|
describe('api/rpc/Trace', () => {
|
||||||
let scope;
|
let scope;
|
||||||
|
@ -19,7 +19,7 @@ import { TEST_HTTP_URL, mockHttp } from '../../../../test/mockRpc';
|
|||||||
import Http from '../../transport/http';
|
import Http from '../../transport/http';
|
||||||
import Web3 from './web3';
|
import Web3 from './web3';
|
||||||
|
|
||||||
const instance = new Web3(new Http(TEST_HTTP_URL));
|
const instance = new Web3(new Http(TEST_HTTP_URL, -1));
|
||||||
|
|
||||||
describe('api/rpc/Web3', () => {
|
describe('api/rpc/Web3', () => {
|
||||||
let scope;
|
let scope;
|
||||||
|
@ -107,7 +107,6 @@ export default class Manager {
|
|||||||
callback(error, data);
|
callback(error, data);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Unable to update callback for subscriptionId ${subscriptionId}`, error);
|
console.error(`Unable to update callback for subscriptionId ${subscriptionId}`, error);
|
||||||
this.unsubscribe(subscriptionId);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -19,11 +19,14 @@ import JsonRpcBase from '../jsonRpcBase';
|
|||||||
|
|
||||||
/* global fetch */
|
/* global fetch */
|
||||||
export default class Http extends JsonRpcBase {
|
export default class Http extends JsonRpcBase {
|
||||||
constructor (url) {
|
constructor (url, connectTimeout = 1000) {
|
||||||
super();
|
super();
|
||||||
|
|
||||||
this._connected = true;
|
this._connected = true;
|
||||||
this._url = url;
|
this._url = url;
|
||||||
|
this._connectTimeout = connectTimeout;
|
||||||
|
|
||||||
|
this._pollConnection();
|
||||||
}
|
}
|
||||||
|
|
||||||
_encodeOptions (method, params) {
|
_encodeOptions (method, params) {
|
||||||
@ -77,4 +80,17 @@ export default class Http extends JsonRpcBase {
|
|||||||
return response.result;
|
return response.result;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_pollConnection = () => {
|
||||||
|
if (this._connectTimeout <= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextTimeout = () => setTimeout(this._pollConnection, this._connectTimeout);
|
||||||
|
|
||||||
|
this
|
||||||
|
.execute('net_listening')
|
||||||
|
.then(nextTimeout)
|
||||||
|
.catch(nextTimeout);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -17,7 +17,7 @@
|
|||||||
import { TEST_HTTP_URL, mockHttp } from '../../../../test/mockRpc';
|
import { TEST_HTTP_URL, mockHttp } from '../../../../test/mockRpc';
|
||||||
import Http from './http';
|
import Http from './http';
|
||||||
|
|
||||||
const transport = new Http(TEST_HTTP_URL);
|
const transport = new Http(TEST_HTTP_URL, -1);
|
||||||
|
|
||||||
describe('api/transport/Http', () => {
|
describe('api/transport/Http', () => {
|
||||||
describe('instance', () => {
|
describe('instance', () => {
|
||||||
|
@ -24,6 +24,7 @@ import owned from './owned.json';
|
|||||||
import registry from './registry.json';
|
import registry from './registry.json';
|
||||||
import signaturereg from './signaturereg.json';
|
import signaturereg from './signaturereg.json';
|
||||||
import tokenreg from './tokenreg.json';
|
import tokenreg from './tokenreg.json';
|
||||||
|
import wallet from './wallet.json';
|
||||||
|
|
||||||
export {
|
export {
|
||||||
basiccoin,
|
basiccoin,
|
||||||
@ -35,5 +36,6 @@ export {
|
|||||||
owned,
|
owned,
|
||||||
registry,
|
registry,
|
||||||
signaturereg,
|
signaturereg,
|
||||||
tokenreg
|
tokenreg,
|
||||||
|
wallet
|
||||||
};
|
};
|
||||||
|
1
js/src/contracts/abi/wallet.json
Normal file
1
js/src/contracts/abi/wallet.json
Normal file
@ -0,0 +1 @@
|
|||||||
|
[{"constant":false,"inputs":[{"name":"_owner","type":"address"}],"name":"removeOwner","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"isOwner","outputs":[{"name":"","type":"bool"}],"type":"function"},{"constant":true,"inputs":[],"name":"m_numOwners","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"m_lastDay","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[],"name":"resetSpentToday","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"m_spentToday","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"_owner","type":"address"}],"name":"addOwner","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"m_required","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"_h","type":"bytes32"}],"name":"confirm","outputs":[{"name":"","type":"bool"}],"type":"function"},{"constant":false,"inputs":[{"name":"_newLimit","type":"uint256"}],"name":"setDailyLimit","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"execute","outputs":[{"name":"_r","type":"bytes32"}],"type":"function"},{"constant":false,"inputs":[{"name":"_operation","type":"bytes32"}],"name":"revoke","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"_newRequired","type":"uint256"}],"name":"changeRequirement","outputs":[],"type":"function"},{"constant":true,"inputs":[{"name":"_operation","type":"bytes32"},{"name":"_owner","type":"address"}],"name":"hasConfirmed","outputs":[{"name":"","type":"bool"}],"type":"function"},{"constant":true,"inputs":[{"name":"ownerIndex","type":"uint256"}],"name":"getOwner","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"}],"name":"kill","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"}],"name":"changeOwner","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"m_dailyLimit","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"inputs":[{"name":"_owners","type":"address[]"},{"name":"_required","type":"uint256"},{"name":"_daylimit","type":"uint256"}],"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"owner","type":"address"},{"indexed":false,"name":"operation","type":"bytes32"}],"name":"Confirmation","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"owner","type":"address"},{"indexed":false,"name":"operation","type":"bytes32"}],"name":"Revoke","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"oldOwner","type":"address"},{"indexed":false,"name":"newOwner","type":"address"}],"name":"OwnerChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newOwner","type":"address"}],"name":"OwnerAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"oldOwner","type":"address"}],"name":"OwnerRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newRequirement","type":"uint256"}],"name":"RequirementChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_from","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"owner","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"to","type":"address"},{"indexed":false,"name":"data","type":"bytes"}],"name":"SingleTransact","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"owner","type":"address"},{"indexed":false,"name":"operation","type":"bytes32"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"to","type":"address"},{"indexed":false,"name":"data","type":"bytes"}],"name":"MultiTransact","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"operation","type":"bytes32"},{"indexed":false,"name":"initiator","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"to","type":"address"},{"indexed":false,"name":"data","type":"bytes"}],"name":"ConfirmationNeeded","type":"event"}]
|
60
js/src/contracts/snippets/human-standard-token.sol
Normal file
60
js/src/contracts/snippets/human-standard-token.sol
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
/*
|
||||||
|
This Token Contract implements the standard token functionality (https://github.com/ethereum/EIPs/issues/20) as well as the following OPTIONAL extras intended for use by humans.
|
||||||
|
|
||||||
|
In other words. This is intended for deployment in something like a Token Factory or Mist wallet, and then used by humans.
|
||||||
|
Imagine coins, currencies, shares, voting weight, etc.
|
||||||
|
Machine-based, rapid creation of many tokens would not necessarily need these extra features or will be minted in other manners.
|
||||||
|
|
||||||
|
1) Initial Finite Supply (upon creation one specifies how much is minted).
|
||||||
|
2) In the absence of a token registry: Optional Decimal, Symbol & Name.
|
||||||
|
3) Optional approveAndCall() functionality to notify a contract if an approval() has occurred.
|
||||||
|
|
||||||
|
.*/
|
||||||
|
|
||||||
|
import "StandardToken.sol";
|
||||||
|
|
||||||
|
contract HumanStandardToken is StandardToken {
|
||||||
|
|
||||||
|
function () {
|
||||||
|
//if ether is sent to this address, send it back.
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Public variables of the token */
|
||||||
|
|
||||||
|
/*
|
||||||
|
NOTE:
|
||||||
|
The following variables are OPTIONAL vanities. One does not have to include them.
|
||||||
|
They allow one to customise the token contract & in no way influences the core functionality.
|
||||||
|
Some wallets/interfaces might not even bother to look at this information.
|
||||||
|
*/
|
||||||
|
string public name; //fancy name: eg Simon Bucks
|
||||||
|
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
|
||||||
|
string public symbol; //An identifier: eg SBX
|
||||||
|
string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme.
|
||||||
|
|
||||||
|
function HumanStandardToken(
|
||||||
|
uint256 _initialAmount,
|
||||||
|
string _tokenName,
|
||||||
|
uint8 _decimalUnits,
|
||||||
|
string _tokenSymbol
|
||||||
|
) {
|
||||||
|
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
|
||||||
|
totalSupply = _initialAmount; // Update total supply
|
||||||
|
name = _tokenName; // Set the name for display purposes
|
||||||
|
decimals = _decimalUnits; // Amount of decimals for display purposes
|
||||||
|
symbol = _tokenSymbol; // Set the symbol for display purposes
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Approves and then calls the receiving contract */
|
||||||
|
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
|
||||||
|
allowed[msg.sender][_spender] = _value;
|
||||||
|
Approval(msg.sender, _spender, _value);
|
||||||
|
|
||||||
|
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
|
||||||
|
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
|
||||||
|
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
|
||||||
|
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
55
js/src/contracts/snippets/standard-token.sol
Normal file
55
js/src/contracts/snippets/standard-token.sol
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
/*
|
||||||
|
You should inherit from StandardToken or, for a token like you would want to
|
||||||
|
deploy in something like Mist, see HumanStandardToken.sol.
|
||||||
|
(This implements ONLY the standard functions and NOTHING else.
|
||||||
|
If you deploy this, you won't have anything useful.)
|
||||||
|
|
||||||
|
Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20
|
||||||
|
.*/
|
||||||
|
|
||||||
|
import "Token.sol";
|
||||||
|
|
||||||
|
contract StandardToken is Token {
|
||||||
|
|
||||||
|
function transfer(address _to, uint256 _value) returns (bool success) {
|
||||||
|
//Default assumes totalSupply can't be over max (2^256 - 1).
|
||||||
|
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
|
||||||
|
//Replace the if with this one instead.
|
||||||
|
//if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
|
||||||
|
if (balances[msg.sender] >= _value && _value > 0) {
|
||||||
|
balances[msg.sender] -= _value;
|
||||||
|
balances[_to] += _value;
|
||||||
|
Transfer(msg.sender, _to, _value);
|
||||||
|
return true;
|
||||||
|
} else { return false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
|
||||||
|
//same as above. Replace this line with the following if you want to protect against wrapping uints.
|
||||||
|
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
|
||||||
|
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
|
||||||
|
balances[_to] += _value;
|
||||||
|
balances[_from] -= _value;
|
||||||
|
allowed[_from][msg.sender] -= _value;
|
||||||
|
Transfer(_from, _to, _value);
|
||||||
|
return true;
|
||||||
|
} else { return false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function balanceOf(address _owner) constant returns (uint256 balance) {
|
||||||
|
return balances[_owner];
|
||||||
|
}
|
||||||
|
|
||||||
|
function approve(address _spender, uint256 _value) returns (bool success) {
|
||||||
|
allowed[msg.sender][_spender] = _value;
|
||||||
|
Approval(msg.sender, _spender, _value);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
|
||||||
|
return allowed[_owner][_spender];
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping (address => uint256) balances;
|
||||||
|
mapping (address => mapping (address => uint256)) allowed;
|
||||||
|
}
|
47
js/src/contracts/snippets/token.sol
Normal file
47
js/src/contracts/snippets/token.sol
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
// Abstract contract for the full ERC 20 Token standard
|
||||||
|
// https://github.com/ethereum/EIPs/issues/20
|
||||||
|
|
||||||
|
contract Token {
|
||||||
|
/* This is a slight change to the ERC20 base standard.
|
||||||
|
function totalSupply() constant returns (uint256 supply);
|
||||||
|
is replaced with:
|
||||||
|
uint256 public totalSupply;
|
||||||
|
This automatically creates a getter function for the totalSupply.
|
||||||
|
This is moved to the base contract since public getter functions are not
|
||||||
|
currently recognised as an implementation of the matching abstract
|
||||||
|
function by the compiler.
|
||||||
|
*/
|
||||||
|
/// total amount of tokens
|
||||||
|
uint256 public totalSupply;
|
||||||
|
|
||||||
|
/// @param _owner The address from which the balance will be retrieved
|
||||||
|
/// @return The balance
|
||||||
|
function balanceOf(address _owner) constant returns (uint256 balance);
|
||||||
|
|
||||||
|
/// @notice send `_value` token to `_to` from `msg.sender`
|
||||||
|
/// @param _to The address of the recipient
|
||||||
|
/// @param _value The amount of token to be transferred
|
||||||
|
/// @return Whether the transfer was successful or not
|
||||||
|
function transfer(address _to, uint256 _value) returns (bool success);
|
||||||
|
|
||||||
|
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
|
||||||
|
/// @param _from The address of the sender
|
||||||
|
/// @param _to The address of the recipient
|
||||||
|
/// @param _value The amount of token to be transferred
|
||||||
|
/// @return Whether the transfer was successful or not
|
||||||
|
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
|
||||||
|
|
||||||
|
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
|
||||||
|
/// @param _spender The address of the account able to transfer the tokens
|
||||||
|
/// @param _value The amount of wei to be approved for transfer
|
||||||
|
/// @return Whether the approval was successful or not
|
||||||
|
function approve(address _spender, uint256 _value) returns (bool success);
|
||||||
|
|
||||||
|
/// @param _owner The address of the account owning tokens
|
||||||
|
/// @param _spender The address of the account able to transfer the tokens
|
||||||
|
/// @return Amount of remaining tokens allowed to spent
|
||||||
|
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
|
||||||
|
|
||||||
|
event Transfer(address indexed _from, address indexed _to, uint256 _value);
|
||||||
|
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
|
||||||
|
}
|
@ -28,26 +28,26 @@ export function attachInterface () {
|
|||||||
return Promise
|
return Promise
|
||||||
.all([
|
.all([
|
||||||
registry.getAddress.call({}, [api.util.sha3('githubhint'), 'A']),
|
registry.getAddress.call({}, [api.util.sha3('githubhint'), 'A']),
|
||||||
api.eth.accounts(),
|
|
||||||
api.parity.accounts()
|
api.parity.accounts()
|
||||||
]);
|
]);
|
||||||
})
|
})
|
||||||
.then(([address, addresses, accountsInfo]) => {
|
.then(([address, accountsInfo]) => {
|
||||||
accountsInfo = accountsInfo || {};
|
|
||||||
console.log(`githubhint was found at ${address}`);
|
console.log(`githubhint was found at ${address}`);
|
||||||
|
|
||||||
const contract = api.newContract(abis.githubhint, address);
|
const contract = api.newContract(abis.githubhint, address);
|
||||||
const accounts = addresses.reduce((obj, address) => {
|
const accounts = Object
|
||||||
const info = accountsInfo[address] || {};
|
.keys(accountsInfo)
|
||||||
|
.filter((address) => accountsInfo[address].uuid)
|
||||||
|
.reduce((obj, address) => {
|
||||||
|
const account = accountsInfo[address];
|
||||||
|
|
||||||
return Object.assign(obj, {
|
return Object.assign(obj, {
|
||||||
[address]: {
|
[address]: {
|
||||||
address,
|
address,
|
||||||
name: info.name,
|
name: account.name
|
||||||
uuid: info.uuid
|
}
|
||||||
}
|
});
|
||||||
});
|
}, {});
|
||||||
}, {});
|
|
||||||
const fromAddress = Object.keys(accounts)[0];
|
const fromAddress = Object.keys(accounts)[0];
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
@ -49,3 +49,15 @@
|
|||||||
padding-bottom: 0 !important;
|
padding-bottom: 0 !important;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.warning {
|
||||||
|
background: #f80;
|
||||||
|
bottom: 0;
|
||||||
|
color: #fff;
|
||||||
|
left: 0;
|
||||||
|
opacity: 1;
|
||||||
|
padding: 1.5em;
|
||||||
|
position: fixed;
|
||||||
|
right: 50%;
|
||||||
|
z-index: 100;
|
||||||
|
}
|
||||||
|
@ -53,6 +53,7 @@ export default class Application extends Component {
|
|||||||
};
|
};
|
||||||
|
|
||||||
render () {
|
render () {
|
||||||
|
const { api } = window.parity;
|
||||||
const {
|
const {
|
||||||
actions,
|
actions,
|
||||||
accounts, contacts,
|
accounts, contacts,
|
||||||
@ -60,9 +61,11 @@ export default class Application extends Component {
|
|||||||
lookup,
|
lookup,
|
||||||
events
|
events
|
||||||
} = this.props;
|
} = this.props;
|
||||||
|
let warning = null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
|
{ warning }
|
||||||
<div className={ styles.header }>
|
<div className={ styles.header }>
|
||||||
<h1>RΞgistry</h1>
|
<h1>RΞgistry</h1>
|
||||||
<Accounts { ...accounts } actions={ actions.accounts } />
|
<Accounts { ...accounts } actions={ actions.accounts } />
|
||||||
@ -70,13 +73,11 @@ export default class Application extends Component {
|
|||||||
{ contract && fee ? (
|
{ contract && fee ? (
|
||||||
<div>
|
<div>
|
||||||
<Lookup { ...lookup } accounts={ accounts.all } contacts={ contacts } actions={ actions.lookup } />
|
<Lookup { ...lookup } accounts={ accounts.all } contacts={ contacts } actions={ actions.lookup } />
|
||||||
|
|
||||||
{ this.renderActions() }
|
{ this.renderActions() }
|
||||||
|
|
||||||
<Events { ...events } accounts={ accounts.all } contacts={ contacts } actions={ actions.events } />
|
<Events { ...events } accounts={ accounts.all } contacts={ contacts } actions={ actions.events } />
|
||||||
<p className={ styles.address }>
|
<div className={ styles.warning }>
|
||||||
The Registry is provided by the contract at <code>{ contract.address }.</code>
|
WARNING: The name registry is experimental. Please ensure that you understand the risks, benefits & consequences of registering a name before doing so. A non-refundable fee of { api.util.fromWei(fee).toFormat(3) }<small>ETH</small> is required for all registrations.
|
||||||
</p>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<CircularProgress size={ 60 } />
|
<CircularProgress size={ 60 } />
|
||||||
|
@ -19,18 +19,16 @@ import { api } from '../parity';
|
|||||||
export const set = (addresses) => ({ type: 'addresses set', addresses });
|
export const set = (addresses) => ({ type: 'addresses set', addresses });
|
||||||
|
|
||||||
export const fetch = () => (dispatch) => {
|
export const fetch = () => (dispatch) => {
|
||||||
return Promise
|
return api.parity
|
||||||
.all([
|
.accounts()
|
||||||
api.eth.accounts(),
|
.then((accountsInfo) => {
|
||||||
api.parity.accounts()
|
const addresses = Object
|
||||||
])
|
.keys(accountsInfo)
|
||||||
.then(([ accounts, data ]) => {
|
.filter((address) => accountsInfo[address] && !accountsInfo[address].meta.deleted)
|
||||||
data = data || {};
|
|
||||||
const addresses = Object.keys(data)
|
|
||||||
.filter((address) => data[address] && !data[address].meta.deleted)
|
|
||||||
.map((address) => ({
|
.map((address) => ({
|
||||||
...data[address], address,
|
...accountsInfo[address],
|
||||||
isAccount: accounts.includes(address)
|
address,
|
||||||
|
isAccount: !!accountsInfo[address].uuid
|
||||||
}));
|
}));
|
||||||
dispatch(set(addresses));
|
dispatch(set(addresses));
|
||||||
})
|
})
|
||||||
|
@ -146,7 +146,7 @@ export default class Import extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
sortFunctions = (a, b) => {
|
sortFunctions = (a, b) => {
|
||||||
return a.name.localeCompare(b.name);
|
return (a.name || '').localeCompare(b.name || '');
|
||||||
}
|
}
|
||||||
|
|
||||||
countFunctions () {
|
countFunctions () {
|
||||||
|
@ -49,26 +49,26 @@ export function attachInterface (callback) {
|
|||||||
return Promise
|
return Promise
|
||||||
.all([
|
.all([
|
||||||
registry.getAddress.call({}, [api.util.sha3('signaturereg'), 'A']),
|
registry.getAddress.call({}, [api.util.sha3('signaturereg'), 'A']),
|
||||||
api.eth.accounts(),
|
|
||||||
api.parity.accounts()
|
api.parity.accounts()
|
||||||
]);
|
]);
|
||||||
})
|
})
|
||||||
.then(([address, addresses, accountsInfo]) => {
|
.then(([address, accountsInfo]) => {
|
||||||
accountsInfo = accountsInfo || {};
|
|
||||||
console.log(`signaturereg was found at ${address}`);
|
console.log(`signaturereg was found at ${address}`);
|
||||||
|
|
||||||
const contract = api.newContract(abis.signaturereg, address);
|
const contract = api.newContract(abis.signaturereg, address);
|
||||||
const accounts = addresses.reduce((obj, address) => {
|
const accounts = Object
|
||||||
const info = accountsInfo[address] || {};
|
.keys(accountsInfo)
|
||||||
|
.filter((address) => accountsInfo[address].uuid)
|
||||||
|
.reduce((obj, address) => {
|
||||||
|
const info = accountsInfo[address] || {};
|
||||||
|
|
||||||
return Object.assign(obj, {
|
return Object.assign(obj, {
|
||||||
[address]: {
|
[address]: {
|
||||||
address,
|
address,
|
||||||
name: info.name || 'Unnamed',
|
name: info.name || 'Unnamed'
|
||||||
uuid: info.uuid
|
}
|
||||||
}
|
});
|
||||||
});
|
}, {});
|
||||||
}, {});
|
|
||||||
const fromAddress = Object.keys(accounts)[0];
|
const fromAddress = Object.keys(accounts)[0];
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
@ -70,7 +70,8 @@ export default class AccountSelector extends Component {
|
|||||||
static propTypes = {
|
static propTypes = {
|
||||||
list: PropTypes.array.isRequired,
|
list: PropTypes.array.isRequired,
|
||||||
selected: PropTypes.object.isRequired,
|
selected: PropTypes.object.isRequired,
|
||||||
handleSetSelected: PropTypes.func.isRequired
|
handleSetSelected: PropTypes.func.isRequired,
|
||||||
|
onAccountChange: PropTypes.func
|
||||||
};
|
};
|
||||||
|
|
||||||
state = {
|
state = {
|
||||||
@ -85,7 +86,8 @@ export default class AccountSelector extends Component {
|
|||||||
nestedItems={ nestedAccounts }
|
nestedItems={ nestedAccounts }
|
||||||
open={ this.state.open }
|
open={ this.state.open }
|
||||||
onSelectAccount={ this.onToggleOpen }
|
onSelectAccount={ this.onToggleOpen }
|
||||||
autoGenerateNestedIndicator={ false } />
|
autoGenerateNestedIndicator={ false }
|
||||||
|
nestedListStyle={ { maxHeight: '14em', overflow: 'auto' } } />
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -110,6 +112,10 @@ export default class AccountSelector extends Component {
|
|||||||
|
|
||||||
onToggleOpen = () => {
|
onToggleOpen = () => {
|
||||||
this.setState({ open: !this.state.open });
|
this.setState({ open: !this.state.open });
|
||||||
|
|
||||||
|
if (typeof this.props.onAccountChange === 'function') {
|
||||||
|
this.props.onAccountChange();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onSelectAccount = (address) => {
|
onSelectAccount = (address) => {
|
||||||
|
@ -35,16 +35,13 @@ export const setSelectedAccount = (address) => ({
|
|||||||
});
|
});
|
||||||
|
|
||||||
export const loadAccounts = () => (dispatch) => {
|
export const loadAccounts = () => (dispatch) => {
|
||||||
Promise
|
api.parity
|
||||||
.all([
|
.accounts()
|
||||||
api.eth.accounts(),
|
.then((accountsInfo) => {
|
||||||
api.parity.accounts()
|
const accountsList = Object
|
||||||
])
|
.keys(accountsInfo)
|
||||||
.then(([ accounts, accountsInfo ]) => {
|
.filter((address) => accountsInfo[address].uuid)
|
||||||
accountsInfo = accountsInfo || {};
|
.map((address) => ({
|
||||||
|
|
||||||
const accountsList = accounts
|
|
||||||
.map(address => ({
|
|
||||||
...accountsInfo[address],
|
...accountsInfo[address],
|
||||||
address
|
address
|
||||||
}));
|
}));
|
||||||
|
@ -81,6 +81,7 @@ export default class RegisterAction extends Component {
|
|||||||
className={ styles.dialog }
|
className={ styles.dialog }
|
||||||
onRequestClose={ this.onClose }
|
onRequestClose={ this.onClose }
|
||||||
actions={ this.renderActions() }
|
actions={ this.renderActions() }
|
||||||
|
ref='dialog'
|
||||||
autoScrollBodyContent
|
autoScrollBodyContent
|
||||||
>
|
>
|
||||||
{ this.renderContent() }
|
{ this.renderContent() }
|
||||||
@ -149,7 +150,9 @@ export default class RegisterAction extends Component {
|
|||||||
renderForm () {
|
renderForm () {
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<AccountSelector />
|
<AccountSelector
|
||||||
|
onAccountChange={ this.onAccountChange }
|
||||||
|
/>
|
||||||
{ this.renderInputs() }
|
{ this.renderInputs() }
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@ -175,6 +178,11 @@ export default class RegisterAction extends Component {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
onAccountChange = () => {
|
||||||
|
const { dialog } = this.refs;
|
||||||
|
dialog.forceUpdate();
|
||||||
|
}
|
||||||
|
|
||||||
onChange (fieldKey, valid, value) {
|
onChange (fieldKey, valid, value) {
|
||||||
const { fields } = this.state;
|
const { fields } = this.state;
|
||||||
const field = fields[fieldKey];
|
const field = fields[fieldKey];
|
||||||
|
@ -20,3 +20,15 @@
|
|||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.warning {
|
||||||
|
background: #f80;
|
||||||
|
bottom: 0;
|
||||||
|
color: #fff;
|
||||||
|
left: 0;
|
||||||
|
opacity: 1;
|
||||||
|
padding: 1.5em;
|
||||||
|
position: fixed;
|
||||||
|
right: 50%;
|
||||||
|
z-index: 100;
|
||||||
|
}
|
||||||
|
@ -17,6 +17,8 @@
|
|||||||
import React, { Component, PropTypes } from 'react';
|
import React, { Component, PropTypes } from 'react';
|
||||||
import getMuiTheme from 'material-ui/styles/getMuiTheme';
|
import getMuiTheme from 'material-ui/styles/getMuiTheme';
|
||||||
|
|
||||||
|
import { api } from '../parity';
|
||||||
|
|
||||||
import Loading from '../Loading';
|
import Loading from '../Loading';
|
||||||
import Status from '../Status';
|
import Status from '../Status';
|
||||||
import Tokens from '../Tokens';
|
import Tokens from '../Tokens';
|
||||||
@ -59,6 +61,9 @@ export default class Application extends Component {
|
|||||||
<Actions />
|
<Actions />
|
||||||
|
|
||||||
<Tokens />
|
<Tokens />
|
||||||
|
<div className={ styles.warning }>
|
||||||
|
WARNING: The token registry is experimental. Please ensure that you understand the steps, risks, benefits & consequences of registering a token before doing so. A non-refundable fee of { api.util.fromWei(contract.fee).toFormat(3) }<small>ETH</small> is required for all registrations.
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -75,7 +75,7 @@ const validateTokenAddress = (address, contract, simple) => {
|
|||||||
|
|
||||||
return getTokenTotalSupply(address)
|
return getTokenTotalSupply(address)
|
||||||
.then(balance => {
|
.then(balance => {
|
||||||
if (balance === null) {
|
if (balance === null || balance.equals(0)) {
|
||||||
return {
|
return {
|
||||||
error: ERRORS.invalidTokenAddress,
|
error: ERRORS.invalidTokenAddress,
|
||||||
valid: false
|
valid: false
|
||||||
|
@ -31,6 +31,12 @@
|
|||||||
.title {
|
.title {
|
||||||
font-size: 3rem;
|
font-size: 3rem;
|
||||||
font-weight: 300;
|
font-weight: 300;
|
||||||
margin-top: 0;
|
margin: 0;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.byline {
|
||||||
|
font-size: 1.25em;
|
||||||
|
opacity: 0.75;
|
||||||
|
margin: 0 0 1.75em 0;
|
||||||
|
}
|
||||||
|
@ -29,17 +29,12 @@ export default class Status extends Component {
|
|||||||
};
|
};
|
||||||
|
|
||||||
render () {
|
render () {
|
||||||
const { address, fee } = this.props;
|
const { fee } = this.props;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={ styles.status }>
|
<div className={ styles.status }>
|
||||||
<h1 className={ styles.title }>Token Registry</h1>
|
<h1 className={ styles.title }>Token Registry</h1>
|
||||||
|
<h3 className={ styles.byline }>A global registry of all recognised tokens on the network</h3>
|
||||||
<Chip
|
|
||||||
isAddress
|
|
||||||
value={ address }
|
|
||||||
label='Address' />
|
|
||||||
|
|
||||||
<Chip
|
<Chip
|
||||||
isAddress={ false }
|
isAddress={ false }
|
||||||
value={ api.util.fromWei(fee).toFixed(3) + 'ETH' }
|
value={ api.util.fromWei(fee).toFixed(3) + 'ETH' }
|
||||||
|
@ -57,6 +57,7 @@ export default class Token extends Component {
|
|||||||
isLoading: PropTypes.bool,
|
isLoading: PropTypes.bool,
|
||||||
isPending: PropTypes.bool,
|
isPending: PropTypes.bool,
|
||||||
isTokenOwner: PropTypes.bool.isRequired,
|
isTokenOwner: PropTypes.bool.isRequired,
|
||||||
|
isContractOwner: PropTypes.bool.isRequired,
|
||||||
|
|
||||||
fullWidth: PropTypes.bool
|
fullWidth: PropTypes.bool
|
||||||
};
|
};
|
||||||
@ -220,7 +221,7 @@ export default class Token extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
renderUnregister () {
|
renderUnregister () {
|
||||||
if (!this.props.isTokenOwner) {
|
if (!this.props.isContractOwner) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -45,7 +45,7 @@ export default class Tokens extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
renderTokens (tokens) {
|
renderTokens (tokens) {
|
||||||
const { accounts } = this.props;
|
const { accounts, isOwner } = this.props;
|
||||||
|
|
||||||
return tokens.map((token, index) => {
|
return tokens.map((token, index) => {
|
||||||
if (!token || !token.tla) {
|
if (!token || !token.tla) {
|
||||||
@ -61,7 +61,8 @@ export default class Tokens extends Component {
|
|||||||
handleMetaLookup={ this.props.handleMetaLookup }
|
handleMetaLookup={ this.props.handleMetaLookup }
|
||||||
handleAddMeta={ this.props.handleAddMeta }
|
handleAddMeta={ this.props.handleAddMeta }
|
||||||
key={ index }
|
key={ index }
|
||||||
isTokenOwner={ isTokenOwner } />
|
isTokenOwner={ isTokenOwner }
|
||||||
|
isContractOwner={ isOwner } />
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -31,7 +31,7 @@ import ContractInstances from './contracts';
|
|||||||
|
|
||||||
import { initStore } from './redux';
|
import { initStore } from './redux';
|
||||||
import { ContextProvider, muiTheme } from './ui';
|
import { ContextProvider, muiTheme } from './ui';
|
||||||
import { Accounts, Account, Addresses, Address, Application, Contract, Contracts, Dapp, Dapps, Settings, SettingsBackground, SettingsParity, SettingsProxy, SettingsViews, Signer, Status } from './views';
|
import { Accounts, Account, Addresses, Address, Application, Contract, Contracts, WriteContract, Dapp, Dapps, Settings, SettingsBackground, SettingsParity, SettingsProxy, SettingsViews, Signer, Status } from './views';
|
||||||
|
|
||||||
import { setApi } from './redux/providers/apiActions';
|
import { setApi } from './redux/providers/apiActions';
|
||||||
|
|
||||||
@ -76,6 +76,7 @@ ReactDOM.render(
|
|||||||
<Route path='apps' component={ Dapps } />
|
<Route path='apps' component={ Dapps } />
|
||||||
<Route path='app/:id' component={ Dapp } />
|
<Route path='app/:id' component={ Dapp } />
|
||||||
<Route path='contracts' component={ Contracts } />
|
<Route path='contracts' component={ Contracts } />
|
||||||
|
<Route path='contracts/write' component={ WriteContract } />
|
||||||
<Route path='contract/:address' component={ Contract } />
|
<Route path='contract/:address' component={ Contract } />
|
||||||
<Route path='settings' component={ Settings }>
|
<Route path='settings' component={ Settings }>
|
||||||
<Route path='background' component={ SettingsBackground } />
|
<Route path='background' component={ SettingsBackground } />
|
||||||
|
@ -109,6 +109,15 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
dappsInterface: {
|
||||||
|
desc: 'Returns the interface the dapps are running on, error if not enabled',
|
||||||
|
params: [],
|
||||||
|
returns: {
|
||||||
|
type: String,
|
||||||
|
desc: 'The interface'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
defaultExtraData: {
|
defaultExtraData: {
|
||||||
desc: 'Returns the default extra data',
|
desc: 'Returns the default extra data',
|
||||||
params: [],
|
params: [],
|
||||||
@ -347,6 +356,20 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
nextNonce: {
|
||||||
|
desc: 'Returns next available nonce for transaction from given account. Includes pending block and transaction queue.',
|
||||||
|
params: [
|
||||||
|
{
|
||||||
|
type: Address,
|
||||||
|
desc: 'Account'
|
||||||
|
}
|
||||||
|
],
|
||||||
|
returns: {
|
||||||
|
type: Quantity,
|
||||||
|
desc: 'Next valid nonce'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
nodeName: {
|
nodeName: {
|
||||||
desc: 'Returns node name (identity)',
|
desc: 'Returns node name (identity)',
|
||||||
params: [],
|
params: [],
|
||||||
|
@ -14,7 +14,7 @@
|
|||||||
// You should have received a copy of the GNU General Public License
|
// You should have received a copy of the GNU General Public License
|
||||||
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
import { Quantity } from '../types';
|
import { Quantity, Data } from '../types';
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
generateAuthorizationToken: {
|
generateAuthorizationToken: {
|
||||||
@ -57,6 +57,24 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
confirmRequestRaw: {
|
||||||
|
desc: 'Confirm a request in the signer queue providing signed request.',
|
||||||
|
params: [
|
||||||
|
{
|
||||||
|
type: Quantity,
|
||||||
|
desc: 'The request id'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: Data,
|
||||||
|
desc: 'Signed request (transaction RLP)'
|
||||||
|
}
|
||||||
|
],
|
||||||
|
returns: {
|
||||||
|
type: Boolean,
|
||||||
|
desc: 'The status of the confirmation'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
rejectRequest: {
|
rejectRequest: {
|
||||||
desc: 'Rejects a request in the signer queue',
|
desc: 'Rejects a request in the signer queue',
|
||||||
params: [
|
params: [
|
||||||
|
32
js/src/modals/AddContract/addContract.css
Normal file
32
js/src/modals/AddContract/addContract.css
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
/* Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
.spaced {
|
||||||
|
margin: 0.25em 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typeContainer {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
|
||||||
|
.desc {
|
||||||
|
font-size: 0.8em;
|
||||||
|
margin-bottom: 0.5em;
|
||||||
|
color: #ccc;
|
||||||
|
z-index: 2;
|
||||||
|
}
|
||||||
|
}
|
@ -17,10 +17,38 @@
|
|||||||
import React, { Component, PropTypes } from 'react';
|
import React, { Component, PropTypes } from 'react';
|
||||||
import ContentAdd from 'material-ui/svg-icons/content/add';
|
import ContentAdd from 'material-ui/svg-icons/content/add';
|
||||||
import ContentClear from 'material-ui/svg-icons/content/clear';
|
import ContentClear from 'material-ui/svg-icons/content/clear';
|
||||||
|
import NavigationArrowForward from 'material-ui/svg-icons/navigation/arrow-forward';
|
||||||
|
import NavigationArrowBack from 'material-ui/svg-icons/navigation/arrow-back';
|
||||||
|
|
||||||
|
import { RadioButton, RadioButtonGroup } from 'material-ui/RadioButton';
|
||||||
|
|
||||||
import { Button, Modal, Form, Input, InputAddress } from '../../ui';
|
import { Button, Modal, Form, Input, InputAddress } from '../../ui';
|
||||||
import { ERRORS, validateAbi, validateAddress, validateName } from '../../util/validation';
|
import { ERRORS, validateAbi, validateAddress, validateName } from '../../util/validation';
|
||||||
|
|
||||||
|
import { eip20, wallet } from '../../contracts/abi';
|
||||||
|
import styles from './addContract.css';
|
||||||
|
|
||||||
|
const ABI_TYPES = [
|
||||||
|
{
|
||||||
|
label: 'Token', readOnly: true, value: JSON.stringify(eip20),
|
||||||
|
type: 'token',
|
||||||
|
description: (<span>A standard <a href='https://github.com/ethereum/EIPs/issues/20' target='_blank'>ERC 20</a> token</span>)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Multisig Wallet', readOnly: true,
|
||||||
|
type: 'multisig',
|
||||||
|
value: JSON.stringify(wallet),
|
||||||
|
description: (<span>Official Multisig contract: <a href='https://github.com/ethereum/dapp-bin/blob/master/wallet/wallet.sol' target='_blank'>see contract code</a></span>)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Custom Contract', value: '',
|
||||||
|
type: 'custom',
|
||||||
|
description: 'Contract created from custom ABI'
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
const STEPS = [ 'choose a contract type', 'enter contract details' ];
|
||||||
|
|
||||||
export default class AddContract extends Component {
|
export default class AddContract extends Component {
|
||||||
static contextTypes = {
|
static contextTypes = {
|
||||||
api: PropTypes.object.isRequired
|
api: PropTypes.object.isRequired
|
||||||
@ -34,44 +62,101 @@ export default class AddContract extends Component {
|
|||||||
state = {
|
state = {
|
||||||
abi: '',
|
abi: '',
|
||||||
abiError: ERRORS.invalidAbi,
|
abiError: ERRORS.invalidAbi,
|
||||||
|
abiType: ABI_TYPES[2],
|
||||||
|
abiTypeIndex: 2,
|
||||||
abiParsed: null,
|
abiParsed: null,
|
||||||
address: '',
|
address: '',
|
||||||
addressError: ERRORS.invalidAddress,
|
addressError: ERRORS.invalidAddress,
|
||||||
name: '',
|
name: '',
|
||||||
nameError: ERRORS.invalidName,
|
nameError: ERRORS.invalidName,
|
||||||
description: ''
|
description: '',
|
||||||
|
step: 0
|
||||||
};
|
};
|
||||||
|
|
||||||
|
componentDidMount () {
|
||||||
|
this.onChangeABIType(null, this.state.abiTypeIndex);
|
||||||
|
}
|
||||||
|
|
||||||
render () {
|
render () {
|
||||||
|
const { step } = this.state;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
visible
|
visible
|
||||||
actions={ this.renderDialogActions() }
|
actions={ this.renderDialogActions() }
|
||||||
title='watch contract'>
|
steps={ STEPS }
|
||||||
{ this.renderFields() }
|
current={ step }
|
||||||
|
>
|
||||||
|
{ this.renderStep(step) }
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
renderStep (step) {
|
||||||
|
switch (step) {
|
||||||
|
case 0:
|
||||||
|
return this.renderContractTypeSelector();
|
||||||
|
default:
|
||||||
|
return this.renderFields();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
renderContractTypeSelector () {
|
||||||
|
const { abiTypeIndex } = this.state;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<RadioButtonGroup
|
||||||
|
valueSelected={ abiTypeIndex }
|
||||||
|
name='contractType'
|
||||||
|
onChange={ this.onChangeABIType }
|
||||||
|
>
|
||||||
|
{ this.renderAbiTypes() }
|
||||||
|
</RadioButtonGroup>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
renderDialogActions () {
|
renderDialogActions () {
|
||||||
const { addressError, nameError } = this.state;
|
const { addressError, nameError, step } = this.state;
|
||||||
const hasError = !!(addressError || nameError);
|
const hasError = !!(addressError || nameError);
|
||||||
|
|
||||||
return ([
|
const cancelBtn = (
|
||||||
<Button
|
<Button
|
||||||
icon={ <ContentClear /> }
|
icon={ <ContentClear /> }
|
||||||
label='Cancel'
|
label='Cancel'
|
||||||
onClick={ this.onClose } />,
|
onClick={ this.onClose } />
|
||||||
|
);
|
||||||
|
|
||||||
|
if (step === 0) {
|
||||||
|
const nextBtn = (
|
||||||
|
<Button
|
||||||
|
icon={ <NavigationArrowForward /> }
|
||||||
|
label='Next'
|
||||||
|
onClick={ this.onNext } />
|
||||||
|
);
|
||||||
|
|
||||||
|
return [ cancelBtn, nextBtn ];
|
||||||
|
}
|
||||||
|
|
||||||
|
const prevBtn = (
|
||||||
|
<Button
|
||||||
|
icon={ <NavigationArrowBack /> }
|
||||||
|
label='Back'
|
||||||
|
onClick={ this.onPrev } />
|
||||||
|
);
|
||||||
|
|
||||||
|
const addBtn = (
|
||||||
<Button
|
<Button
|
||||||
icon={ <ContentAdd /> }
|
icon={ <ContentAdd /> }
|
||||||
label='Add Contract'
|
label='Add Contract'
|
||||||
disabled={ hasError }
|
disabled={ hasError }
|
||||||
onClick={ this.onAdd } />
|
onClick={ this.onAdd } />
|
||||||
]);
|
);
|
||||||
|
|
||||||
|
return [ cancelBtn, prevBtn, addBtn ];
|
||||||
}
|
}
|
||||||
|
|
||||||
renderFields () {
|
renderFields () {
|
||||||
const { abi, abiError, address, addressError, description, name, nameError } = this.state;
|
const { abi, abiError, address, addressError, description, name, nameError, abiType } = this.state;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Form>
|
<Form>
|
||||||
@ -80,7 +165,9 @@ export default class AddContract extends Component {
|
|||||||
hint='the network address for the contract'
|
hint='the network address for the contract'
|
||||||
error={ addressError }
|
error={ addressError }
|
||||||
value={ address }
|
value={ address }
|
||||||
onSubmit={ this.onEditAddress } />
|
onSubmit={ this.onEditAddress }
|
||||||
|
onChange={ this.onChangeAddress }
|
||||||
|
/>
|
||||||
<Input
|
<Input
|
||||||
label='contract name'
|
label='contract name'
|
||||||
hint='a descriptive name for the contract'
|
hint='a descriptive name for the contract'
|
||||||
@ -94,20 +181,57 @@ export default class AddContract extends Component {
|
|||||||
hint='an expanded description for the entry'
|
hint='an expanded description for the entry'
|
||||||
value={ description }
|
value={ description }
|
||||||
onSubmit={ this.onEditDescription } />
|
onSubmit={ this.onEditDescription } />
|
||||||
|
|
||||||
<Input
|
<Input
|
||||||
label='contract abi'
|
label='contract abi'
|
||||||
hint='the abi for the contract'
|
hint='the abi for the contract'
|
||||||
error={ abiError }
|
error={ abiError }
|
||||||
value={ abi }
|
value={ abi }
|
||||||
onSubmit={ this.onEditAbi } />
|
readOnly={ abiType.readOnly }
|
||||||
|
onSubmit={ this.onEditAbi }
|
||||||
|
/>
|
||||||
</Form>
|
</Form>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
onEditAbi = (abi) => {
|
renderAbiTypes () {
|
||||||
const { api } = this.context;
|
return ABI_TYPES.map((type, index) => (
|
||||||
|
<RadioButton
|
||||||
|
className={ styles.spaced }
|
||||||
|
value={ index }
|
||||||
|
label={ (
|
||||||
|
<div className={ styles.typeContainer }>
|
||||||
|
<span>{ type.label }</span>
|
||||||
|
<span className={ styles.desc }>{ type.description }</span>
|
||||||
|
</div>
|
||||||
|
) }
|
||||||
|
key={ index }
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
this.setState(validateAbi(abi, api));
|
onNext = () => {
|
||||||
|
this.setState({ step: this.state.step + 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
onPrev = () => {
|
||||||
|
this.setState({ step: this.state.step - 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
onChangeABIType = (event, index) => {
|
||||||
|
const abiType = ABI_TYPES[index];
|
||||||
|
this.setState({ abiTypeIndex: index, abiType });
|
||||||
|
this.onEditAbi(abiType.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
onEditAbi = (abiIn) => {
|
||||||
|
const { api } = this.context;
|
||||||
|
const { abi, abiError, abiParsed } = validateAbi(abiIn, api);
|
||||||
|
this.setState({ abi, abiError, abiParsed });
|
||||||
|
}
|
||||||
|
|
||||||
|
onChangeAddress = (event, value) => {
|
||||||
|
this.onEditAddress(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
onEditAddress = (_address) => {
|
onEditAddress = (_address) => {
|
||||||
@ -138,7 +262,7 @@ export default class AddContract extends Component {
|
|||||||
|
|
||||||
onAdd = () => {
|
onAdd = () => {
|
||||||
const { api } = this.context;
|
const { api } = this.context;
|
||||||
const { abiParsed, address, name, description } = this.state;
|
const { abiParsed, address, name, description, abiType } = this.state;
|
||||||
|
|
||||||
Promise.all([
|
Promise.all([
|
||||||
api.parity.setAccountName(address, name),
|
api.parity.setAccountName(address, name),
|
||||||
@ -147,6 +271,7 @@ export default class AddContract extends Component {
|
|||||||
deleted: false,
|
deleted: false,
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
abi: abiParsed,
|
abi: abiParsed,
|
||||||
|
type: abiType.type,
|
||||||
description
|
description
|
||||||
})
|
})
|
||||||
]).catch((error) => {
|
]).catch((error) => {
|
||||||
|
@ -58,7 +58,7 @@ export default class AccountDetails extends Component {
|
|||||||
readOnly
|
readOnly
|
||||||
allowCopy
|
allowCopy
|
||||||
hint='the account recovery phrase'
|
hint='the account recovery phrase'
|
||||||
label='account recovery phrase (keep safe)'
|
label='owner recovery phrase (keep private and secure, it allows full and unlimited access to the account)'
|
||||||
value={ phrase } />
|
value={ phrase } />
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -25,7 +25,7 @@ import styles from '../deployContract.css';
|
|||||||
export default class DetailsStep extends Component {
|
export default class DetailsStep extends Component {
|
||||||
static contextTypes = {
|
static contextTypes = {
|
||||||
api: PropTypes.object.isRequired
|
api: PropTypes.object.isRequired
|
||||||
}
|
};
|
||||||
|
|
||||||
static propTypes = {
|
static propTypes = {
|
||||||
accounts: PropTypes.object.isRequired,
|
accounts: PropTypes.object.isRequired,
|
||||||
@ -46,16 +46,33 @@ export default class DetailsStep extends Component {
|
|||||||
onFromAddressChange: PropTypes.func.isRequired,
|
onFromAddressChange: PropTypes.func.isRequired,
|
||||||
onDescriptionChange: PropTypes.func.isRequired,
|
onDescriptionChange: PropTypes.func.isRequired,
|
||||||
onNameChange: PropTypes.func.isRequired,
|
onNameChange: PropTypes.func.isRequired,
|
||||||
onParamsChange: PropTypes.func.isRequired
|
onParamsChange: PropTypes.func.isRequired,
|
||||||
}
|
readOnly: PropTypes.bool
|
||||||
|
};
|
||||||
|
|
||||||
|
static defaultProps = {
|
||||||
|
readOnly: false
|
||||||
|
};
|
||||||
|
|
||||||
state = {
|
state = {
|
||||||
inputs: []
|
inputs: []
|
||||||
}
|
}
|
||||||
|
|
||||||
|
componentDidMount () {
|
||||||
|
const { abi, code } = this.props;
|
||||||
|
|
||||||
|
if (abi) {
|
||||||
|
this.onAbiChange(abi);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (code) {
|
||||||
|
this.onCodeChange(code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
render () {
|
render () {
|
||||||
const { accounts } = this.props;
|
const { accounts } = this.props;
|
||||||
const { abi, abiError, code, codeError, fromAddress, fromAddressError, name, nameError } = this.props;
|
const { abi, abiError, code, codeError, fromAddress, fromAddressError, name, nameError, readOnly } = this.props;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Form>
|
<Form>
|
||||||
@ -77,13 +94,15 @@ export default class DetailsStep extends Component {
|
|||||||
hint='the abi of the contract to deploy'
|
hint='the abi of the contract to deploy'
|
||||||
error={ abiError }
|
error={ abiError }
|
||||||
value={ abi }
|
value={ abi }
|
||||||
onSubmit={ this.onAbiChange } />
|
onSubmit={ this.onAbiChange }
|
||||||
|
readOnly={ readOnly } />
|
||||||
<Input
|
<Input
|
||||||
label='code'
|
label='code'
|
||||||
hint='the compiled code of the contract to deploy'
|
hint='the compiled code of the contract to deploy'
|
||||||
error={ codeError }
|
error={ codeError }
|
||||||
value={ code }
|
value={ code }
|
||||||
onSubmit={ this.onCodeChange } />
|
onSubmit={ this.onCodeChange }
|
||||||
|
readOnly={ readOnly } />
|
||||||
{ this.renderConstructorInputs() }
|
{ this.renderConstructorInputs() }
|
||||||
</Form>
|
</Form>
|
||||||
);
|
);
|
||||||
|
@ -36,8 +36,17 @@ export default class DeployContract extends Component {
|
|||||||
|
|
||||||
static propTypes = {
|
static propTypes = {
|
||||||
accounts: PropTypes.object.isRequired,
|
accounts: PropTypes.object.isRequired,
|
||||||
onClose: PropTypes.func.isRequired
|
onClose: PropTypes.func.isRequired,
|
||||||
}
|
abi: PropTypes.string,
|
||||||
|
code: PropTypes.string,
|
||||||
|
readOnly: PropTypes.bool,
|
||||||
|
source: PropTypes.string
|
||||||
|
};
|
||||||
|
|
||||||
|
static defaultProps = {
|
||||||
|
readOnly: false,
|
||||||
|
source: ''
|
||||||
|
};
|
||||||
|
|
||||||
state = {
|
state = {
|
||||||
abi: '',
|
abi: '',
|
||||||
@ -57,6 +66,31 @@ export default class DeployContract extends Component {
|
|||||||
deployError: null
|
deployError: null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
componentWillMount () {
|
||||||
|
const { abi, code } = this.props;
|
||||||
|
|
||||||
|
if (abi && code) {
|
||||||
|
this.setState({ abi, code });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
componentWillReceiveProps (nextProps) {
|
||||||
|
const { abi, code } = nextProps;
|
||||||
|
const newState = {};
|
||||||
|
|
||||||
|
if (abi !== this.props.abi) {
|
||||||
|
newState.abi = abi;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (code !== this.props.code) {
|
||||||
|
newState.code = code;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Object.keys(newState).length) {
|
||||||
|
this.setState(newState);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
render () {
|
render () {
|
||||||
const { step, deployError } = this.state;
|
const { step, deployError } = this.state;
|
||||||
|
|
||||||
@ -115,7 +149,7 @@ export default class DeployContract extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
renderStep () {
|
renderStep () {
|
||||||
const { accounts } = this.props;
|
const { accounts, readOnly } = this.props;
|
||||||
const { address, deployError, step, deployState, txhash } = this.state;
|
const { address, deployError, step, deployState, txhash } = this.state;
|
||||||
|
|
||||||
if (deployError) {
|
if (deployError) {
|
||||||
@ -129,6 +163,7 @@ export default class DeployContract extends Component {
|
|||||||
return (
|
return (
|
||||||
<DetailsStep
|
<DetailsStep
|
||||||
{ ...this.state }
|
{ ...this.state }
|
||||||
|
readOnly={ readOnly }
|
||||||
accounts={ accounts }
|
accounts={ accounts }
|
||||||
onAbiChange={ this.onAbiChange }
|
onAbiChange={ this.onAbiChange }
|
||||||
onCodeChange={ this.onCodeChange }
|
onCodeChange={ this.onCodeChange }
|
||||||
@ -200,6 +235,7 @@ export default class DeployContract extends Component {
|
|||||||
|
|
||||||
onDeployStart = () => {
|
onDeployStart = () => {
|
||||||
const { api, store } = this.context;
|
const { api, store } = this.context;
|
||||||
|
const { source } = this.props;
|
||||||
const { abiParsed, code, description, name, params, fromAddress } = this.state;
|
const { abiParsed, code, description, name, params, fromAddress } = this.state;
|
||||||
const options = {
|
const options = {
|
||||||
data: code,
|
data: code,
|
||||||
@ -219,6 +255,7 @@ export default class DeployContract extends Component {
|
|||||||
contract: true,
|
contract: true,
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
deleted: false,
|
deleted: false,
|
||||||
|
source,
|
||||||
description
|
description
|
||||||
})
|
})
|
||||||
])
|
])
|
||||||
|
17
js/src/modals/LoadContract/index.js
Normal file
17
js/src/modals/LoadContract/index.js
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
// Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
export default from './loadContract';
|
52
js/src/modals/LoadContract/loadContract.css
Normal file
52
js/src/modals/LoadContract/loadContract.css
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
/* Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
.loadContainer {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
|
||||||
|
> * {
|
||||||
|
flex: 50%;
|
||||||
|
width: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.editor {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
padding-left: 1em;
|
||||||
|
|
||||||
|
p {
|
||||||
|
line-height: 48px;
|
||||||
|
height: 48px;
|
||||||
|
overflow: hidden;
|
||||||
|
white-space: nowrap;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.2em;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.confirmRemoval {
|
||||||
|
text-align: center;
|
||||||
|
|
||||||
|
.editor {
|
||||||
|
text-align: left;
|
||||||
|
margin-top: 0.5em;
|
||||||
|
}
|
||||||
|
}
|
284
js/src/modals/LoadContract/loadContract.js
Normal file
284
js/src/modals/LoadContract/loadContract.js
Normal file
@ -0,0 +1,284 @@
|
|||||||
|
// Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import React, { Component, PropTypes } from 'react';
|
||||||
|
|
||||||
|
import ContentClear from 'material-ui/svg-icons/content/clear';
|
||||||
|
import CheckIcon from 'material-ui/svg-icons/navigation/check';
|
||||||
|
import DeleteIcon from 'material-ui/svg-icons/action/delete';
|
||||||
|
|
||||||
|
import { List, ListItem, makeSelectable } from 'material-ui/List';
|
||||||
|
import { Subheader, IconButton, Tabs, Tab } from 'material-ui';
|
||||||
|
import moment from 'moment';
|
||||||
|
|
||||||
|
import { Button, Modal, Editor } from '../../ui';
|
||||||
|
|
||||||
|
import styles from './loadContract.css';
|
||||||
|
|
||||||
|
const SelectableList = makeSelectable(List);
|
||||||
|
|
||||||
|
const SELECTED_STYLE = {
|
||||||
|
backgroundColor: 'rgba(255, 255, 255, 0.1)'
|
||||||
|
};
|
||||||
|
|
||||||
|
export default class LoadContract extends Component {
|
||||||
|
|
||||||
|
static propTypes = {
|
||||||
|
onClose: PropTypes.func.isRequired,
|
||||||
|
onLoad: PropTypes.func.isRequired,
|
||||||
|
onDelete: PropTypes.func.isRequired,
|
||||||
|
contracts: PropTypes.object.isRequired,
|
||||||
|
snippets: PropTypes.object.isRequired
|
||||||
|
};
|
||||||
|
|
||||||
|
state = {
|
||||||
|
selected: -1,
|
||||||
|
deleteRequest: false,
|
||||||
|
deleteId: -1
|
||||||
|
};
|
||||||
|
|
||||||
|
render () {
|
||||||
|
const { deleteRequest } = this.state;
|
||||||
|
|
||||||
|
const title = deleteRequest
|
||||||
|
? 'confirm removal'
|
||||||
|
: 'view contracts';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
title={ title }
|
||||||
|
actions={ this.renderDialogActions() }
|
||||||
|
visible
|
||||||
|
scroll
|
||||||
|
>
|
||||||
|
{ this.renderBody() }
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
renderBody () {
|
||||||
|
if (this.state.deleteRequest) {
|
||||||
|
return this.renderConfirmRemoval();
|
||||||
|
}
|
||||||
|
|
||||||
|
const { contracts, snippets } = this.props;
|
||||||
|
|
||||||
|
const contractsTab = Object.keys(contracts).length === 0
|
||||||
|
? null
|
||||||
|
: (
|
||||||
|
<Tab label='Local' >
|
||||||
|
{ this.renderEditor() }
|
||||||
|
|
||||||
|
<SelectableList
|
||||||
|
onChange={ this.onClickContract }
|
||||||
|
>
|
||||||
|
<Subheader>Saved Contracts</Subheader>
|
||||||
|
{ this.renderContracts(contracts) }
|
||||||
|
</SelectableList>
|
||||||
|
</Tab>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={ styles.loadContainer }>
|
||||||
|
<Tabs onChange={ this.handleChangeTab }>
|
||||||
|
{ contractsTab }
|
||||||
|
|
||||||
|
<Tab label='Snippets' >
|
||||||
|
{ this.renderEditor() }
|
||||||
|
|
||||||
|
<SelectableList
|
||||||
|
onChange={ this.onClickContract }
|
||||||
|
>
|
||||||
|
<Subheader>Contract Snippets</Subheader>
|
||||||
|
{ this.renderContracts(snippets, false) }
|
||||||
|
</SelectableList>
|
||||||
|
</Tab>
|
||||||
|
</Tabs>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
renderConfirmRemoval () {
|
||||||
|
const { deleteId } = this.state;
|
||||||
|
const { name, timestamp, sourcecode } = this.props.contracts[deleteId];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={ styles.confirmRemoval }>
|
||||||
|
<p>
|
||||||
|
Are you sure you want to remove the following
|
||||||
|
contract from your saved contracts?
|
||||||
|
</p>
|
||||||
|
<ListItem
|
||||||
|
primaryText={ name }
|
||||||
|
secondaryText={ `Saved ${moment(timestamp).fromNow()}` }
|
||||||
|
style={ { backgroundColor: 'none', cursor: 'default' } }
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className={ styles.editor }>
|
||||||
|
<Editor
|
||||||
|
value={ sourcecode }
|
||||||
|
maxLines={ 20 }
|
||||||
|
readOnly
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
renderEditor () {
|
||||||
|
const { contracts, snippets } = this.props;
|
||||||
|
const { selected } = this.state;
|
||||||
|
|
||||||
|
const mergedContracts = Object.assign({}, contracts, snippets);
|
||||||
|
|
||||||
|
if (selected === -1 || !mergedContracts[selected]) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { sourcecode, name } = mergedContracts[selected];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={ styles.editor }>
|
||||||
|
<p>{ name }</p>
|
||||||
|
<Editor
|
||||||
|
value={ sourcecode }
|
||||||
|
maxLines={ 20 }
|
||||||
|
readOnly
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
renderContracts (contracts, removable = true) {
|
||||||
|
const { selected } = this.state;
|
||||||
|
|
||||||
|
return Object
|
||||||
|
.values(contracts)
|
||||||
|
.map((contract) => {
|
||||||
|
const { id, name, timestamp, description } = contract;
|
||||||
|
const onDelete = () => this.onDeleteRequest(id);
|
||||||
|
|
||||||
|
const secondaryText = description || `Saved ${moment(timestamp).fromNow()}`;
|
||||||
|
const remove = removable
|
||||||
|
? (
|
||||||
|
<IconButton onClick={ onDelete }>
|
||||||
|
<DeleteIcon />
|
||||||
|
</IconButton>
|
||||||
|
)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ListItem
|
||||||
|
value={ id }
|
||||||
|
key={ id }
|
||||||
|
primaryText={ name }
|
||||||
|
secondaryText={ secondaryText }
|
||||||
|
style={ selected === id ? SELECTED_STYLE : null }
|
||||||
|
rightIconButton={ remove }
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
renderDialogActions () {
|
||||||
|
const { deleteRequest } = this.state;
|
||||||
|
|
||||||
|
if (deleteRequest) {
|
||||||
|
return [
|
||||||
|
<Button
|
||||||
|
icon={ <ContentClear /> }
|
||||||
|
label='No'
|
||||||
|
key='No'
|
||||||
|
onClick={ this.onRejectRemoval }
|
||||||
|
/>,
|
||||||
|
<Button
|
||||||
|
icon={ <DeleteIcon /> }
|
||||||
|
label='Yes'
|
||||||
|
key='Yes'
|
||||||
|
onClick={ this.onConfirmRemoval }
|
||||||
|
/>
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
const cancelBtn = (
|
||||||
|
<Button
|
||||||
|
icon={ <ContentClear /> }
|
||||||
|
label='Cancel'
|
||||||
|
onClick={ this.onClose }
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
const loadBtn = (
|
||||||
|
<Button
|
||||||
|
icon={ <CheckIcon /> }
|
||||||
|
label='Load'
|
||||||
|
onClick={ this.onLoad }
|
||||||
|
disabled={ this.state.selected === -1 }
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
return [ cancelBtn, loadBtn ];
|
||||||
|
}
|
||||||
|
|
||||||
|
handleChangeTab = () => {
|
||||||
|
this.setState({ selected: -1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
onClickContract = (_, value) => {
|
||||||
|
this.setState({ selected: value });
|
||||||
|
}
|
||||||
|
|
||||||
|
onClose = () => {
|
||||||
|
this.props.onClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
onLoad = () => {
|
||||||
|
const { contracts, snippets } = this.props;
|
||||||
|
const { selected } = this.state;
|
||||||
|
|
||||||
|
const mergedContracts = Object.assign({}, contracts, snippets);
|
||||||
|
const contract = mergedContracts[selected];
|
||||||
|
|
||||||
|
this.props.onLoad(contract);
|
||||||
|
this.props.onClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
onDeleteRequest = (id) => {
|
||||||
|
this.setState({
|
||||||
|
deleteRequest: true,
|
||||||
|
deleteId: id
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
onConfirmRemoval = () => {
|
||||||
|
const { deleteId } = this.state;
|
||||||
|
this.props.onDelete(deleteId);
|
||||||
|
|
||||||
|
this.setState({
|
||||||
|
deleteRequest: false,
|
||||||
|
deleteId: -1,
|
||||||
|
selected: -1
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
onRejectRemoval = () => {
|
||||||
|
this.setState({
|
||||||
|
deleteRequest: false,
|
||||||
|
deleteId: -1
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
17
js/src/modals/SaveContract/index.js
Normal file
17
js/src/modals/SaveContract/index.js
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
// Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
export default from './saveContract';
|
20
js/src/modals/SaveContract/saveContract.css
Normal file
20
js/src/modals/SaveContract/saveContract.css
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
/* Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
.source {
|
||||||
|
margin-top: 2em;
|
||||||
|
}
|
109
js/src/modals/SaveContract/saveContract.js
Normal file
109
js/src/modals/SaveContract/saveContract.js
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
// Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import React, { Component, PropTypes } from 'react';
|
||||||
|
|
||||||
|
import SaveIcon from 'material-ui/svg-icons/content/save';
|
||||||
|
import ContentClear from 'material-ui/svg-icons/content/clear';
|
||||||
|
|
||||||
|
import { Button, Modal, Editor, Form, Input } from '../../ui';
|
||||||
|
import { ERRORS, validateName } from '../../util/validation';
|
||||||
|
|
||||||
|
import styles from './saveContract.css';
|
||||||
|
|
||||||
|
export default class SaveContract extends Component {
|
||||||
|
|
||||||
|
static propTypes = {
|
||||||
|
sourcecode: PropTypes.string.isRequired,
|
||||||
|
onClose: PropTypes.func.isRequired,
|
||||||
|
onSave: PropTypes.func.isRequired
|
||||||
|
};
|
||||||
|
|
||||||
|
state = {
|
||||||
|
name: '',
|
||||||
|
nameError: ERRORS.invalidName
|
||||||
|
};
|
||||||
|
|
||||||
|
render () {
|
||||||
|
const { sourcecode } = this.props;
|
||||||
|
const { name, nameError } = this.state;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
title='save contract'
|
||||||
|
actions={ this.renderDialogActions() }
|
||||||
|
visible
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<Form>
|
||||||
|
<Input
|
||||||
|
label='contract name'
|
||||||
|
hint='choose a name for this contract'
|
||||||
|
value={ name }
|
||||||
|
error={ nameError }
|
||||||
|
onChange={ this.onChangeName }
|
||||||
|
/>
|
||||||
|
</Form>
|
||||||
|
<Editor
|
||||||
|
className={ styles.source }
|
||||||
|
value={ sourcecode }
|
||||||
|
maxLines={ 20 }
|
||||||
|
readOnly
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
renderDialogActions () {
|
||||||
|
const cancelBtn = (
|
||||||
|
<Button
|
||||||
|
icon={ <ContentClear /> }
|
||||||
|
label='Cancel'
|
||||||
|
onClick={ this.onClose }
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
const confirmBtn = (
|
||||||
|
<Button
|
||||||
|
icon={ <SaveIcon /> }
|
||||||
|
label='Save'
|
||||||
|
disabled={ !!this.state.nameError }
|
||||||
|
onClick={ this.onSave }
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
return [ cancelBtn, confirmBtn ];
|
||||||
|
}
|
||||||
|
|
||||||
|
onClose = () => {
|
||||||
|
this.props.onClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
onSave = () => {
|
||||||
|
const { name } = this.state;
|
||||||
|
const { sourcecode } = this.props;
|
||||||
|
|
||||||
|
this.props.onSave({ name, sourcecode });
|
||||||
|
this.onClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
onChangeName = (event, value) => {
|
||||||
|
const { name, nameError } = validateName(value);
|
||||||
|
this.setState({ name, nameError });
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -24,6 +24,8 @@ import FirstRun from './FirstRun';
|
|||||||
import Shapeshift from './Shapeshift';
|
import Shapeshift from './Shapeshift';
|
||||||
import Transfer from './Transfer';
|
import Transfer from './Transfer';
|
||||||
import PasswordManager from './PasswordManager';
|
import PasswordManager from './PasswordManager';
|
||||||
|
import SaveContract from './SaveContract';
|
||||||
|
import LoadContract from './LoadContract';
|
||||||
|
|
||||||
export {
|
export {
|
||||||
AddAddress,
|
AddAddress,
|
||||||
@ -35,5 +37,7 @@ export {
|
|||||||
FirstRun,
|
FirstRun,
|
||||||
Shapeshift,
|
Shapeshift,
|
||||||
Transfer,
|
Transfer,
|
||||||
PasswordManager
|
PasswordManager,
|
||||||
|
LoadContract,
|
||||||
|
SaveContract
|
||||||
};
|
};
|
||||||
|
37
js/src/redux/providers/compilerActions.js
Normal file
37
js/src/redux/providers/compilerActions.js
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
// Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import CompilerWorker from 'worker-loader!./compilerWorker.js';
|
||||||
|
|
||||||
|
export function setWorker (worker) {
|
||||||
|
return {
|
||||||
|
type: 'setWorker',
|
||||||
|
worker
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setupWorker () {
|
||||||
|
return (dispatch, getState) => {
|
||||||
|
const state = getState();
|
||||||
|
|
||||||
|
if (state.compiler.worker) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const worker = new CompilerWorker();
|
||||||
|
dispatch(setWorker(worker));
|
||||||
|
};
|
||||||
|
}
|
29
js/src/redux/providers/compilerReducer.js
Normal file
29
js/src/redux/providers/compilerReducer.js
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
// Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import { handleActions } from 'redux-actions';
|
||||||
|
|
||||||
|
const initialState = {
|
||||||
|
worker: null
|
||||||
|
};
|
||||||
|
|
||||||
|
export default handleActions({
|
||||||
|
setWorker (state, action) {
|
||||||
|
const { worker } = action;
|
||||||
|
|
||||||
|
return Object.assign({}, state, { worker });
|
||||||
|
}
|
||||||
|
}, initialState);
|
177
js/src/redux/providers/compilerWorker.js
Normal file
177
js/src/redux/providers/compilerWorker.js
Normal file
@ -0,0 +1,177 @@
|
|||||||
|
// Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import solc from 'solc/browser-wrapper';
|
||||||
|
import { isWebUri } from 'valid-url';
|
||||||
|
|
||||||
|
self.solcVersions = {};
|
||||||
|
self.files = {};
|
||||||
|
self.lastCompile = {
|
||||||
|
sourcecode: '',
|
||||||
|
result: '',
|
||||||
|
version: ''
|
||||||
|
};
|
||||||
|
|
||||||
|
// eslint-disable-next-line no-undef
|
||||||
|
onmessage = (event) => {
|
||||||
|
const message = JSON.parse(event.data);
|
||||||
|
|
||||||
|
switch (message.action) {
|
||||||
|
case 'compile':
|
||||||
|
compile(message.data);
|
||||||
|
break;
|
||||||
|
case 'load':
|
||||||
|
load(message.data);
|
||||||
|
break;
|
||||||
|
case 'setFiles':
|
||||||
|
setFiles(message.data);
|
||||||
|
break;
|
||||||
|
case 'close':
|
||||||
|
close();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
function setFiles (files) {
|
||||||
|
const prevFiles = self.files;
|
||||||
|
const nextFiles = files.reduce((obj, file) => {
|
||||||
|
obj[file.name] = file.sourcecode;
|
||||||
|
return obj;
|
||||||
|
}, {});
|
||||||
|
|
||||||
|
self.files = {
|
||||||
|
...prevFiles,
|
||||||
|
...nextFiles
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function findImports (path) {
|
||||||
|
if (self.files[path]) {
|
||||||
|
if (self.files[path].error) {
|
||||||
|
return { error: self.files[path].error };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { contents: self.files[path] };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isWebUri(path)) {
|
||||||
|
console.log('[worker] fetching', path);
|
||||||
|
|
||||||
|
fetch(path)
|
||||||
|
.then((r) => r.text())
|
||||||
|
.then((c) => {
|
||||||
|
console.log('[worker]', 'got content at ' + path);
|
||||||
|
self.files[path] = c;
|
||||||
|
|
||||||
|
postMessage(JSON.stringify({
|
||||||
|
event: 'try-again'
|
||||||
|
}));
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
console.error('[worker]', 'fetching', path, e);
|
||||||
|
self.files[path] = { error: e };
|
||||||
|
});
|
||||||
|
|
||||||
|
return { error: '__parity_tryAgain' };
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[worker] path ${path} not found...`);
|
||||||
|
return { error: 'File not found' };
|
||||||
|
}
|
||||||
|
|
||||||
|
function compile (data) {
|
||||||
|
const { sourcecode, build } = data;
|
||||||
|
const { longVersion } = build;
|
||||||
|
|
||||||
|
if (self.lastCompile.sourcecode === sourcecode && self.lastCompile.longVersion === longVersion) {
|
||||||
|
return postMessage(JSON.stringify({
|
||||||
|
event: 'compiled',
|
||||||
|
data: self.lastCompile.result
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchSolc(build)
|
||||||
|
.then((compiler) => {
|
||||||
|
const input = {
|
||||||
|
'': sourcecode
|
||||||
|
};
|
||||||
|
|
||||||
|
const compiled = compiler.compile({ sources: input }, 0, findImports);
|
||||||
|
|
||||||
|
self.lastCompile = {
|
||||||
|
version: longVersion, result: compiled,
|
||||||
|
sourcecode
|
||||||
|
};
|
||||||
|
|
||||||
|
postMessage(JSON.stringify({
|
||||||
|
event: 'compiled',
|
||||||
|
data: compiled
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function load (build) {
|
||||||
|
postMessage(JSON.stringify({
|
||||||
|
event: 'loading',
|
||||||
|
data: true
|
||||||
|
}));
|
||||||
|
|
||||||
|
fetchSolc(build)
|
||||||
|
.then(() => {
|
||||||
|
postMessage(JSON.stringify({
|
||||||
|
event: 'loading',
|
||||||
|
data: false
|
||||||
|
}));
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
postMessage(JSON.stringify({
|
||||||
|
event: 'loading',
|
||||||
|
data: false
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function fetchSolc (build) {
|
||||||
|
const { path, longVersion } = build;
|
||||||
|
|
||||||
|
if (self.solcVersions[path]) {
|
||||||
|
return Promise.resolve(self.solcVersions[path]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const URL = `https://raw.githubusercontent.com/ethereum/solc-bin/gh-pages/bin/${path}`;
|
||||||
|
console.log(`[worker] fetching solc-bin ${longVersion} at ${URL}`);
|
||||||
|
|
||||||
|
return fetch(URL)
|
||||||
|
.then((r) => r.text())
|
||||||
|
.then((code) => {
|
||||||
|
const solcCode = code.replace(/^var Module;/, 'var Module=self.__solcModule;');
|
||||||
|
self.__solcModule = {};
|
||||||
|
|
||||||
|
console.log(`[worker] evaluating ${longVersion}`);
|
||||||
|
|
||||||
|
// eslint-disable-next-line no-eval
|
||||||
|
eval(solcCode);
|
||||||
|
|
||||||
|
console.log(`[worker] done evaluating ${longVersion}`);
|
||||||
|
|
||||||
|
const compiler = solc(self.__solcModule);
|
||||||
|
self.solcVersions[path] = compiler;
|
||||||
|
return compiler;
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
console.error('fetching solc', e);
|
||||||
|
});
|
||||||
|
}
|
@ -26,3 +26,4 @@ export personalReducer from './personalReducer';
|
|||||||
export signerReducer from './signerReducer';
|
export signerReducer from './signerReducer';
|
||||||
export statusReducer from './statusReducer';
|
export statusReducer from './statusReducer';
|
||||||
export blockchainReducer from './blockchainReducer';
|
export blockchainReducer from './blockchainReducer';
|
||||||
|
export compilerReducer from './compilerReducer';
|
||||||
|
@ -16,6 +16,9 @@
|
|||||||
|
|
||||||
import * as actions from './signerActions';
|
import * as actions from './signerActions';
|
||||||
|
|
||||||
|
import { inHex } from '../../api/format/input';
|
||||||
|
import { Wallet } from '../../util/wallet';
|
||||||
|
|
||||||
export default class SignerMiddleware {
|
export default class SignerMiddleware {
|
||||||
constructor (api) {
|
constructor (api) {
|
||||||
this._api = api;
|
this._api = api;
|
||||||
@ -49,23 +52,58 @@ export default class SignerMiddleware {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onConfirmStart = (store, action) => {
|
onConfirmStart = (store, action) => {
|
||||||
const { id, password } = action.payload;
|
const { id, password, wallet, payload } = action.payload;
|
||||||
|
|
||||||
this._api.signer
|
const handlePromise = promise => {
|
||||||
.confirmRequest(id, {}, password)
|
promise
|
||||||
.then((txHash) => {
|
.then((txHash) => {
|
||||||
console.log('confirmRequest', id, txHash);
|
console.log('confirmRequest', id, txHash);
|
||||||
if (!txHash) {
|
if (!txHash) {
|
||||||
store.dispatch(actions.errorConfirmRequest({ id, err: 'Unable to confirm.' }));
|
store.dispatch(actions.errorConfirmRequest({ id, err: 'Unable to confirm.' }));
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
store.dispatch(actions.successConfirmRequest({ id, txHash }));
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error('confirmRequest', id, error);
|
||||||
|
store.dispatch(actions.errorConfirmRequest({ id, err: error.message }));
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Sign request in-browser
|
||||||
|
if (wallet && payload.transaction) {
|
||||||
|
const { transaction } = payload;
|
||||||
|
|
||||||
|
(transaction.nonce.isZero()
|
||||||
|
? this._api.parity.nextNonce(transaction.from)
|
||||||
|
: Promise.resolve(transaction.nonce)
|
||||||
|
).then(nonce => {
|
||||||
|
let txData = {
|
||||||
|
to: inHex(transaction.to),
|
||||||
|
nonce: inHex(transaction.nonce.isZero() ? nonce : transaction.nonce),
|
||||||
|
gasPrice: inHex(transaction.gasPrice),
|
||||||
|
gasLimit: inHex(transaction.gas),
|
||||||
|
value: inHex(transaction.value),
|
||||||
|
data: inHex(transaction.data)
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
// NOTE: Derving the key takes significant amount of time,
|
||||||
|
// make sure to display some kind of "in-progress" state.
|
||||||
|
const signer = Wallet.fromJson(wallet, password);
|
||||||
|
const rawTx = signer.signTransaction(txData);
|
||||||
|
|
||||||
|
handlePromise(this._api.signer.confirmRequestRaw(id, rawTx));
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
store.dispatch(actions.errorConfirmRequest({ id, err: error.message }));
|
||||||
}
|
}
|
||||||
|
|
||||||
store.dispatch(actions.successConfirmRequest({ id, txHash }));
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
console.error('confirmRequest', id, error);
|
|
||||||
store.dispatch(actions.errorConfirmRequest({ id, err: error.message }));
|
|
||||||
});
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
handlePromise(this._api.signer.confirmRequest(id, {}, password));
|
||||||
}
|
}
|
||||||
|
|
||||||
onRejectStart = (store, action) => {
|
onRejectStart = (store, action) => {
|
||||||
|
@ -85,11 +85,6 @@ export default class Status {
|
|||||||
setTimeout(this._pollStatus, timeout);
|
setTimeout(this._pollStatus, timeout);
|
||||||
};
|
};
|
||||||
|
|
||||||
const wasConnected = this._store.getState().nodeStatus.isConnected;
|
|
||||||
if (isConnected !== wasConnected) {
|
|
||||||
this._fetchEnode();
|
|
||||||
}
|
|
||||||
|
|
||||||
this._store.dispatch(statusCollection({ isConnected, isConnecting, needsToken, secureToken }));
|
this._store.dispatch(statusCollection({ isConnected, isConnecting, needsToken, secureToken }));
|
||||||
|
|
||||||
if (!isConnected) {
|
if (!isConnected) {
|
||||||
@ -111,8 +106,7 @@ export default class Status {
|
|||||||
this._api.parity.netPort(),
|
this._api.parity.netPort(),
|
||||||
this._api.parity.nodeName(),
|
this._api.parity.nodeName(),
|
||||||
this._api.parity.rpcSettings(),
|
this._api.parity.rpcSettings(),
|
||||||
this._api.eth.syncing(),
|
this._api.eth.syncing()
|
||||||
this._pollTraceMode()
|
|
||||||
])
|
])
|
||||||
.then(([clientVersion, coinbase, defaultExtraData, extraData, gasFloorTarget, hashrate, minGasPrice, netChain, netPeers, netPort, nodeName, rpcSettings, syncing, traceMode]) => {
|
.then(([clientVersion, coinbase, defaultExtraData, extraData, gasFloorTarget, hashrate, minGasPrice, netChain, netPeers, netPort, nodeName, rpcSettings, syncing, traceMode]) => {
|
||||||
const isTest = netChain === 'morden' || netChain === 'testnet';
|
const isTest = netChain === 'morden' || netChain === 'testnet';
|
||||||
@ -134,12 +128,12 @@ export default class Status {
|
|||||||
isTest,
|
isTest,
|
||||||
traceMode
|
traceMode
|
||||||
}));
|
}));
|
||||||
nextTimeout();
|
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
console.error('_pollStatus', error);
|
console.error('_pollStatus', error);
|
||||||
nextTimeout();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
nextTimeout();
|
||||||
}
|
}
|
||||||
|
|
||||||
_pollLogs = () => {
|
_pollLogs = () => {
|
||||||
|
@ -17,7 +17,7 @@
|
|||||||
import { combineReducers } from 'redux';
|
import { combineReducers } from 'redux';
|
||||||
import { routerReducer } from 'react-router-redux';
|
import { routerReducer } from 'react-router-redux';
|
||||||
|
|
||||||
import { apiReducer, balancesReducer, blockchainReducer, imagesReducer, personalReducer, signerReducer, statusReducer as nodeStatusReducer } from './providers';
|
import { apiReducer, balancesReducer, blockchainReducer, compilerReducer, imagesReducer, personalReducer, signerReducer, statusReducer as nodeStatusReducer } from './providers';
|
||||||
|
|
||||||
import { errorReducer } from '../ui/Errors';
|
import { errorReducer } from '../ui/Errors';
|
||||||
import { settingsReducer } from '../views/Settings';
|
import { settingsReducer } from '../views/Settings';
|
||||||
@ -33,6 +33,7 @@ export default function () {
|
|||||||
|
|
||||||
balances: balancesReducer,
|
balances: balancesReducer,
|
||||||
blockchain: blockchainReducer,
|
blockchain: blockchainReducer,
|
||||||
|
compiler: compilerReducer,
|
||||||
images: imagesReducer,
|
images: imagesReducer,
|
||||||
nodeStatus: nodeStatusReducer,
|
nodeStatus: nodeStatusReducer,
|
||||||
personal: personalReducer,
|
personal: personalReducer,
|
||||||
|
@ -23,9 +23,10 @@ export default class SecureApi extends Api {
|
|||||||
super(new Api.Transport.Ws(url, sysuiToken));
|
super(new Api.Transport.Ws(url, sysuiToken));
|
||||||
|
|
||||||
this._isConnecting = true;
|
this._isConnecting = true;
|
||||||
this._connectState = 0;
|
this._connectState = sysuiToken === 'initial' ? 1 : 0;
|
||||||
this._needsToken = false;
|
this._needsToken = false;
|
||||||
this._dappsPort = 8080;
|
this._dappsPort = 8080;
|
||||||
|
this._dappsInterface = null;
|
||||||
this._signerPort = 8180;
|
this._signerPort = 8180;
|
||||||
|
|
||||||
console.log('SecureApi:constructor', sysuiToken);
|
console.log('SecureApi:constructor', sysuiToken);
|
||||||
@ -100,17 +101,19 @@ export default class SecureApi extends Api {
|
|||||||
Promise
|
Promise
|
||||||
.all([
|
.all([
|
||||||
this.parity.dappsPort(),
|
this.parity.dappsPort(),
|
||||||
|
this.parity.dappsInterface(),
|
||||||
this.parity.signerPort()
|
this.parity.signerPort()
|
||||||
])
|
])
|
||||||
.then(([dappsPort, signerPort]) => {
|
.then(([dappsPort, dappsInterface, signerPort]) => {
|
||||||
this._dappsPort = dappsPort.toNumber();
|
this._dappsPort = dappsPort.toNumber();
|
||||||
|
this._dappsInterface = dappsInterface;
|
||||||
this._signerPort = signerPort.toNumber();
|
this._signerPort = signerPort.toNumber();
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log('SecureApi:connectSuccess', this._transport.token);
|
console.log('SecureApi:connectSuccess', this._transport.token);
|
||||||
}
|
}
|
||||||
|
|
||||||
updateToken (token, connectState) {
|
updateToken (token, connectState = 0) {
|
||||||
this._connectState = connectState;
|
this._connectState = connectState;
|
||||||
this._transport.updateToken(token.replace(/[^a-zA-Z0-9]/g, ''));
|
this._transport.updateToken(token.replace(/[^a-zA-Z0-9]/g, ''));
|
||||||
this._followConnection();
|
this._followConnection();
|
||||||
@ -122,7 +125,17 @@ export default class SecureApi extends Api {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get dappsUrl () {
|
get dappsUrl () {
|
||||||
return `http://${window.location.hostname}:${this._dappsPort}`;
|
let hostname;
|
||||||
|
|
||||||
|
if (window.location.hostname === 'home.parity') {
|
||||||
|
hostname = 'dapps.parity';
|
||||||
|
} else if (!this._dappsInterface || this._dappsInterface === '0.0.0.0') {
|
||||||
|
hostname = window.location.hostname;
|
||||||
|
} else {
|
||||||
|
hostname = this._dappsInterface;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `http://${hostname}:${this._dappsPort}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
get signerPort () {
|
get signerPort () {
|
||||||
|
45
js/src/ui/Actionbar/Import/import.css
vendored
Normal file
45
js/src/ui/Actionbar/Import/import.css
vendored
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
/* Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
.importZone {
|
||||||
|
width: 100%;
|
||||||
|
height: 200px;
|
||||||
|
border-width: 2px;
|
||||||
|
border-color: #666;
|
||||||
|
border-style: dashed;
|
||||||
|
border-radius: 10px;
|
||||||
|
|
||||||
|
background-color: rgba(50, 50, 50, 0.2);
|
||||||
|
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-size: 1.2em;
|
||||||
|
|
||||||
|
transition: all 0.5s ease;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
cursor: pointer;
|
||||||
|
border-radius: 0;
|
||||||
|
background-color: rgba(50, 50, 50, 0.5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.desc {
|
||||||
|
margin-top: 0;
|
||||||
|
color: #ccc;
|
||||||
|
}
|
198
js/src/ui/Actionbar/Import/import.js
Normal file
198
js/src/ui/Actionbar/Import/import.js
Normal file
@ -0,0 +1,198 @@
|
|||||||
|
// Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import React, { Component, PropTypes } from 'react';
|
||||||
|
import Dropzone from 'react-dropzone';
|
||||||
|
import FileUploadIcon from 'material-ui/svg-icons/file/file-upload';
|
||||||
|
import ContentClear from 'material-ui/svg-icons/content/clear';
|
||||||
|
import ActionDoneAll from 'material-ui/svg-icons/action/done-all';
|
||||||
|
|
||||||
|
import { Modal, Button } from '../../';
|
||||||
|
|
||||||
|
import styles from './import.css';
|
||||||
|
|
||||||
|
const initialState = {
|
||||||
|
step: 0,
|
||||||
|
show: false,
|
||||||
|
validate: false,
|
||||||
|
validationBody: null,
|
||||||
|
content: ''
|
||||||
|
};
|
||||||
|
|
||||||
|
export default class ActionbarImport extends Component {
|
||||||
|
|
||||||
|
static propTypes = {
|
||||||
|
onConfirm: PropTypes.func.isRequired,
|
||||||
|
renderValidation: PropTypes.func,
|
||||||
|
className: PropTypes.string,
|
||||||
|
title: PropTypes.string
|
||||||
|
};
|
||||||
|
|
||||||
|
static defaultProps = {
|
||||||
|
title: 'Import from a file'
|
||||||
|
};
|
||||||
|
|
||||||
|
state = Object.assign({}, initialState);
|
||||||
|
|
||||||
|
render () {
|
||||||
|
const { className } = this.props;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Button
|
||||||
|
className={ className }
|
||||||
|
icon={ <FileUploadIcon /> }
|
||||||
|
label='import'
|
||||||
|
onClick={ this.onOpenModal }
|
||||||
|
/>
|
||||||
|
{ this.renderModal() }
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
renderModal () {
|
||||||
|
const { title, renderValidation } = this.props;
|
||||||
|
const { show, step } = this.state;
|
||||||
|
|
||||||
|
if (!show) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasSteps = typeof renderValidation === 'function';
|
||||||
|
|
||||||
|
const steps = hasSteps ? [ 'select a file', 'validate' ] : null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
actions={ this.renderActions() }
|
||||||
|
title={ title }
|
||||||
|
steps={ steps }
|
||||||
|
current={ step }
|
||||||
|
visible
|
||||||
|
>
|
||||||
|
{ this.renderBody() }
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
renderActions () {
|
||||||
|
const { validate } = this.state;
|
||||||
|
|
||||||
|
const cancelBtn = (
|
||||||
|
<Button
|
||||||
|
key='cancel'
|
||||||
|
label='Cancel'
|
||||||
|
icon={ <ContentClear /> }
|
||||||
|
onClick={ this.onCloseModal }
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (validate) {
|
||||||
|
const confirmBtn = (
|
||||||
|
<Button
|
||||||
|
key='confirm'
|
||||||
|
label='Confirm'
|
||||||
|
icon={ <ActionDoneAll /> }
|
||||||
|
onClick={ this.onConfirm }
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
return [ cancelBtn, confirmBtn ];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [ cancelBtn ];
|
||||||
|
}
|
||||||
|
|
||||||
|
renderBody () {
|
||||||
|
const { validate } = this.state;
|
||||||
|
|
||||||
|
if (validate) {
|
||||||
|
return this.renderValidation();
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.renderFileSelect();
|
||||||
|
}
|
||||||
|
|
||||||
|
renderFileSelect () {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Dropzone
|
||||||
|
onDrop={ this.onDrop }
|
||||||
|
multiple={ false }
|
||||||
|
className={ styles.importZone }
|
||||||
|
>
|
||||||
|
<div>Drop a file here, or click to select a file to upload.</div>
|
||||||
|
</Dropzone>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
renderValidation () {
|
||||||
|
const { validationBody } = this.state;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<p className={ styles.desc }>
|
||||||
|
Confirm that this is what was intended to import.
|
||||||
|
</p>
|
||||||
|
<div>
|
||||||
|
{ validationBody }
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
onDrop = (files) => {
|
||||||
|
const { renderValidation } = this.props;
|
||||||
|
|
||||||
|
const file = files[0];
|
||||||
|
const reader = new FileReader();
|
||||||
|
|
||||||
|
reader.onload = (e) => {
|
||||||
|
const content = e.target.result;
|
||||||
|
|
||||||
|
if (typeof renderValidation !== 'function') {
|
||||||
|
this.props.onConfirm(content);
|
||||||
|
return this.onCloseModal();
|
||||||
|
}
|
||||||
|
|
||||||
|
this.setState({
|
||||||
|
step: 1,
|
||||||
|
validate: true,
|
||||||
|
validationBody: renderValidation(content),
|
||||||
|
content
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
reader.readAsText(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
onConfirm = () => {
|
||||||
|
const { content } = this.state;
|
||||||
|
|
||||||
|
this.props.onConfirm(content);
|
||||||
|
return this.onCloseModal();
|
||||||
|
}
|
||||||
|
|
||||||
|
onOpenModal = () => {
|
||||||
|
this.setState({ show: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
onCloseModal = () => {
|
||||||
|
this.setState(initialState);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
17
js/src/ui/Actionbar/Import/index.js
Normal file
17
js/src/ui/Actionbar/Import/index.js
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
// Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
export default from './import';
|
@ -19,6 +19,7 @@ import { FlatButton } from 'material-ui';
|
|||||||
|
|
||||||
export default class Button extends Component {
|
export default class Button extends Component {
|
||||||
static propTypes = {
|
static propTypes = {
|
||||||
|
backgroundColor: PropTypes.string,
|
||||||
className: PropTypes.string,
|
className: PropTypes.string,
|
||||||
disabled: PropTypes.bool,
|
disabled: PropTypes.bool,
|
||||||
icon: PropTypes.node,
|
icon: PropTypes.node,
|
||||||
@ -26,19 +27,25 @@ export default class Button extends Component {
|
|||||||
React.PropTypes.string,
|
React.PropTypes.string,
|
||||||
React.PropTypes.object
|
React.PropTypes.object
|
||||||
]),
|
]),
|
||||||
onClick: PropTypes.func
|
onClick: PropTypes.func,
|
||||||
|
primary: PropTypes.bool
|
||||||
|
}
|
||||||
|
|
||||||
|
static defaultProps = {
|
||||||
|
primary: true
|
||||||
}
|
}
|
||||||
|
|
||||||
render () {
|
render () {
|
||||||
const { className, disabled, icon, label, onClick } = this.props;
|
const { className, backgroundColor, disabled, icon, label, primary, onClick } = this.props;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<FlatButton
|
<FlatButton
|
||||||
className={ className }
|
className={ className }
|
||||||
|
backgroundColor={ backgroundColor }
|
||||||
disabled={ disabled }
|
disabled={ disabled }
|
||||||
icon={ icon }
|
icon={ icon }
|
||||||
label={ label }
|
label={ label }
|
||||||
primary
|
primary={ primary }
|
||||||
onTouchTap={ onClick } />
|
onTouchTap={ onClick } />
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
103
js/src/ui/Editor/editor.js
Normal file
103
js/src/ui/Editor/editor.js
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
// Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import React, { PropTypes, Component } from 'react';
|
||||||
|
|
||||||
|
import 'brace';
|
||||||
|
import AceEditor from 'react-ace';
|
||||||
|
import { noop } from 'lodash';
|
||||||
|
|
||||||
|
import 'brace/theme/solarized_dark';
|
||||||
|
import 'brace/mode/json';
|
||||||
|
import './mode-solidity';
|
||||||
|
|
||||||
|
export default class Editor extends Component {
|
||||||
|
|
||||||
|
static propTypes = {
|
||||||
|
className: PropTypes.string,
|
||||||
|
value: PropTypes.string,
|
||||||
|
mode: PropTypes.string,
|
||||||
|
maxLines: PropTypes.number,
|
||||||
|
annotations: PropTypes.array,
|
||||||
|
onExecute: PropTypes.func,
|
||||||
|
onChange: PropTypes.func,
|
||||||
|
readOnly: PropTypes.bool
|
||||||
|
};
|
||||||
|
|
||||||
|
static defaultProps = {
|
||||||
|
className: '',
|
||||||
|
value: '',
|
||||||
|
mode: 'javascript',
|
||||||
|
annotations: [],
|
||||||
|
onExecute: noop,
|
||||||
|
onChange: noop,
|
||||||
|
readOnly: false
|
||||||
|
};
|
||||||
|
|
||||||
|
componentWillMount () {
|
||||||
|
this.name = `PARITY_EDITOR_${Math.round(Math.random() * 99999)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
render () {
|
||||||
|
const { className, annotations, value, readOnly, mode, maxLines } = this.props;
|
||||||
|
const commands = [
|
||||||
|
{
|
||||||
|
name: 'execut',
|
||||||
|
bindKey: { win: 'Ctrl-Enter', mac: 'Command-Enter' },
|
||||||
|
exec: this.handleExecute
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
const max = (maxLines !== undefined)
|
||||||
|
? maxLines
|
||||||
|
: (readOnly ? value.split('\n').length + 1 : null);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AceEditor
|
||||||
|
mode={ mode }
|
||||||
|
theme='solarized_dark'
|
||||||
|
width='100%'
|
||||||
|
ref='brace'
|
||||||
|
style={ { flex: 1 } }
|
||||||
|
onChange={ this.handleOnChange }
|
||||||
|
name={ this.name }
|
||||||
|
editorProps={ { $blockScrolling: Infinity } }
|
||||||
|
setOptions={ {
|
||||||
|
useWorker: false,
|
||||||
|
fontFamily: 'monospace',
|
||||||
|
fontSize: '0.9em'
|
||||||
|
} }
|
||||||
|
maxLines={ max }
|
||||||
|
enableBasicAutocompletion={ !readOnly }
|
||||||
|
showPrintMargin={ false }
|
||||||
|
annotations={ annotations }
|
||||||
|
value={ value }
|
||||||
|
commands={ commands }
|
||||||
|
readOnly={ readOnly }
|
||||||
|
className={ className }
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
handleExecute = () => {
|
||||||
|
this.props.onExecute();
|
||||||
|
}
|
||||||
|
|
||||||
|
handleOnChange = (value) => {
|
||||||
|
this.props.onChange(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
17
js/src/ui/Editor/index.js
Normal file
17
js/src/ui/Editor/index.js
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
// Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
export default from './editor';
|
994
js/src/ui/Editor/mode-solidity.js
Normal file
994
js/src/ui/Editor/mode-solidity.js
Normal file
@ -0,0 +1,994 @@
|
|||||||
|
// Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This file has been taken from `ethereum/browser-solidity`
|
||||||
|
*
|
||||||
|
* @see: https://raw.githubusercontent.com/ethereum/browser-solidity/master/src/mode-solidity.js
|
||||||
|
*/
|
||||||
|
/* eslint-disable */
|
||||||
|
var ace = window.ace;
|
||||||
|
|
||||||
|
ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
var oop = acequire("../lib/oop");
|
||||||
|
var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules;
|
||||||
|
|
||||||
|
var DocCommentHighlightRules = function() {
|
||||||
|
this.$rules = {
|
||||||
|
"start" : [ {
|
||||||
|
token : "comment.doc.tag",
|
||||||
|
regex : "@[\\w\\d_]+" // TODO: fix email addresses
|
||||||
|
},
|
||||||
|
DocCommentHighlightRules.getTagRule(),
|
||||||
|
{
|
||||||
|
defaultToken : "comment.doc",
|
||||||
|
caseInsensitive: true
|
||||||
|
}]
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
oop.inherits(DocCommentHighlightRules, TextHighlightRules);
|
||||||
|
|
||||||
|
DocCommentHighlightRules.getTagRule = function(start) {
|
||||||
|
return {
|
||||||
|
token : "comment.doc.tag.storage.type",
|
||||||
|
regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b"
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
DocCommentHighlightRules.getStartRule = function(start) {
|
||||||
|
return {
|
||||||
|
token : "comment.doc", // doc comment
|
||||||
|
regex : "\\/\\*(?=\\*)",
|
||||||
|
next : start
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
DocCommentHighlightRules.getEndRule = function (start) {
|
||||||
|
return {
|
||||||
|
token : "comment.doc", // closing comment
|
||||||
|
regex : "\\*\\/",
|
||||||
|
next : start
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
exports.DocCommentHighlightRules = DocCommentHighlightRules;
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(acequire, exports, module) {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
var oop = acequire("../lib/oop");
|
||||||
|
var DocCommentHighlightRules = acequire("./doc_comment_highlight_rules").DocCommentHighlightRules;
|
||||||
|
var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules;
|
||||||
|
|
||||||
|
var JavaScriptHighlightRules = function(options) {
|
||||||
|
var intTypes = 'bytes|int|uint';
|
||||||
|
for (var width = 8; width <= 256; width += 8)
|
||||||
|
intTypes += '|bytes' + (width / 8) + '|uint' + width + '|int' + width;
|
||||||
|
var keywordMapper = this.createKeywordMapper({
|
||||||
|
"variable.language":
|
||||||
|
"this|bool|string|byte|bytes|bytes0|address|" + intTypes,
|
||||||
|
"keyword":
|
||||||
|
"contract|library|constant|event|modifier|" +
|
||||||
|
"struct|mapping|enum|break|continue|delete|else|for|function|" +
|
||||||
|
"if|new|return|returns|var|while|using|" +
|
||||||
|
"private|public|external|internal|storage|memory",
|
||||||
|
"storage.type":
|
||||||
|
"constant|var|function",
|
||||||
|
"constant.language.boolean": "true|false"
|
||||||
|
}, "identifier");
|
||||||
|
var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void";
|
||||||
|
var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*\\b";
|
||||||
|
|
||||||
|
var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex
|
||||||
|
"u[0-9a-fA-F]{4}|" + // unicode
|
||||||
|
"[0-2][0-7]{0,2}|" + // oct
|
||||||
|
"3[0-6][0-7]?|" + // oct
|
||||||
|
"37[0-7]?|" + // oct
|
||||||
|
"[4-7][0-7]?|" + //oct
|
||||||
|
".)";
|
||||||
|
|
||||||
|
this.$rules = {
|
||||||
|
"no_regex" : [
|
||||||
|
{
|
||||||
|
token : "comment",
|
||||||
|
regex : "\\/\\/",
|
||||||
|
next : "line_comment"
|
||||||
|
},
|
||||||
|
DocCommentHighlightRules.getStartRule("doc-start"),
|
||||||
|
{
|
||||||
|
token : "comment", // multi line comment
|
||||||
|
regex : /\/\*/,
|
||||||
|
next : "comment"
|
||||||
|
}, {
|
||||||
|
token : "string",
|
||||||
|
regex : "'(?=.)",
|
||||||
|
next : "qstring"
|
||||||
|
}, {
|
||||||
|
token : "string",
|
||||||
|
regex : '"(?=.)',
|
||||||
|
next : "qqstring"
|
||||||
|
}, {
|
||||||
|
token : "constant.numeric", // hex
|
||||||
|
regex : /0[xX][0-9a-fA-F]+\b/
|
||||||
|
}, {
|
||||||
|
token : "constant.numeric", // float
|
||||||
|
regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/
|
||||||
|
}, {
|
||||||
|
token : [
|
||||||
|
"storage.type", "punctuation.operator", "support.function",
|
||||||
|
"punctuation.operator", "entity.name.function", "text","keyword.operator"
|
||||||
|
],
|
||||||
|
regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)",
|
||||||
|
next: "function_arguments"
|
||||||
|
}, {
|
||||||
|
token : [
|
||||||
|
"storage.type", "punctuation.operator", "entity.name.function", "text",
|
||||||
|
"keyword.operator", "text", "storage.type", "text", "paren.lparen"
|
||||||
|
],
|
||||||
|
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
|
||||||
|
next: "function_arguments"
|
||||||
|
}, {
|
||||||
|
token : [
|
||||||
|
"entity.name.function", "text", "keyword.operator", "text", "storage.type",
|
||||||
|
"text", "paren.lparen"
|
||||||
|
],
|
||||||
|
regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
|
||||||
|
next: "function_arguments"
|
||||||
|
}, {
|
||||||
|
token : [
|
||||||
|
"storage.type", "punctuation.operator", "entity.name.function", "text",
|
||||||
|
"keyword.operator", "text",
|
||||||
|
"storage.type", "text", "entity.name.function", "text", "paren.lparen"
|
||||||
|
],
|
||||||
|
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()",
|
||||||
|
next: "function_arguments"
|
||||||
|
}, {
|
||||||
|
token : [
|
||||||
|
"storage.type", "text", "entity.name.function", "text", "paren.lparen"
|
||||||
|
],
|
||||||
|
regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()",
|
||||||
|
next: "function_arguments"
|
||||||
|
}, {
|
||||||
|
token : [
|
||||||
|
"entity.name.function", "text", "punctuation.operator",
|
||||||
|
"text", "storage.type", "text", "paren.lparen"
|
||||||
|
],
|
||||||
|
regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()",
|
||||||
|
next: "function_arguments"
|
||||||
|
}, {
|
||||||
|
token : [
|
||||||
|
"text", "text", "storage.type", "text", "paren.lparen"
|
||||||
|
],
|
||||||
|
regex : "(:)(\\s*)(function)(\\s*)(\\()",
|
||||||
|
next: "function_arguments"
|
||||||
|
}, {
|
||||||
|
token : "keyword",
|
||||||
|
regex : "(?:" + kwBeforeRe + ")\\b",
|
||||||
|
next : "start"
|
||||||
|
}, {
|
||||||
|
token : ["punctuation.operator", "support.function"],
|
||||||
|
regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/
|
||||||
|
}, {
|
||||||
|
token : ["punctuation.operator", "support.function.dom"],
|
||||||
|
regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/
|
||||||
|
}, {
|
||||||
|
token : ["punctuation.operator", "support.constant"],
|
||||||
|
regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/
|
||||||
|
}, {
|
||||||
|
token : ["support.constant"],
|
||||||
|
regex : /that\b/
|
||||||
|
}, {
|
||||||
|
token : ["storage.type", "punctuation.operator", "support.function.firebug"],
|
||||||
|
regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/
|
||||||
|
}, {
|
||||||
|
token : keywordMapper,
|
||||||
|
regex : identifierRe
|
||||||
|
}, {
|
||||||
|
token : "keyword.operator",
|
||||||
|
regex : /--|\*\*|\+\+|===|==|=|!=|!==|=>|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|[!$%&*+\-~\/^]=?/,
|
||||||
|
next : "start"
|
||||||
|
}, {
|
||||||
|
token : "punctuation.operator",
|
||||||
|
regex : /[?:,;.]/,
|
||||||
|
next : "start"
|
||||||
|
}, {
|
||||||
|
token : "paren.lparen",
|
||||||
|
regex : /[\[({]/,
|
||||||
|
next : "start"
|
||||||
|
}, {
|
||||||
|
token : "paren.rparen",
|
||||||
|
regex : /[\])}]/
|
||||||
|
}, {
|
||||||
|
token: "comment",
|
||||||
|
regex: /^#!.*$/
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"start": [
|
||||||
|
DocCommentHighlightRules.getStartRule("doc-start"),
|
||||||
|
{
|
||||||
|
token : "comment", // multi line comment
|
||||||
|
regex : "\\/\\*",
|
||||||
|
next : "comment_regex_allowed"
|
||||||
|
}, {
|
||||||
|
token : "comment",
|
||||||
|
regex : "\\/\\/",
|
||||||
|
next : "line_comment_regex_allowed"
|
||||||
|
}, {
|
||||||
|
token: "string.regexp",
|
||||||
|
regex: "\\/",
|
||||||
|
next: "regex"
|
||||||
|
}, {
|
||||||
|
token : "text",
|
||||||
|
regex : "\\s+|^$",
|
||||||
|
next : "start"
|
||||||
|
}, {
|
||||||
|
token: "empty",
|
||||||
|
regex: "",
|
||||||
|
next: "no_regex"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"regex": [
|
||||||
|
{
|
||||||
|
token: "regexp.keyword.operator",
|
||||||
|
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
|
||||||
|
}, {
|
||||||
|
token: "string.regexp",
|
||||||
|
regex: "/[sxngimy]*",
|
||||||
|
next: "no_regex"
|
||||||
|
}, {
|
||||||
|
token : "invalid",
|
||||||
|
regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/
|
||||||
|
}, {
|
||||||
|
token : "constant.language.escape",
|
||||||
|
regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/
|
||||||
|
}, {
|
||||||
|
token : "constant.language.delimiter",
|
||||||
|
regex: /\|/
|
||||||
|
}, {
|
||||||
|
token: "constant.language.escape",
|
||||||
|
regex: /\[\^?/,
|
||||||
|
next: "regex_character_class"
|
||||||
|
}, {
|
||||||
|
token: "empty",
|
||||||
|
regex: "$",
|
||||||
|
next: "no_regex"
|
||||||
|
}, {
|
||||||
|
defaultToken: "string.regexp"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"regex_character_class": [
|
||||||
|
{
|
||||||
|
token: "regexp.charclass.keyword.operator",
|
||||||
|
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
|
||||||
|
}, {
|
||||||
|
token: "constant.language.escape",
|
||||||
|
regex: "]",
|
||||||
|
next: "regex"
|
||||||
|
}, {
|
||||||
|
token: "constant.language.escape",
|
||||||
|
regex: "-"
|
||||||
|
}, {
|
||||||
|
token: "empty",
|
||||||
|
regex: "$",
|
||||||
|
next: "no_regex"
|
||||||
|
}, {
|
||||||
|
defaultToken: "string.regexp.charachterclass"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"function_arguments": [
|
||||||
|
{
|
||||||
|
token: "variable.parameter",
|
||||||
|
regex: identifierRe
|
||||||
|
}, {
|
||||||
|
token: "punctuation.operator",
|
||||||
|
regex: "[, ]+"
|
||||||
|
}, {
|
||||||
|
token: "punctuation.operator",
|
||||||
|
regex: "$"
|
||||||
|
}, {
|
||||||
|
token: "empty",
|
||||||
|
regex: "",
|
||||||
|
next: "no_regex"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"comment_regex_allowed" : [
|
||||||
|
DocCommentHighlightRules.getTagRule(),
|
||||||
|
{token : "comment", regex : "\\*\\/", next : "start"},
|
||||||
|
{defaultToken : "comment", caseInsensitive: true}
|
||||||
|
],
|
||||||
|
"comment" : [
|
||||||
|
DocCommentHighlightRules.getTagRule(),
|
||||||
|
{token : "comment", regex : "\\*\\/", next : "no_regex"},
|
||||||
|
{defaultToken : "comment", caseInsensitive: true}
|
||||||
|
],
|
||||||
|
"line_comment_regex_allowed" : [
|
||||||
|
DocCommentHighlightRules.getTagRule(),
|
||||||
|
{token : "comment", regex : "$|^", next : "start"},
|
||||||
|
{defaultToken : "comment", caseInsensitive: true}
|
||||||
|
],
|
||||||
|
"line_comment" : [
|
||||||
|
DocCommentHighlightRules.getTagRule(),
|
||||||
|
{token : "comment", regex : "$|^", next : "no_regex"},
|
||||||
|
{defaultToken : "comment", caseInsensitive: true}
|
||||||
|
],
|
||||||
|
"qqstring" : [
|
||||||
|
{
|
||||||
|
token : "constant.language.escape",
|
||||||
|
regex : escapedRe
|
||||||
|
}, {
|
||||||
|
token : "string",
|
||||||
|
regex : "\\\\$",
|
||||||
|
next : "qqstring"
|
||||||
|
}, {
|
||||||
|
token : "string",
|
||||||
|
regex : '"|$',
|
||||||
|
next : "no_regex"
|
||||||
|
}, {
|
||||||
|
defaultToken: "string"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"qstring" : [
|
||||||
|
{
|
||||||
|
token : "constant.language.escape",
|
||||||
|
regex : escapedRe
|
||||||
|
}, {
|
||||||
|
token : "string",
|
||||||
|
regex : "\\\\$",
|
||||||
|
next : "qstring"
|
||||||
|
}, {
|
||||||
|
token : "string",
|
||||||
|
regex : "'|$",
|
||||||
|
next : "no_regex"
|
||||||
|
}, {
|
||||||
|
defaultToken: "string"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
if (!options || !options.noES6) {
|
||||||
|
this.$rules.no_regex.unshift({
|
||||||
|
regex: "[{}]", onMatch: function(val, state, stack) {
|
||||||
|
this.next = val == "{" ? this.nextState : "";
|
||||||
|
if (val == "{" && stack.length) {
|
||||||
|
stack.unshift("start", state);
|
||||||
|
return "paren";
|
||||||
|
}
|
||||||
|
if (val == "}" && stack.length) {
|
||||||
|
stack.shift();
|
||||||
|
this.next = stack.shift();
|
||||||
|
if (this.next.indexOf("string") != -1)
|
||||||
|
return "paren.quasi.end";
|
||||||
|
}
|
||||||
|
return val == "{" ? "paren.lparen" : "paren.rparen";
|
||||||
|
},
|
||||||
|
nextState: "start"
|
||||||
|
}, {
|
||||||
|
token : "string.quasi.start",
|
||||||
|
regex : /`/,
|
||||||
|
push : [{
|
||||||
|
token : "constant.language.escape",
|
||||||
|
regex : escapedRe
|
||||||
|
}, {
|
||||||
|
token : "paren.quasi.start",
|
||||||
|
regex : /\${/,
|
||||||
|
push : "start"
|
||||||
|
}, {
|
||||||
|
token : "string.quasi.end",
|
||||||
|
regex : /`/,
|
||||||
|
next : "pop"
|
||||||
|
}, {
|
||||||
|
defaultToken: "string.quasi"
|
||||||
|
}]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
this.embedRules(DocCommentHighlightRules, "doc-",
|
||||||
|
[ DocCommentHighlightRules.getEndRule("no_regex") ]);
|
||||||
|
|
||||||
|
this.normalizeRules();
|
||||||
|
};
|
||||||
|
|
||||||
|
oop.inherits(JavaScriptHighlightRules, TextHighlightRules);
|
||||||
|
|
||||||
|
exports.JavaScriptHighlightRules = JavaScriptHighlightRules;
|
||||||
|
});
|
||||||
|
|
||||||
|
ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
var Range = acequire("../range").Range;
|
||||||
|
|
||||||
|
var MatchingBraceOutdent = function() {};
|
||||||
|
|
||||||
|
(function() {
|
||||||
|
|
||||||
|
this.checkOutdent = function(line, input) {
|
||||||
|
if (! /^\s+$/.test(line))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return /^\s*\}/.test(input);
|
||||||
|
};
|
||||||
|
|
||||||
|
this.autoOutdent = function(doc, row) {
|
||||||
|
var line = doc.getLine(row);
|
||||||
|
var match = line.match(/^(\s*\})/);
|
||||||
|
|
||||||
|
if (!match) return 0;
|
||||||
|
|
||||||
|
var column = match[1].length;
|
||||||
|
var openBracePos = doc.findMatchingBracket({row: row, column: column});
|
||||||
|
|
||||||
|
if (!openBracePos || openBracePos.row == row) return 0;
|
||||||
|
|
||||||
|
var indent = this.$getIndent(doc.getLine(openBracePos.row));
|
||||||
|
doc.replace(new Range(row, 0, row, column-1), indent);
|
||||||
|
};
|
||||||
|
|
||||||
|
this.$getIndent = function(line) {
|
||||||
|
return line.match(/^\s*/)[0];
|
||||||
|
};
|
||||||
|
|
||||||
|
}).call(MatchingBraceOutdent.prototype);
|
||||||
|
|
||||||
|
exports.MatchingBraceOutdent = MatchingBraceOutdent;
|
||||||
|
});
|
||||||
|
|
||||||
|
ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(acequire, exports, module) {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
var oop = acequire("../../lib/oop");
|
||||||
|
var Behaviour = acequire("../behaviour").Behaviour;
|
||||||
|
var TokenIterator = acequire("../../token_iterator").TokenIterator;
|
||||||
|
var lang = acequire("../../lib/lang");
|
||||||
|
|
||||||
|
var SAFE_INSERT_IN_TOKENS =
|
||||||
|
["text", "paren.rparen", "punctuation.operator"];
|
||||||
|
var SAFE_INSERT_BEFORE_TOKENS =
|
||||||
|
["text", "paren.rparen", "punctuation.operator", "comment"];
|
||||||
|
|
||||||
|
var context;
|
||||||
|
var contextCache = {};
|
||||||
|
var initContext = function(editor) {
|
||||||
|
var id = -1;
|
||||||
|
if (editor.multiSelect) {
|
||||||
|
id = editor.selection.index;
|
||||||
|
if (contextCache.rangeCount != editor.multiSelect.rangeCount)
|
||||||
|
contextCache = {rangeCount: editor.multiSelect.rangeCount};
|
||||||
|
}
|
||||||
|
if (contextCache[id])
|
||||||
|
return context = contextCache[id];
|
||||||
|
context = contextCache[id] = {
|
||||||
|
autoInsertedBrackets: 0,
|
||||||
|
autoInsertedRow: -1,
|
||||||
|
autoInsertedLineEnd: "",
|
||||||
|
maybeInsertedBrackets: 0,
|
||||||
|
maybeInsertedRow: -1,
|
||||||
|
maybeInsertedLineStart: "",
|
||||||
|
maybeInsertedLineEnd: ""
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
var CstyleBehaviour = function() {
|
||||||
|
this.add("braces", "insertion", function(state, action, editor, session, text) {
|
||||||
|
var cursor = editor.getCursorPosition();
|
||||||
|
var line = session.doc.getLine(cursor.row);
|
||||||
|
if (text == '{') {
|
||||||
|
initContext(editor);
|
||||||
|
var selection = editor.getSelectionRange();
|
||||||
|
var selected = session.doc.getTextRange(selection);
|
||||||
|
if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
|
||||||
|
return {
|
||||||
|
text: '{' + selected + '}',
|
||||||
|
selection: false
|
||||||
|
};
|
||||||
|
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
|
||||||
|
if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) {
|
||||||
|
CstyleBehaviour.recordAutoInsert(editor, session, "}");
|
||||||
|
return {
|
||||||
|
text: '{}',
|
||||||
|
selection: [1, 1]
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
CstyleBehaviour.recordMaybeInsert(editor, session, "{");
|
||||||
|
return {
|
||||||
|
text: '{',
|
||||||
|
selection: [1, 1]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (text == '}') {
|
||||||
|
initContext(editor);
|
||||||
|
var rightChar = line.substring(cursor.column, cursor.column + 1);
|
||||||
|
if (rightChar == '}') {
|
||||||
|
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
|
||||||
|
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
|
||||||
|
CstyleBehaviour.popAutoInsertedClosing();
|
||||||
|
return {
|
||||||
|
text: '',
|
||||||
|
selection: [1, 1]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (text == "\n" || text == "\r\n") {
|
||||||
|
initContext(editor);
|
||||||
|
var closing = "";
|
||||||
|
if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
|
||||||
|
closing = lang.stringRepeat("}", context.maybeInsertedBrackets);
|
||||||
|
CstyleBehaviour.clearMaybeInsertedClosing();
|
||||||
|
}
|
||||||
|
var rightChar = line.substring(cursor.column, cursor.column + 1);
|
||||||
|
if (rightChar === '}') {
|
||||||
|
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}');
|
||||||
|
if (!openBracePos)
|
||||||
|
return null;
|
||||||
|
var next_indent = this.$getIndent(session.getLine(openBracePos.row));
|
||||||
|
} else if (closing) {
|
||||||
|
var next_indent = this.$getIndent(line);
|
||||||
|
} else {
|
||||||
|
CstyleBehaviour.clearMaybeInsertedClosing();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var indent = next_indent + session.getTabString();
|
||||||
|
|
||||||
|
return {
|
||||||
|
text: '\n' + indent + '\n' + next_indent + closing,
|
||||||
|
selection: [1, indent.length, 1, indent.length]
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
CstyleBehaviour.clearMaybeInsertedClosing();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.add("braces", "deletion", function(state, action, editor, session, range) {
|
||||||
|
var selected = session.doc.getTextRange(range);
|
||||||
|
if (!range.isMultiLine() && selected == '{') {
|
||||||
|
initContext(editor);
|
||||||
|
var line = session.doc.getLine(range.start.row);
|
||||||
|
var rightChar = line.substring(range.end.column, range.end.column + 1);
|
||||||
|
if (rightChar == '}') {
|
||||||
|
range.end.column++;
|
||||||
|
return range;
|
||||||
|
} else {
|
||||||
|
context.maybeInsertedBrackets--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.add("parens", "insertion", function(state, action, editor, session, text) {
|
||||||
|
if (text == '(') {
|
||||||
|
initContext(editor);
|
||||||
|
var selection = editor.getSelectionRange();
|
||||||
|
var selected = session.doc.getTextRange(selection);
|
||||||
|
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
|
||||||
|
return {
|
||||||
|
text: '(' + selected + ')',
|
||||||
|
selection: false
|
||||||
|
};
|
||||||
|
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
|
||||||
|
CstyleBehaviour.recordAutoInsert(editor, session, ")");
|
||||||
|
return {
|
||||||
|
text: '()',
|
||||||
|
selection: [1, 1]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} else if (text == ')') {
|
||||||
|
initContext(editor);
|
||||||
|
var cursor = editor.getCursorPosition();
|
||||||
|
var line = session.doc.getLine(cursor.row);
|
||||||
|
var rightChar = line.substring(cursor.column, cursor.column + 1);
|
||||||
|
if (rightChar == ')') {
|
||||||
|
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
|
||||||
|
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
|
||||||
|
CstyleBehaviour.popAutoInsertedClosing();
|
||||||
|
return {
|
||||||
|
text: '',
|
||||||
|
selection: [1, 1]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.add("parens", "deletion", function(state, action, editor, session, range) {
|
||||||
|
var selected = session.doc.getTextRange(range);
|
||||||
|
if (!range.isMultiLine() && selected == '(') {
|
||||||
|
initContext(editor);
|
||||||
|
var line = session.doc.getLine(range.start.row);
|
||||||
|
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
|
||||||
|
if (rightChar == ')') {
|
||||||
|
range.end.column++;
|
||||||
|
return range;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.add("brackets", "insertion", function(state, action, editor, session, text) {
|
||||||
|
if (text == '[') {
|
||||||
|
initContext(editor);
|
||||||
|
var selection = editor.getSelectionRange();
|
||||||
|
var selected = session.doc.getTextRange(selection);
|
||||||
|
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
|
||||||
|
return {
|
||||||
|
text: '[' + selected + ']',
|
||||||
|
selection: false
|
||||||
|
};
|
||||||
|
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
|
||||||
|
CstyleBehaviour.recordAutoInsert(editor, session, "]");
|
||||||
|
return {
|
||||||
|
text: '[]',
|
||||||
|
selection: [1, 1]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} else if (text == ']') {
|
||||||
|
initContext(editor);
|
||||||
|
var cursor = editor.getCursorPosition();
|
||||||
|
var line = session.doc.getLine(cursor.row);
|
||||||
|
var rightChar = line.substring(cursor.column, cursor.column + 1);
|
||||||
|
if (rightChar == ']') {
|
||||||
|
var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
|
||||||
|
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
|
||||||
|
CstyleBehaviour.popAutoInsertedClosing();
|
||||||
|
return {
|
||||||
|
text: '',
|
||||||
|
selection: [1, 1]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.add("brackets", "deletion", function(state, action, editor, session, range) {
|
||||||
|
var selected = session.doc.getTextRange(range);
|
||||||
|
if (!range.isMultiLine() && selected == '[') {
|
||||||
|
initContext(editor);
|
||||||
|
var line = session.doc.getLine(range.start.row);
|
||||||
|
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
|
||||||
|
if (rightChar == ']') {
|
||||||
|
range.end.column++;
|
||||||
|
return range;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.add("string_dquotes", "insertion", function(state, action, editor, session, text) {
|
||||||
|
if (text == '"' || text == "'") {
|
||||||
|
initContext(editor);
|
||||||
|
var quote = text;
|
||||||
|
var selection = editor.getSelectionRange();
|
||||||
|
var selected = session.doc.getTextRange(selection);
|
||||||
|
if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
|
||||||
|
return {
|
||||||
|
text: quote + selected + quote,
|
||||||
|
selection: false
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
var cursor = editor.getCursorPosition();
|
||||||
|
var line = session.doc.getLine(cursor.row);
|
||||||
|
var leftChar = line.substring(cursor.column-1, cursor.column);
|
||||||
|
if (leftChar == '\\') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
var tokens = session.getTokens(selection.start.row);
|
||||||
|
var col = 0, token;
|
||||||
|
var quotepos = -1; // Track whether we're inside an open quote.
|
||||||
|
|
||||||
|
for (var x = 0; x < tokens.length; x++) {
|
||||||
|
token = tokens[x];
|
||||||
|
if (token.type == "string") {
|
||||||
|
quotepos = -1;
|
||||||
|
} else if (quotepos < 0) {
|
||||||
|
quotepos = token.value.indexOf(quote);
|
||||||
|
}
|
||||||
|
if ((token.value.length + col) > selection.start.column) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
col += tokens[x].value.length;
|
||||||
|
}
|
||||||
|
if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) {
|
||||||
|
if (!CstyleBehaviour.isSaneInsertion(editor, session))
|
||||||
|
return;
|
||||||
|
return {
|
||||||
|
text: quote + quote,
|
||||||
|
selection: [1,1]
|
||||||
|
};
|
||||||
|
} else if (token && token.type === "string") {
|
||||||
|
var rightChar = line.substring(cursor.column, cursor.column + 1);
|
||||||
|
if (rightChar == quote) {
|
||||||
|
return {
|
||||||
|
text: '',
|
||||||
|
selection: [1, 1]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.add("string_dquotes", "deletion", function(state, action, editor, session, range) {
|
||||||
|
var selected = session.doc.getTextRange(range);
|
||||||
|
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
|
||||||
|
initContext(editor);
|
||||||
|
var line = session.doc.getLine(range.start.row);
|
||||||
|
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
|
||||||
|
if (rightChar == selected) {
|
||||||
|
range.end.column++;
|
||||||
|
return range;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
CstyleBehaviour.isSaneInsertion = function(editor, session) {
|
||||||
|
var cursor = editor.getCursorPosition();
|
||||||
|
var iterator = new TokenIterator(session, cursor.row, cursor.column);
|
||||||
|
if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
|
||||||
|
var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
|
||||||
|
if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
iterator.stepForward();
|
||||||
|
return iterator.getCurrentTokenRow() !== cursor.row ||
|
||||||
|
this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
|
||||||
|
};
|
||||||
|
|
||||||
|
CstyleBehaviour.$matchTokenType = function(token, types) {
|
||||||
|
return types.indexOf(token.type || token) > -1;
|
||||||
|
};
|
||||||
|
|
||||||
|
CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) {
|
||||||
|
var cursor = editor.getCursorPosition();
|
||||||
|
var line = session.doc.getLine(cursor.row);
|
||||||
|
if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0]))
|
||||||
|
context.autoInsertedBrackets = 0;
|
||||||
|
context.autoInsertedRow = cursor.row;
|
||||||
|
context.autoInsertedLineEnd = bracket + line.substr(cursor.column);
|
||||||
|
context.autoInsertedBrackets++;
|
||||||
|
};
|
||||||
|
|
||||||
|
CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) {
|
||||||
|
var cursor = editor.getCursorPosition();
|
||||||
|
var line = session.doc.getLine(cursor.row);
|
||||||
|
if (!this.isMaybeInsertedClosing(cursor, line))
|
||||||
|
context.maybeInsertedBrackets = 0;
|
||||||
|
context.maybeInsertedRow = cursor.row;
|
||||||
|
context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
|
||||||
|
context.maybeInsertedLineEnd = line.substr(cursor.column);
|
||||||
|
context.maybeInsertedBrackets++;
|
||||||
|
};
|
||||||
|
|
||||||
|
CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) {
|
||||||
|
return context.autoInsertedBrackets > 0 &&
|
||||||
|
cursor.row === context.autoInsertedRow &&
|
||||||
|
bracket === context.autoInsertedLineEnd[0] &&
|
||||||
|
line.substr(cursor.column) === context.autoInsertedLineEnd;
|
||||||
|
};
|
||||||
|
|
||||||
|
CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) {
|
||||||
|
return context.maybeInsertedBrackets > 0 &&
|
||||||
|
cursor.row === context.maybeInsertedRow &&
|
||||||
|
line.substr(cursor.column) === context.maybeInsertedLineEnd &&
|
||||||
|
line.substr(0, cursor.column) == context.maybeInsertedLineStart;
|
||||||
|
};
|
||||||
|
|
||||||
|
CstyleBehaviour.popAutoInsertedClosing = function() {
|
||||||
|
context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1);
|
||||||
|
context.autoInsertedBrackets--;
|
||||||
|
};
|
||||||
|
|
||||||
|
CstyleBehaviour.clearMaybeInsertedClosing = function() {
|
||||||
|
if (context) {
|
||||||
|
context.maybeInsertedBrackets = 0;
|
||||||
|
context.maybeInsertedRow = -1;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
oop.inherits(CstyleBehaviour, Behaviour);
|
||||||
|
|
||||||
|
exports.CstyleBehaviour = CstyleBehaviour;
|
||||||
|
});
|
||||||
|
|
||||||
|
ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
var oop = acequire("../../lib/oop");
|
||||||
|
var Range = acequire("../../range").Range;
|
||||||
|
var BaseFoldMode = acequire("./fold_mode").FoldMode;
|
||||||
|
|
||||||
|
var FoldMode = exports.FoldMode = function(commentRegex) {
|
||||||
|
if (commentRegex) {
|
||||||
|
this.foldingStartMarker = new RegExp(
|
||||||
|
this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
|
||||||
|
);
|
||||||
|
this.foldingStopMarker = new RegExp(
|
||||||
|
this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
oop.inherits(FoldMode, BaseFoldMode);
|
||||||
|
|
||||||
|
(function() {
|
||||||
|
|
||||||
|
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
|
||||||
|
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
|
||||||
|
|
||||||
|
this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
|
||||||
|
var line = session.getLine(row);
|
||||||
|
var match = line.match(this.foldingStartMarker);
|
||||||
|
if (match) {
|
||||||
|
var i = match.index;
|
||||||
|
|
||||||
|
if (match[1])
|
||||||
|
return this.openingBracketBlock(session, match[1], row, i);
|
||||||
|
|
||||||
|
var range = session.getCommentFoldRange(row, i + match[0].length, 1);
|
||||||
|
|
||||||
|
if (range && !range.isMultiLine()) {
|
||||||
|
if (forceMultiline) {
|
||||||
|
range = this.getSectionRange(session, row);
|
||||||
|
} else if (foldStyle != "all")
|
||||||
|
range = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return range;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (foldStyle === "markbegin")
|
||||||
|
return;
|
||||||
|
|
||||||
|
var match = line.match(this.foldingStopMarker);
|
||||||
|
if (match) {
|
||||||
|
var i = match.index + match[0].length;
|
||||||
|
|
||||||
|
if (match[1])
|
||||||
|
return this.closingBracketBlock(session, match[1], row, i);
|
||||||
|
|
||||||
|
return session.getCommentFoldRange(row, i, -1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
this.getSectionRange = function(session, row) {
|
||||||
|
var line = session.getLine(row);
|
||||||
|
var startIndent = line.search(/\S/);
|
||||||
|
var startRow = row;
|
||||||
|
var startColumn = line.length;
|
||||||
|
row = row + 1;
|
||||||
|
var endRow = row;
|
||||||
|
var maxRow = session.getLength();
|
||||||
|
while (++row < maxRow) {
|
||||||
|
line = session.getLine(row);
|
||||||
|
var indent = line.search(/\S/);
|
||||||
|
if (indent === -1)
|
||||||
|
continue;
|
||||||
|
if (startIndent > indent)
|
||||||
|
break;
|
||||||
|
var subRange = this.getFoldWidgetRange(session, "all", row);
|
||||||
|
|
||||||
|
if (subRange) {
|
||||||
|
if (subRange.start.row <= startRow) {
|
||||||
|
break;
|
||||||
|
} else if (subRange.isMultiLine()) {
|
||||||
|
row = subRange.end.row;
|
||||||
|
} else if (startIndent == indent) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
endRow = row;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
|
||||||
|
};
|
||||||
|
|
||||||
|
}).call(FoldMode.prototype);
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(acequire, exports, module) {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
var oop = acequire("../lib/oop");
|
||||||
|
var TextMode = acequire("./text").Mode;
|
||||||
|
var JavaScriptHighlightRules = acequire("./javascript_highlight_rules").JavaScriptHighlightRules;
|
||||||
|
var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent;
|
||||||
|
var Range = acequire("../range").Range;
|
||||||
|
var WorkerClient = acequire("../worker/worker_client").WorkerClient;
|
||||||
|
var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour;
|
||||||
|
var CStyleFoldMode = acequire("./folding/cstyle").FoldMode;
|
||||||
|
|
||||||
|
var Mode = function() {
|
||||||
|
this.HighlightRules = JavaScriptHighlightRules;
|
||||||
|
|
||||||
|
this.$outdent = new MatchingBraceOutdent();
|
||||||
|
this.$behaviour = new CstyleBehaviour();
|
||||||
|
this.foldingRules = new CStyleFoldMode();
|
||||||
|
};
|
||||||
|
oop.inherits(Mode, TextMode);
|
||||||
|
|
||||||
|
(function() {
|
||||||
|
|
||||||
|
this.lineCommentStart = "//";
|
||||||
|
this.blockComment = {start: "/*", end: "*/"};
|
||||||
|
|
||||||
|
this.getNextLineIndent = function(state, line, tab) {
|
||||||
|
var indent = this.$getIndent(line);
|
||||||
|
|
||||||
|
var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
|
||||||
|
var tokens = tokenizedLine.tokens;
|
||||||
|
var endState = tokenizedLine.state;
|
||||||
|
|
||||||
|
if (tokens.length && tokens[tokens.length-1].type == "comment") {
|
||||||
|
return indent;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state == "start" || state == "no_regex") {
|
||||||
|
var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);
|
||||||
|
if (match) {
|
||||||
|
indent += tab;
|
||||||
|
}
|
||||||
|
} else if (state == "doc-start") {
|
||||||
|
if (endState == "start" || endState == "no_regex") {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
var match = line.match(/^\s*(\/?)\*/);
|
||||||
|
if (match) {
|
||||||
|
if (match[1]) {
|
||||||
|
indent += " ";
|
||||||
|
}
|
||||||
|
indent += "* ";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return indent;
|
||||||
|
};
|
||||||
|
|
||||||
|
this.checkOutdent = function(state, line, input) {
|
||||||
|
return this.$outdent.checkOutdent(line, input);
|
||||||
|
};
|
||||||
|
|
||||||
|
this.autoOutdent = function(state, doc, row) {
|
||||||
|
this.$outdent.autoOutdent(doc, row);
|
||||||
|
};
|
||||||
|
|
||||||
|
// this.createWorker = function(session) {
|
||||||
|
// var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker");
|
||||||
|
// worker.attachToDocument(session.getDocument());
|
||||||
|
//
|
||||||
|
// worker.on("jslint", function(results) {
|
||||||
|
// session.setAnnotations(results.data);
|
||||||
|
// });
|
||||||
|
//
|
||||||
|
// worker.on("terminate", function() {
|
||||||
|
// session.clearAnnotations();
|
||||||
|
// });
|
||||||
|
//
|
||||||
|
// return worker;
|
||||||
|
// };
|
||||||
|
|
||||||
|
this.$id = "ace/mode/javascript";
|
||||||
|
}).call(Mode.prototype);
|
||||||
|
|
||||||
|
exports.Mode = Mode;
|
||||||
|
});
|
@ -16,6 +16,7 @@
|
|||||||
|
|
||||||
import Actionbar from './Actionbar';
|
import Actionbar from './Actionbar';
|
||||||
import ActionbarExport from './Actionbar/Export';
|
import ActionbarExport from './Actionbar/Export';
|
||||||
|
import ActionbarImport from './Actionbar/Import';
|
||||||
import ActionbarSearch from './Actionbar/Search';
|
import ActionbarSearch from './Actionbar/Search';
|
||||||
import ActionbarSort from './Actionbar/Sort';
|
import ActionbarSort from './Actionbar/Sort';
|
||||||
import Badge from './Badge';
|
import Badge from './Badge';
|
||||||
@ -26,6 +27,7 @@ import ConfirmDialog from './ConfirmDialog';
|
|||||||
import Container, { Title as ContainerTitle } from './Container';
|
import Container, { Title as ContainerTitle } from './Container';
|
||||||
import ContextProvider from './ContextProvider';
|
import ContextProvider from './ContextProvider';
|
||||||
import CopyToClipboard from './CopyToClipboard';
|
import CopyToClipboard from './CopyToClipboard';
|
||||||
|
import Editor from './Editor';
|
||||||
import Errors from './Errors';
|
import Errors from './Errors';
|
||||||
import Form, { AddressSelect, FormWrap, Input, InputAddress, InputAddressSelect, InputChip, InputInline, Select } from './Form';
|
import Form, { AddressSelect, FormWrap, Input, InputAddress, InputAddressSelect, InputChip, InputInline, Select } from './Form';
|
||||||
import IdentityIcon from './IdentityIcon';
|
import IdentityIcon from './IdentityIcon';
|
||||||
@ -43,6 +45,7 @@ import TxHash from './TxHash';
|
|||||||
export {
|
export {
|
||||||
Actionbar,
|
Actionbar,
|
||||||
ActionbarExport,
|
ActionbarExport,
|
||||||
|
ActionbarImport,
|
||||||
ActionbarSearch,
|
ActionbarSearch,
|
||||||
ActionbarSort,
|
ActionbarSort,
|
||||||
AddressSelect,
|
AddressSelect,
|
||||||
@ -55,6 +58,7 @@ export {
|
|||||||
ContainerTitle,
|
ContainerTitle,
|
||||||
ContextProvider,
|
ContextProvider,
|
||||||
CopyToClipboard,
|
CopyToClipboard,
|
||||||
|
Editor,
|
||||||
Errors,
|
Errors,
|
||||||
Form,
|
Form,
|
||||||
FormWrap,
|
FormWrap,
|
||||||
|
@ -38,10 +38,22 @@ export function validateAbi (abi, api) {
|
|||||||
abiParsed = JSON.parse(abi);
|
abiParsed = JSON.parse(abi);
|
||||||
|
|
||||||
if (!api.util.isArray(abiParsed) || !abiParsed.length) {
|
if (!api.util.isArray(abiParsed) || !abiParsed.length) {
|
||||||
abiError = ERRORS.inavlidAbi;
|
abiError = ERRORS.invalidAbi;
|
||||||
} else {
|
return { abi, abiError, abiParsed };
|
||||||
abi = JSON.stringify(abiParsed);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate each elements of the Array
|
||||||
|
const invalidIndex = abiParsed
|
||||||
|
.map((o) => isValidAbiEvent(o, api) || isValidAbiFunction(o, api))
|
||||||
|
.findIndex((valid) => !valid);
|
||||||
|
|
||||||
|
if (invalidIndex !== -1) {
|
||||||
|
const invalid = abiParsed[invalidIndex];
|
||||||
|
abiError = `${ERRORS.invalidAbi} (#${invalidIndex}: ${invalid.name || invalid.type})`;
|
||||||
|
return { abi, abiError, abiParsed };
|
||||||
|
}
|
||||||
|
|
||||||
|
abi = JSON.stringify(abiParsed);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
abiError = ERRORS.invalidAbi;
|
abiError = ERRORS.invalidAbi;
|
||||||
}
|
}
|
||||||
@ -53,6 +65,25 @@ export function validateAbi (abi, api) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isValidAbiFunction (object, api) {
|
||||||
|
if (!object) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ((object.type === 'function' && object.name) || object.type === 'constructor') &&
|
||||||
|
(object.inputs && api.util.isArray(object.inputs));
|
||||||
|
}
|
||||||
|
|
||||||
|
function isValidAbiEvent (object, api) {
|
||||||
|
if (!object) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (object.type === 'event') &&
|
||||||
|
(object.name) &&
|
||||||
|
(object.inputs && api.util.isArray(object.inputs));
|
||||||
|
}
|
||||||
|
|
||||||
export function validateAddress (address) {
|
export function validateAddress (address) {
|
||||||
let addressError = null;
|
let addressError = null;
|
||||||
|
|
||||||
|
82
js/src/util/wallet.js
Normal file
82
js/src/util/wallet.js
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
// Copyright 2015, 2016 Ethcore (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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import scrypt from 'scryptsy';
|
||||||
|
import Transaction from 'ethereumjs-tx';
|
||||||
|
import { pbkdf2Sync } from 'crypto';
|
||||||
|
import { createDecipheriv } from 'browserify-aes';
|
||||||
|
|
||||||
|
import { inHex } from '../api/format/input';
|
||||||
|
import { sha3 } from '../api/util/sha3';
|
||||||
|
|
||||||
|
// Adapted from https://github.com/kvhnuke/etherwallet/blob/mercury/app/scripts/myetherwallet.js
|
||||||
|
|
||||||
|
export class Wallet {
|
||||||
|
|
||||||
|
static fromJson (json, password) {
|
||||||
|
if (json.version !== 3) {
|
||||||
|
throw new Error('Only V3 wallets are supported');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { kdf } = json.crypto;
|
||||||
|
const kdfparams = json.crypto.kdfparams || {};
|
||||||
|
const pwd = Buffer.from(password);
|
||||||
|
const salt = Buffer.from(kdfparams.salt, 'hex');
|
||||||
|
let derivedKey;
|
||||||
|
|
||||||
|
if (kdf === 'scrypt') {
|
||||||
|
derivedKey = scrypt(pwd, salt, kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen);
|
||||||
|
} else if (kdf === 'pbkdf2') {
|
||||||
|
if (kdfparams.prf !== 'hmac-sha256') {
|
||||||
|
throw new Error('Unsupported parameters to PBKDF2');
|
||||||
|
}
|
||||||
|
derivedKey = pbkdf2Sync(pwd, salt, kdfparams.c, kdfparams.dklen, 'sha256');
|
||||||
|
} else {
|
||||||
|
throw new Error('Unsupported key derivation scheme');
|
||||||
|
}
|
||||||
|
|
||||||
|
const ciphertext = Buffer.from(json.crypto.ciphertext, 'hex');
|
||||||
|
let mac = sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext]));
|
||||||
|
if (mac !== inHex(json.crypto.mac)) {
|
||||||
|
throw new Error('Key derivation failed - possibly wrong passphrase');
|
||||||
|
}
|
||||||
|
|
||||||
|
const decipher = createDecipheriv(
|
||||||
|
json.crypto.cipher,
|
||||||
|
derivedKey.slice(0, 16),
|
||||||
|
Buffer.from(json.crypto.cipherparams.iv, 'hex')
|
||||||
|
);
|
||||||
|
let seed = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
||||||
|
|
||||||
|
while (seed.length < 32) {
|
||||||
|
const nullBuff = Buffer.from([0x00]);
|
||||||
|
seed = Buffer.concat([nullBuff, seed]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Wallet(seed);
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor (seed) {
|
||||||
|
this.seed = seed;
|
||||||
|
}
|
||||||
|
|
||||||
|
signTransaction (transaction) {
|
||||||
|
const tx = new Transaction(transaction);
|
||||||
|
tx.sign(this.seed);
|
||||||
|
return inHex(tx.serialize().toString('hex'));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -48,9 +48,7 @@ class Transactions extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
componentDidMount () {
|
componentDidMount () {
|
||||||
if (this.props.traceMode !== undefined) {
|
this.getTransactions(this.props);
|
||||||
this.getTransactions(this.props);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
componentWillReceiveProps (newProps) {
|
componentWillReceiveProps (newProps) {
|
||||||
|
@ -145,6 +145,8 @@ export default class List extends Component {
|
|||||||
return tagsA.localeCompare(tagsB);
|
return tagsA.localeCompare(tagsB);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const reverse = key === 'timestamp' ? -1 : 1;
|
||||||
|
|
||||||
const metaA = accountA.meta[key];
|
const metaA = accountA.meta[key];
|
||||||
const metaB = accountB.meta[key];
|
const metaB = accountB.meta[key];
|
||||||
|
|
||||||
@ -152,14 +154,22 @@ export default class List extends Component {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((metaA && !metaB) || (metaA < metaB)) {
|
if (metaA && !metaB) {
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((!metaA && metaB) || (metaA > metaB)) {
|
if (metaA < metaB) {
|
||||||
|
return -1 * reverse;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!metaA && metaB) {
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (metaA > metaB) {
|
||||||
|
return 1 * reverse;
|
||||||
|
}
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user