Merge branch 'master' into check-updates
This commit is contained in:
commit
e170134d97
2
Cargo.lock
generated
2
Cargo.lock
generated
@ -1306,7 +1306,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#2397280818ec4e4502b379f788f2eecdbc63abb4"
|
source = "git+https://github.com/ethcore/js-precompiled.git#eb9d978ed5ad1c514b37e89c716f80b3c8d613b5"
|
||||||
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)",
|
||||||
]
|
]
|
||||||
|
@ -16,13 +16,13 @@
|
|||||||
|
|
||||||
//! I/O and event context generalizations.
|
//! I/O and event context generalizations.
|
||||||
|
|
||||||
use network::{NetworkContext, PeerId};
|
use network::{NetworkContext, PeerId, NodeId};
|
||||||
|
|
||||||
use super::{Announcement, LightProtocol, ReqId};
|
use super::{Announcement, LightProtocol, ReqId};
|
||||||
use super::error::Error;
|
use super::error::Error;
|
||||||
use request::Request;
|
use request::Request;
|
||||||
|
|
||||||
/// An I/O context which allows sending and receiving packets as well as
|
/// An I/O context which allows sending and receiving packets as well as
|
||||||
/// disconnecting peers. This is used as a generalization of the portions
|
/// disconnecting peers. This is used as a generalization of the portions
|
||||||
/// of a p2p network which the light protocol structure makes use of.
|
/// of a p2p network which the light protocol structure makes use of.
|
||||||
pub trait IoContext {
|
pub trait IoContext {
|
||||||
@ -41,8 +41,12 @@ pub trait IoContext {
|
|||||||
|
|
||||||
/// Get a peer's protocol version.
|
/// Get a peer's protocol version.
|
||||||
fn protocol_version(&self, peer: PeerId) -> Option<u8>;
|
fn protocol_version(&self, peer: PeerId) -> Option<u8>;
|
||||||
|
|
||||||
|
/// Persistent peer id
|
||||||
|
fn persistent_peer_id(&self, peer: PeerId) -> Option<NodeId>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
impl<'a> IoContext for NetworkContext<'a> {
|
impl<'a> IoContext for NetworkContext<'a> {
|
||||||
fn send(&self, peer: PeerId, packet_id: u8, packet_body: Vec<u8>) {
|
fn send(&self, peer: PeerId, packet_id: u8, packet_body: Vec<u8>) {
|
||||||
if let Err(e) = self.send(peer, packet_id, packet_body) {
|
if let Err(e) = self.send(peer, packet_id, packet_body) {
|
||||||
@ -67,6 +71,10 @@ impl<'a> IoContext for NetworkContext<'a> {
|
|||||||
fn protocol_version(&self, peer: PeerId) -> Option<u8> {
|
fn protocol_version(&self, peer: PeerId) -> Option<u8> {
|
||||||
self.protocol_version(self.subprotocol_name(), peer)
|
self.protocol_version(self.subprotocol_name(), peer)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn persistent_peer_id(&self, peer: PeerId) -> Option<NodeId> {
|
||||||
|
self.session_info(peer).and_then(|info| info.id)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Context for a protocol event.
|
/// Context for a protocol event.
|
||||||
@ -75,6 +83,9 @@ pub trait EventContext {
|
|||||||
/// disconnected/connected peer.
|
/// disconnected/connected peer.
|
||||||
fn peer(&self) -> PeerId;
|
fn peer(&self) -> PeerId;
|
||||||
|
|
||||||
|
/// Returns the relevant's peer persistent Id (aka NodeId).
|
||||||
|
fn persistent_peer_id(&self, peer: PeerId) -> Option<NodeId>;
|
||||||
|
|
||||||
/// Make a request from a peer.
|
/// Make a request from a peer.
|
||||||
fn request_from(&self, peer: PeerId, request: Request) -> Result<ReqId, Error>;
|
fn request_from(&self, peer: PeerId, request: Request) -> Result<ReqId, Error>;
|
||||||
|
|
||||||
@ -89,7 +100,7 @@ pub trait EventContext {
|
|||||||
fn disable_peer(&self, peer: PeerId);
|
fn disable_peer(&self, peer: PeerId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Concrete implementation of `EventContext` over the light protocol struct and
|
/// Concrete implementation of `EventContext` over the light protocol struct and
|
||||||
/// an io context.
|
/// an io context.
|
||||||
pub struct Ctx<'a> {
|
pub struct Ctx<'a> {
|
||||||
/// Io context to enable immediate response to events.
|
/// Io context to enable immediate response to events.
|
||||||
@ -97,11 +108,18 @@ pub struct Ctx<'a> {
|
|||||||
/// Protocol implementation.
|
/// Protocol implementation.
|
||||||
pub proto: &'a LightProtocol,
|
pub proto: &'a LightProtocol,
|
||||||
/// Relevant peer for event.
|
/// Relevant peer for event.
|
||||||
pub peer: PeerId,
|
pub peer: PeerId,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> EventContext for Ctx<'a> {
|
impl<'a> EventContext for Ctx<'a> {
|
||||||
fn peer(&self) -> PeerId { self.peer }
|
fn peer(&self) -> PeerId {
|
||||||
|
self.peer
|
||||||
|
}
|
||||||
|
|
||||||
|
fn persistent_peer_id(&self, id: PeerId) -> Option<NodeId> {
|
||||||
|
self.io.persistent_peer_id(id)
|
||||||
|
}
|
||||||
|
|
||||||
fn request_from(&self, peer: PeerId, request: Request) -> Result<ReqId, Error> {
|
fn request_from(&self, peer: PeerId, request: Request) -> Result<ReqId, Error> {
|
||||||
self.proto.request_from(self.io, &peer, request)
|
self.proto.request_from(self.io, &peer, request)
|
||||||
}
|
}
|
||||||
@ -117,4 +135,4 @@ impl<'a> EventContext for Ctx<'a> {
|
|||||||
fn disable_peer(&self, peer: PeerId) {
|
fn disable_peer(&self, peer: PeerId) {
|
||||||
self.io.disable_peer(peer);
|
self.io.disable_peer(peer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -15,13 +15,13 @@
|
|||||||
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
//! Tests for the `LightProtocol` implementation.
|
//! Tests for the `LightProtocol` implementation.
|
||||||
//! These don't test of the higher level logic on top of
|
//! These don't test of the higher level logic on top of
|
||||||
|
|
||||||
use ethcore::blockchain_info::BlockChainInfo;
|
use ethcore::blockchain_info::BlockChainInfo;
|
||||||
use ethcore::client::{BlockChainClient, EachBlockWith, TestBlockChainClient};
|
use ethcore::client::{BlockChainClient, EachBlockWith, TestBlockChainClient};
|
||||||
use ethcore::ids::BlockId;
|
use ethcore::ids::BlockId;
|
||||||
use ethcore::transaction::SignedTransaction;
|
use ethcore::transaction::SignedTransaction;
|
||||||
use network::PeerId;
|
use network::{PeerId, NodeId};
|
||||||
|
|
||||||
use net::buffer_flow::FlowParams;
|
use net::buffer_flow::FlowParams;
|
||||||
use net::context::IoContext;
|
use net::context::IoContext;
|
||||||
@ -68,6 +68,10 @@ impl IoContext for Expect {
|
|||||||
fn protocol_version(&self, _peer: PeerId) -> Option<u8> {
|
fn protocol_version(&self, _peer: PeerId) -> Option<u8> {
|
||||||
Some(super::MAX_PROTOCOL_VERSION)
|
Some(super::MAX_PROTOCOL_VERSION)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn persistent_peer_id(&self, _peer: PeerId) -> Option<NodeId> {
|
||||||
|
None
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// can't implement directly for Arc due to cross-crate orphan rules.
|
// can't implement directly for Arc due to cross-crate orphan rules.
|
||||||
@ -117,7 +121,7 @@ impl Provider for TestProvider {
|
|||||||
.map(|x: u64| x.saturating_mul(req.skip + 1))
|
.map(|x: u64| x.saturating_mul(req.skip + 1))
|
||||||
.take_while(|x| if req.reverse { x < &start_num } else { best_num - start_num >= *x })
|
.take_while(|x| if req.reverse { x < &start_num } else { best_num - start_num >= *x })
|
||||||
.map(|x| if req.reverse { start_num - x } else { start_num + x })
|
.map(|x| if req.reverse { start_num - x } else { start_num + x })
|
||||||
.map(|x| self.0.client.block_header(BlockId::Number(x)))
|
.map(|x| self.0.client.block_header(BlockId::Number(x)))
|
||||||
.take_while(|x| x.is_some())
|
.take_while(|x| x.is_some())
|
||||||
.flat_map(|x| x)
|
.flat_map(|x| x)
|
||||||
.collect()
|
.collect()
|
||||||
@ -150,12 +154,12 @@ impl Provider for TestProvider {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn contract_code(&self, req: request::ContractCodes) -> Vec<Bytes> {
|
fn contract_code(&self, req: request::ContractCodes) -> Vec<Bytes> {
|
||||||
req.code_requests.into_iter()
|
req.code_requests.into_iter()
|
||||||
.map(|req| {
|
.map(|req| {
|
||||||
req.account_key.iter().chain(req.account_key.iter()).cloned().collect()
|
req.account_key.iter().chain(req.account_key.iter()).cloned().collect()
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
@ -213,9 +217,9 @@ fn status(chain_info: BlockChainInfo) -> Status {
|
|||||||
#[test]
|
#[test]
|
||||||
fn handshake_expected() {
|
fn handshake_expected() {
|
||||||
let flow_params = make_flow_params();
|
let flow_params = make_flow_params();
|
||||||
let capabilities = capabilities();
|
let capabilities = capabilities();
|
||||||
|
|
||||||
let (provider, proto) = setup(flow_params.clone(), capabilities.clone());
|
let (provider, proto) = setup(flow_params.clone(), capabilities.clone());
|
||||||
|
|
||||||
let status = status(provider.client.chain_info());
|
let status = status(provider.client.chain_info());
|
||||||
|
|
||||||
@ -228,9 +232,9 @@ fn handshake_expected() {
|
|||||||
#[should_panic]
|
#[should_panic]
|
||||||
fn genesis_mismatch() {
|
fn genesis_mismatch() {
|
||||||
let flow_params = make_flow_params();
|
let flow_params = make_flow_params();
|
||||||
let capabilities = capabilities();
|
let capabilities = capabilities();
|
||||||
|
|
||||||
let (provider, proto) = setup(flow_params.clone(), capabilities.clone());
|
let (provider, proto) = setup(flow_params.clone(), capabilities.clone());
|
||||||
|
|
||||||
let mut status = status(provider.client.chain_info());
|
let mut status = status(provider.client.chain_info());
|
||||||
status.genesis_hash = H256::default();
|
status.genesis_hash = H256::default();
|
||||||
@ -243,15 +247,15 @@ fn genesis_mismatch() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn buffer_overflow() {
|
fn buffer_overflow() {
|
||||||
let flow_params = make_flow_params();
|
let flow_params = make_flow_params();
|
||||||
let capabilities = capabilities();
|
let capabilities = capabilities();
|
||||||
|
|
||||||
let (provider, proto) = setup(flow_params.clone(), capabilities.clone());
|
let (provider, proto) = setup(flow_params.clone(), capabilities.clone());
|
||||||
|
|
||||||
let status = status(provider.client.chain_info());
|
let status = status(provider.client.chain_info());
|
||||||
|
|
||||||
{
|
{
|
||||||
let packet_body = write_handshake(&status, &capabilities, Some(&flow_params));
|
let packet_body = write_handshake(&status, &capabilities, Some(&flow_params));
|
||||||
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body));
|
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body));
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
@ -276,9 +280,9 @@ fn buffer_overflow() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn get_block_headers() {
|
fn get_block_headers() {
|
||||||
let flow_params = FlowParams::new(5_000_000.into(), Default::default(), 0.into());
|
let flow_params = FlowParams::new(5_000_000.into(), Default::default(), 0.into());
|
||||||
let capabilities = capabilities();
|
let capabilities = capabilities();
|
||||||
|
|
||||||
let (provider, proto) = setup(flow_params.clone(), capabilities.clone());
|
let (provider, proto) = setup(flow_params.clone(), capabilities.clone());
|
||||||
|
|
||||||
let cur_status = status(provider.client.chain_info());
|
let cur_status = status(provider.client.chain_info());
|
||||||
let my_status = write_handshake(&cur_status, &capabilities, Some(&flow_params));
|
let my_status = write_handshake(&cur_status, &capabilities, Some(&flow_params));
|
||||||
@ -288,8 +292,8 @@ fn get_block_headers() {
|
|||||||
let cur_status = status(provider.client.chain_info());
|
let cur_status = status(provider.client.chain_info());
|
||||||
|
|
||||||
{
|
{
|
||||||
let packet_body = write_handshake(&cur_status, &capabilities, Some(&flow_params));
|
let packet_body = write_handshake(&cur_status, &capabilities, Some(&flow_params));
|
||||||
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body));
|
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body));
|
||||||
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &my_status);
|
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &my_status);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -309,7 +313,7 @@ fn get_block_headers() {
|
|||||||
let new_buf = *flow_params.limit() - flow_params.compute_cost(request::Kind::Headers, 10);
|
let new_buf = *flow_params.limit() - flow_params.compute_cost(request::Kind::Headers, 10);
|
||||||
|
|
||||||
let mut response_stream = RlpStream::new_list(3);
|
let mut response_stream = RlpStream::new_list(3);
|
||||||
|
|
||||||
response_stream.append(&req_id).append(&new_buf).begin_list(10);
|
response_stream.append(&req_id).append(&new_buf).begin_list(10);
|
||||||
for header in headers {
|
for header in headers {
|
||||||
response_stream.append_raw(&header, 1);
|
response_stream.append_raw(&header, 1);
|
||||||
@ -325,9 +329,9 @@ fn get_block_headers() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn get_block_bodies() {
|
fn get_block_bodies() {
|
||||||
let flow_params = FlowParams::new(5_000_000.into(), Default::default(), 0.into());
|
let flow_params = FlowParams::new(5_000_000.into(), Default::default(), 0.into());
|
||||||
let capabilities = capabilities();
|
let capabilities = capabilities();
|
||||||
|
|
||||||
let (provider, proto) = setup(flow_params.clone(), capabilities.clone());
|
let (provider, proto) = setup(flow_params.clone(), capabilities.clone());
|
||||||
|
|
||||||
let cur_status = status(provider.client.chain_info());
|
let cur_status = status(provider.client.chain_info());
|
||||||
let my_status = write_handshake(&cur_status, &capabilities, Some(&flow_params));
|
let my_status = write_handshake(&cur_status, &capabilities, Some(&flow_params));
|
||||||
@ -337,8 +341,8 @@ fn get_block_bodies() {
|
|||||||
let cur_status = status(provider.client.chain_info());
|
let cur_status = status(provider.client.chain_info());
|
||||||
|
|
||||||
{
|
{
|
||||||
let packet_body = write_handshake(&cur_status, &capabilities, Some(&flow_params));
|
let packet_body = write_handshake(&cur_status, &capabilities, Some(&flow_params));
|
||||||
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body));
|
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body));
|
||||||
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &my_status);
|
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &my_status);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -356,7 +360,7 @@ fn get_block_bodies() {
|
|||||||
let new_buf = *flow_params.limit() - flow_params.compute_cost(request::Kind::Bodies, 10);
|
let new_buf = *flow_params.limit() - flow_params.compute_cost(request::Kind::Bodies, 10);
|
||||||
|
|
||||||
let mut response_stream = RlpStream::new_list(3);
|
let mut response_stream = RlpStream::new_list(3);
|
||||||
|
|
||||||
response_stream.append(&req_id).append(&new_buf).begin_list(10);
|
response_stream.append(&req_id).append(&new_buf).begin_list(10);
|
||||||
for body in bodies {
|
for body in bodies {
|
||||||
response_stream.append_raw(&body, 1);
|
response_stream.append_raw(&body, 1);
|
||||||
@ -372,9 +376,9 @@ fn get_block_bodies() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn get_block_receipts() {
|
fn get_block_receipts() {
|
||||||
let flow_params = FlowParams::new(5_000_000.into(), Default::default(), 0.into());
|
let flow_params = FlowParams::new(5_000_000.into(), Default::default(), 0.into());
|
||||||
let capabilities = capabilities();
|
let capabilities = capabilities();
|
||||||
|
|
||||||
let (provider, proto) = setup(flow_params.clone(), capabilities.clone());
|
let (provider, proto) = setup(flow_params.clone(), capabilities.clone());
|
||||||
|
|
||||||
let cur_status = status(provider.client.chain_info());
|
let cur_status = status(provider.client.chain_info());
|
||||||
let my_status = write_handshake(&cur_status, &capabilities, Some(&flow_params));
|
let my_status = write_handshake(&cur_status, &capabilities, Some(&flow_params));
|
||||||
@ -384,8 +388,8 @@ fn get_block_receipts() {
|
|||||||
let cur_status = status(provider.client.chain_info());
|
let cur_status = status(provider.client.chain_info());
|
||||||
|
|
||||||
{
|
{
|
||||||
let packet_body = write_handshake(&cur_status, &capabilities, Some(&flow_params));
|
let packet_body = write_handshake(&cur_status, &capabilities, Some(&flow_params));
|
||||||
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body));
|
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body));
|
||||||
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &my_status);
|
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &my_status);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -409,7 +413,7 @@ fn get_block_receipts() {
|
|||||||
let new_buf = *flow_params.limit() - flow_params.compute_cost(request::Kind::Receipts, receipts.len());
|
let new_buf = *flow_params.limit() - flow_params.compute_cost(request::Kind::Receipts, receipts.len());
|
||||||
|
|
||||||
let mut response_stream = RlpStream::new_list(3);
|
let mut response_stream = RlpStream::new_list(3);
|
||||||
|
|
||||||
response_stream.append(&req_id).append(&new_buf).begin_list(receipts.len());
|
response_stream.append(&req_id).append(&new_buf).begin_list(receipts.len());
|
||||||
for block_receipts in receipts {
|
for block_receipts in receipts {
|
||||||
response_stream.append_raw(&block_receipts, 1);
|
response_stream.append_raw(&block_receipts, 1);
|
||||||
@ -425,15 +429,15 @@ fn get_block_receipts() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn get_state_proofs() {
|
fn get_state_proofs() {
|
||||||
let flow_params = FlowParams::new(5_000_000.into(), Default::default(), 0.into());
|
let flow_params = FlowParams::new(5_000_000.into(), Default::default(), 0.into());
|
||||||
let capabilities = capabilities();
|
let capabilities = capabilities();
|
||||||
|
|
||||||
let (provider, proto) = setup(flow_params.clone(), capabilities.clone());
|
let (provider, proto) = setup(flow_params.clone(), capabilities.clone());
|
||||||
|
|
||||||
let cur_status = status(provider.client.chain_info());
|
let cur_status = status(provider.client.chain_info());
|
||||||
|
|
||||||
{
|
{
|
||||||
let packet_body = write_handshake(&cur_status, &capabilities, Some(&flow_params));
|
let packet_body = write_handshake(&cur_status, &capabilities, Some(&flow_params));
|
||||||
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body.clone()));
|
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body.clone()));
|
||||||
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &packet_body);
|
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &packet_body);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -441,7 +445,7 @@ fn get_state_proofs() {
|
|||||||
let key1 = U256::from(11223344).into();
|
let key1 = U256::from(11223344).into();
|
||||||
let key2 = U256::from(99988887).into();
|
let key2 = U256::from(99988887).into();
|
||||||
|
|
||||||
let request = Request::StateProofs (request::StateProofs {
|
let request = Request::StateProofs (request::StateProofs {
|
||||||
requests: vec![
|
requests: vec![
|
||||||
request::StateProof { block: H256::default(), key1: key1, key2: None, from_level: 0 },
|
request::StateProof { block: H256::default(), key1: key1, key2: None, from_level: 0 },
|
||||||
request::StateProof { block: H256::default(), key1: key1, key2: Some(key2), from_level: 0},
|
request::StateProof { block: H256::default(), key1: key1, key2: Some(key2), from_level: 0},
|
||||||
@ -458,7 +462,7 @@ fn get_state_proofs() {
|
|||||||
let new_buf = *flow_params.limit() - flow_params.compute_cost(request::Kind::StateProofs, 2);
|
let new_buf = *flow_params.limit() - flow_params.compute_cost(request::Kind::StateProofs, 2);
|
||||||
|
|
||||||
let mut response_stream = RlpStream::new_list(3);
|
let mut response_stream = RlpStream::new_list(3);
|
||||||
|
|
||||||
response_stream.append(&req_id).append(&new_buf).begin_list(2);
|
response_stream.append(&req_id).append(&new_buf).begin_list(2);
|
||||||
for proof in proofs {
|
for proof in proofs {
|
||||||
response_stream.append_raw(&proof, 1);
|
response_stream.append_raw(&proof, 1);
|
||||||
@ -474,15 +478,15 @@ fn get_state_proofs() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn get_contract_code() {
|
fn get_contract_code() {
|
||||||
let flow_params = FlowParams::new(5_000_000.into(), Default::default(), 0.into());
|
let flow_params = FlowParams::new(5_000_000.into(), Default::default(), 0.into());
|
||||||
let capabilities = capabilities();
|
let capabilities = capabilities();
|
||||||
|
|
||||||
let (provider, proto) = setup(flow_params.clone(), capabilities.clone());
|
let (provider, proto) = setup(flow_params.clone(), capabilities.clone());
|
||||||
|
|
||||||
let cur_status = status(provider.client.chain_info());
|
let cur_status = status(provider.client.chain_info());
|
||||||
|
|
||||||
{
|
{
|
||||||
let packet_body = write_handshake(&cur_status, &capabilities, Some(&flow_params));
|
let packet_body = write_handshake(&cur_status, &capabilities, Some(&flow_params));
|
||||||
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body.clone()));
|
proto.on_connect(&1, &Expect::Send(1, packet::STATUS, packet_body.clone()));
|
||||||
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &packet_body);
|
proto.handle_packet(&Expect::Nothing, &1, packet::STATUS, &packet_body);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -490,7 +494,7 @@ fn get_contract_code() {
|
|||||||
let key1 = U256::from(11223344).into();
|
let key1 = U256::from(11223344).into();
|
||||||
let key2 = U256::from(99988887).into();
|
let key2 = U256::from(99988887).into();
|
||||||
|
|
||||||
let request = Request::Codes (request::ContractCodes {
|
let request = Request::Codes (request::ContractCodes {
|
||||||
code_requests: vec![
|
code_requests: vec![
|
||||||
request::ContractCode { block_hash: H256::default(), account_key: key1 },
|
request::ContractCode { block_hash: H256::default(), account_key: key1 },
|
||||||
request::ContractCode { block_hash: H256::default(), account_key: key2 },
|
request::ContractCode { block_hash: H256::default(), account_key: key2 },
|
||||||
@ -507,7 +511,7 @@ fn get_contract_code() {
|
|||||||
let new_buf = *flow_params.limit() - flow_params.compute_cost(request::Kind::Codes, 2);
|
let new_buf = *flow_params.limit() - flow_params.compute_cost(request::Kind::Codes, 2);
|
||||||
|
|
||||||
let mut response_stream = RlpStream::new_list(3);
|
let mut response_stream = RlpStream::new_list(3);
|
||||||
|
|
||||||
response_stream.append(&req_id).append(&new_buf).begin_list(2);
|
response_stream.append(&req_id).append(&new_buf).begin_list(2);
|
||||||
for code in codes {
|
for code in codes {
|
||||||
response_stream.append(&code);
|
response_stream.append(&code);
|
||||||
@ -518,4 +522,4 @@ fn get_contract_code() {
|
|||||||
|
|
||||||
let expected = Expect::Respond(packet::CONTRACT_CODES, response);
|
let expected = Expect::Respond(packet::CONTRACT_CODES, response);
|
||||||
proto.handle_packet(&expected, &1, packet::GET_CONTRACT_CODES, &request_body);
|
proto.handle_packet(&expected, &1, packet::GET_CONTRACT_CODES, &request_body);
|
||||||
}
|
}
|
||||||
|
@ -40,6 +40,14 @@ pub trait ChainNotify : Send + Sync {
|
|||||||
fn stop(&self) {
|
fn stop(&self) {
|
||||||
// does nothing by default
|
// does nothing by default
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// fires when new transactions are received from a peer
|
||||||
|
fn transactions_received(&self,
|
||||||
|
_hashes: Vec<H256>,
|
||||||
|
_peer_id: usize,
|
||||||
|
) {
|
||||||
|
// does nothing by default
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IpcConfig for ChainNotify { }
|
impl IpcConfig for ChainNotify { }
|
||||||
|
@ -584,11 +584,15 @@ impl Client {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Import transactions from the IO queue
|
/// Import transactions from the IO queue
|
||||||
pub fn import_queued_transactions(&self, transactions: &[Bytes]) -> usize {
|
pub fn import_queued_transactions(&self, transactions: &[Bytes], peer_id: usize) -> usize {
|
||||||
trace!(target: "external_tx", "Importing queued");
|
trace!(target: "external_tx", "Importing queued");
|
||||||
let _timer = PerfTimer::new("import_queued_transactions");
|
let _timer = PerfTimer::new("import_queued_transactions");
|
||||||
self.queue_transactions.fetch_sub(transactions.len(), AtomicOrdering::SeqCst);
|
self.queue_transactions.fetch_sub(transactions.len(), AtomicOrdering::SeqCst);
|
||||||
let txs = transactions.iter().filter_map(|bytes| UntrustedRlp::new(bytes).as_val().ok()).collect();
|
let txs: Vec<SignedTransaction> = transactions.iter().filter_map(|bytes| UntrustedRlp::new(bytes).as_val().ok()).collect();
|
||||||
|
let hashes: Vec<_> = txs.iter().map(|tx| tx.hash()).collect();
|
||||||
|
self.notify(|notify| {
|
||||||
|
notify.transactions_received(hashes.clone(), peer_id);
|
||||||
|
});
|
||||||
let results = self.miner.import_external_transactions(self, txs);
|
let results = self.miner.import_external_transactions(self, txs);
|
||||||
results.len()
|
results.len()
|
||||||
}
|
}
|
||||||
@ -1303,14 +1307,14 @@ impl BlockChainClient for Client {
|
|||||||
(*self.build_last_hashes(self.chain.read().best_block_hash())).clone()
|
(*self.build_last_hashes(self.chain.read().best_block_hash())).clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn queue_transactions(&self, transactions: Vec<Bytes>) {
|
fn queue_transactions(&self, transactions: Vec<Bytes>, peer_id: usize) {
|
||||||
let queue_size = self.queue_transactions.load(AtomicOrdering::Relaxed);
|
let queue_size = self.queue_transactions.load(AtomicOrdering::Relaxed);
|
||||||
trace!(target: "external_tx", "Queue size: {}", queue_size);
|
trace!(target: "external_tx", "Queue size: {}", queue_size);
|
||||||
if queue_size > MAX_TX_QUEUE_SIZE {
|
if queue_size > MAX_TX_QUEUE_SIZE {
|
||||||
debug!("Ignoring {} transactions: queue is full", transactions.len());
|
debug!("Ignoring {} transactions: queue is full", transactions.len());
|
||||||
} else {
|
} else {
|
||||||
let len = transactions.len();
|
let len = transactions.len();
|
||||||
match self.io_channel.lock().send(ClientIoMessage::NewTransactions(transactions)) {
|
match self.io_channel.lock().send(ClientIoMessage::NewTransactions(transactions, peer_id)) {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
self.queue_transactions.fetch_add(len, AtomicOrdering::SeqCst);
|
self.queue_transactions.fetch_add(len, AtomicOrdering::SeqCst);
|
||||||
}
|
}
|
||||||
|
@ -661,7 +661,7 @@ impl BlockChainClient for TestBlockChainClient {
|
|||||||
unimplemented!();
|
unimplemented!();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn queue_transactions(&self, transactions: Vec<Bytes>) {
|
fn queue_transactions(&self, transactions: Vec<Bytes>, _peer_id: usize) {
|
||||||
// import right here
|
// import right here
|
||||||
let txs = transactions.into_iter().filter_map(|bytes| UntrustedRlp::new(&bytes).as_val().ok()).collect();
|
let txs = transactions.into_iter().filter_map(|bytes| UntrustedRlp::new(&bytes).as_val().ok()).collect();
|
||||||
self.miner.import_external_transactions(self, txs);
|
self.miner.import_external_transactions(self, txs);
|
||||||
|
@ -203,7 +203,7 @@ pub trait BlockChainClient : Sync + Send {
|
|||||||
fn last_hashes(&self) -> LastHashes;
|
fn last_hashes(&self) -> LastHashes;
|
||||||
|
|
||||||
/// Queue transactions for importing.
|
/// Queue transactions for importing.
|
||||||
fn queue_transactions(&self, transactions: Vec<Bytes>);
|
fn queue_transactions(&self, transactions: Vec<Bytes>, peer_id: usize);
|
||||||
|
|
||||||
/// list all transactions
|
/// list all transactions
|
||||||
fn pending_transactions(&self) -> Vec<SignedTransaction>;
|
fn pending_transactions(&self) -> Vec<SignedTransaction>;
|
||||||
@ -310,9 +310,9 @@ pub trait ProvingBlockChainClient: BlockChainClient {
|
|||||||
/// The key is the keccak hash of the account's address.
|
/// The key is the keccak hash of the account's address.
|
||||||
/// Returns a vector of raw trie nodes (in order from the root) proving the query.
|
/// Returns a vector of raw trie nodes (in order from the root) proving the query.
|
||||||
/// Nodes after `from_level` may be omitted.
|
/// Nodes after `from_level` may be omitted.
|
||||||
/// An empty vector indicates unservable query.
|
/// An empty vector indicates unservable query.
|
||||||
fn prove_account(&self, key1: H256, from_level: u32, id: BlockId) -> Vec<Bytes>;
|
fn prove_account(&self, key1: H256, from_level: u32, id: BlockId) -> Vec<Bytes>;
|
||||||
|
|
||||||
/// Get code by address hash.
|
/// Get code by address hash.
|
||||||
fn code_by_hash(&self, account_key: H256, id: BlockId) -> Bytes;
|
fn code_by_hash(&self, account_key: H256, id: BlockId) -> Bytes;
|
||||||
}
|
}
|
||||||
|
@ -39,7 +39,7 @@ pub enum ClientIoMessage {
|
|||||||
/// A block is ready
|
/// A block is ready
|
||||||
BlockVerified,
|
BlockVerified,
|
||||||
/// New transaction RLPs are ready to be imported
|
/// New transaction RLPs are ready to be imported
|
||||||
NewTransactions(Vec<Bytes>),
|
NewTransactions(Vec<Bytes>, usize),
|
||||||
/// Begin snapshot restoration
|
/// Begin snapshot restoration
|
||||||
BeginRestoration(ManifestData),
|
BeginRestoration(ManifestData),
|
||||||
/// Feed a state chunk to the snapshot service
|
/// Feed a state chunk to the snapshot service
|
||||||
@ -196,7 +196,9 @@ impl IoHandler<ClientIoMessage> for ClientIoHandler {
|
|||||||
|
|
||||||
match *net_message {
|
match *net_message {
|
||||||
ClientIoMessage::BlockVerified => { self.client.import_verified_blocks(); }
|
ClientIoMessage::BlockVerified => { self.client.import_verified_blocks(); }
|
||||||
ClientIoMessage::NewTransactions(ref transactions) => { self.client.import_queued_transactions(transactions); }
|
ClientIoMessage::NewTransactions(ref transactions, peer_id) => {
|
||||||
|
self.client.import_queued_transactions(transactions, peer_id);
|
||||||
|
}
|
||||||
ClientIoMessage::BeginRestoration(ref manifest) => {
|
ClientIoMessage::BeginRestoration(ref manifest) => {
|
||||||
if let Err(e) = self.snapshot.init_restore(manifest.clone(), true) {
|
if let Err(e) = self.snapshot.init_restore(manifest.clone(), true) {
|
||||||
warn!("Failed to initialize snapshot restoration: {}", e);
|
warn!("Failed to initialize snapshot restoration: {}", e);
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "parity.js",
|
"name": "parity.js",
|
||||||
"version": "0.2.114",
|
"version": "0.2.119",
|
||||||
"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>",
|
||||||
|
@ -22,8 +22,12 @@ export default class DappReg {
|
|||||||
this.getInstance();
|
this.getInstance();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getContract () {
|
||||||
|
return this._registry.getContract('dappreg');
|
||||||
|
}
|
||||||
|
|
||||||
getInstance () {
|
getInstance () {
|
||||||
return this._registry.getContractInstance('dappreg');
|
return this.getContract().then((contract) => contract.instance);
|
||||||
}
|
}
|
||||||
|
|
||||||
count () {
|
count () {
|
||||||
|
@ -48,7 +48,6 @@ class BaseTransaction extends Component {
|
|||||||
<IdentityIcon
|
<IdentityIcon
|
||||||
address={ transaction.from }
|
address={ transaction.from }
|
||||||
/>
|
/>
|
||||||
0x{ transaction.nonce.toString(16) }
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -34,7 +34,7 @@ describe('dapps/localtx/Transaction', () => {
|
|||||||
it('renders without crashing', () => {
|
it('renders without crashing', () => {
|
||||||
const transaction = {
|
const transaction = {
|
||||||
hash: '0x1234567890',
|
hash: '0x1234567890',
|
||||||
nonce: 15,
|
nonce: new BigNumber(15),
|
||||||
gasPrice: new BigNumber(10),
|
gasPrice: new BigNumber(10),
|
||||||
gas: new BigNumber(10)
|
gas: new BigNumber(10)
|
||||||
};
|
};
|
||||||
|
@ -19,11 +19,14 @@ import { action, observable, transaction } from 'mobx';
|
|||||||
import { addLocaleData } from 'react-intl';
|
import { addLocaleData } from 'react-intl';
|
||||||
import de from 'react-intl/locale-data/de';
|
import de from 'react-intl/locale-data/de';
|
||||||
import en from 'react-intl/locale-data/en';
|
import en from 'react-intl/locale-data/en';
|
||||||
|
import store from 'store';
|
||||||
|
|
||||||
import languages from './languages';
|
import languages from './languages';
|
||||||
import deMessages from './de';
|
import deMessages from './de';
|
||||||
import enMessages from './en';
|
import enMessages from './en';
|
||||||
|
|
||||||
|
const LS_STORE_KEY = '_parity::locale';
|
||||||
|
|
||||||
let instance = null;
|
let instance = null;
|
||||||
const isProduction = process.env.NODE_ENV === 'production';
|
const isProduction = process.env.NODE_ENV === 'production';
|
||||||
|
|
||||||
@ -45,10 +48,21 @@ export default class Store {
|
|||||||
@observable messages = MESSAGES[DEFAULT];
|
@observable messages = MESSAGES[DEFAULT];
|
||||||
@observable isDevelopment = !isProduction;
|
@observable isDevelopment = !isProduction;
|
||||||
|
|
||||||
|
constructor () {
|
||||||
|
const savedLocale = store.get(LS_STORE_KEY);
|
||||||
|
|
||||||
|
this.locale = (savedLocale && LOCALES.includes(savedLocale))
|
||||||
|
? savedLocale
|
||||||
|
: DEFAULT;
|
||||||
|
this.messages = MESSAGES[this.locale];
|
||||||
|
}
|
||||||
|
|
||||||
@action setLocale (locale) {
|
@action setLocale (locale) {
|
||||||
transaction(() => {
|
transaction(() => {
|
||||||
this.locale = locale;
|
this.locale = locale;
|
||||||
this.messages = MESSAGES[locale];
|
this.messages = MESSAGES[locale];
|
||||||
|
|
||||||
|
store.set(LS_STORE_KEY, locale);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -15,10 +15,9 @@
|
|||||||
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
import React, { Component, PropTypes } from 'react';
|
import React, { Component, PropTypes } from 'react';
|
||||||
import { Redirect, Router, Route, IndexRoute } from 'react-router';
|
import { Router } from 'react-router';
|
||||||
|
|
||||||
import { Accounts, Account, Addresses, Address, Application, Contract, Contracts, WriteContract, Wallet, Dapp, Dapps, Settings, SettingsBackground, SettingsParity, SettingsProxy, SettingsViews, Signer, Status } from '~/views';
|
|
||||||
|
|
||||||
|
import routes from './routes';
|
||||||
import styles from './reset.css';
|
import styles from './reset.css';
|
||||||
|
|
||||||
export default class MainApplication extends Component {
|
export default class MainApplication extends Component {
|
||||||
@ -26,73 +25,11 @@ export default class MainApplication extends Component {
|
|||||||
routerHistory: PropTypes.any.isRequired
|
routerHistory: PropTypes.any.isRequired
|
||||||
};
|
};
|
||||||
|
|
||||||
handleDeprecatedRoute = (nextState, replace) => {
|
|
||||||
const { address } = nextState.params;
|
|
||||||
const redirectMap = {
|
|
||||||
account: 'accounts',
|
|
||||||
address: 'addresses',
|
|
||||||
contract: 'contracts'
|
|
||||||
};
|
|
||||||
|
|
||||||
const oldRoute = nextState.routes[0].path;
|
|
||||||
const newRoute = Object.keys(redirectMap).reduce((newRoute, key) => {
|
|
||||||
return newRoute.replace(new RegExp(`^/${key}`), '/' + redirectMap[key]);
|
|
||||||
}, oldRoute);
|
|
||||||
|
|
||||||
console.warn(`Route "${oldRoute}" is deprecated. Please use "${newRoute}"`);
|
|
||||||
replace(newRoute.replace(':address', address));
|
|
||||||
}
|
|
||||||
|
|
||||||
render () {
|
render () {
|
||||||
const { routerHistory } = this.props;
|
const { routerHistory } = this.props;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Router className={ styles.reset } history={ routerHistory }>
|
<Router className={ styles.reset } history={ routerHistory } routes={ routes } />
|
||||||
<Redirect from='/' to='/accounts' />
|
|
||||||
<Redirect from='/auth' to='/accounts' query={ {} } />
|
|
||||||
<Redirect from='/settings' to='/settings/views' />
|
|
||||||
|
|
||||||
{ /** Backward Compatible links */ }
|
|
||||||
<Route path='/account/:address' onEnter={ this.handleDeprecatedRoute } />
|
|
||||||
<Route path='/address/:address' onEnter={ this.handleDeprecatedRoute } />
|
|
||||||
<Route path='/contract/:address' onEnter={ this.handleDeprecatedRoute } />
|
|
||||||
|
|
||||||
<Route path='/' component={ Application }>
|
|
||||||
<Route path='accounts'>
|
|
||||||
<IndexRoute component={ Accounts } />
|
|
||||||
<Route path=':address' component={ Account } />
|
|
||||||
<Route path='/wallet/:address' component={ Wallet } />
|
|
||||||
</Route>
|
|
||||||
|
|
||||||
<Route path='addresses'>
|
|
||||||
<IndexRoute component={ Addresses } />
|
|
||||||
<Route path=':address' component={ Address } />
|
|
||||||
</Route>
|
|
||||||
|
|
||||||
<Route path='apps' component={ Dapps } />
|
|
||||||
<Route path='app/:id' component={ Dapp } />
|
|
||||||
|
|
||||||
<Route path='contracts'>
|
|
||||||
<IndexRoute component={ Contracts } />
|
|
||||||
<Route path='develop' component={ WriteContract } />
|
|
||||||
<Route path=':address' component={ Contract } />
|
|
||||||
</Route>
|
|
||||||
|
|
||||||
<Route path='settings' component={ Settings }>
|
|
||||||
<Route path='background' component={ SettingsBackground } />
|
|
||||||
<Route path='proxy' component={ SettingsProxy } />
|
|
||||||
<Route path='views' component={ SettingsViews } />
|
|
||||||
<Route path='parity' component={ SettingsParity } />
|
|
||||||
</Route>
|
|
||||||
|
|
||||||
<Route path='signer' component={ Signer } />
|
|
||||||
|
|
||||||
<Route path='status'>
|
|
||||||
<IndexRoute component={ Status } />
|
|
||||||
<Route path=':subpage' component={ Status } />
|
|
||||||
</Route>
|
|
||||||
</Route>
|
|
||||||
</Router>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -14,31 +14,29 @@
|
|||||||
// 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 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 { observer } from 'mobx-react';
|
||||||
|
import React, { Component, PropTypes } from 'react';
|
||||||
|
import { FormattedMessage } from 'react-intl';
|
||||||
|
|
||||||
import { Button, Modal, Form, Input, InputAddress } from '~/ui';
|
import { Button, Form, Input, InputAddress, Modal } from '~/ui';
|
||||||
import { ERRORS, validateAddress, validateName } from '~/util/validation';
|
|
||||||
|
|
||||||
|
import Store from './store';
|
||||||
|
|
||||||
|
@observer
|
||||||
export default class AddAddress extends Component {
|
export default class AddAddress extends Component {
|
||||||
static contextTypes = {
|
static contextTypes = {
|
||||||
api: PropTypes.object.isRequired
|
api: PropTypes.object.isRequired
|
||||||
}
|
}
|
||||||
|
|
||||||
static propTypes = {
|
static propTypes = {
|
||||||
contacts: PropTypes.object.isRequired,
|
|
||||||
address: PropTypes.string,
|
address: PropTypes.string,
|
||||||
onClose: PropTypes.func
|
contacts: PropTypes.object.isRequired,
|
||||||
|
onClose: PropTypes.func.isRequired
|
||||||
};
|
};
|
||||||
|
|
||||||
state = {
|
store = new Store(this.context.api, this.props.contacts);
|
||||||
address: '',
|
|
||||||
addressError: ERRORS.invalidAddress,
|
|
||||||
name: '',
|
|
||||||
nameError: ERRORS.invalidName,
|
|
||||||
description: ''
|
|
||||||
};
|
|
||||||
|
|
||||||
componentWillMount () {
|
componentWillMount () {
|
||||||
if (this.props.address) {
|
if (this.props.address) {
|
||||||
@ -49,109 +47,113 @@ export default class AddAddress extends Component {
|
|||||||
render () {
|
render () {
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
visible
|
|
||||||
actions={ this.renderDialogActions() }
|
actions={ this.renderDialogActions() }
|
||||||
title='add saved address'>
|
title={
|
||||||
|
<FormattedMessage
|
||||||
|
id='addAddress.label'
|
||||||
|
defaultMessage='add saved address' />
|
||||||
|
}
|
||||||
|
visible>
|
||||||
{ this.renderFields() }
|
{ this.renderFields() }
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
renderDialogActions () {
|
renderDialogActions () {
|
||||||
const { addressError, nameError } = this.state;
|
const { hasError } = this.store;
|
||||||
const hasError = !!(addressError || nameError);
|
|
||||||
|
|
||||||
return ([
|
return ([
|
||||||
<Button
|
<Button
|
||||||
icon={ <ContentClear /> }
|
icon={ <ContentClear /> }
|
||||||
label='Cancel'
|
label={
|
||||||
onClick={ this.onClose } />,
|
<FormattedMessage
|
||||||
|
id='addAddress.button.close'
|
||||||
|
defaultMessage='Cancel' />
|
||||||
|
}
|
||||||
|
onClick={ this.onClose }
|
||||||
|
ref='closeButton' />,
|
||||||
<Button
|
<Button
|
||||||
icon={ <ContentAdd /> }
|
|
||||||
label='Save Address'
|
|
||||||
disabled={ hasError }
|
disabled={ hasError }
|
||||||
onClick={ this.onAdd } />
|
icon={ <ContentAdd /> }
|
||||||
|
label={
|
||||||
|
<FormattedMessage
|
||||||
|
id='addAddress.button.add'
|
||||||
|
defaultMessage='Save Address' />
|
||||||
|
}
|
||||||
|
onClick={ this.onAdd }
|
||||||
|
ref='addButton' />
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
renderFields () {
|
renderFields () {
|
||||||
const { address, addressError, description, name, nameError } = this.state;
|
const { address, addressError, description, name, nameError } = this.store;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Form>
|
<Form>
|
||||||
<InputAddress
|
<InputAddress
|
||||||
label='network address'
|
|
||||||
hint='the network address for the entry'
|
|
||||||
error={ addressError }
|
|
||||||
value={ address }
|
|
||||||
disabled={ !!this.props.address }
|
|
||||||
allowCopy={ false }
|
allowCopy={ false }
|
||||||
onChange={ this.onEditAddress } />
|
disabled={ !!this.props.address }
|
||||||
|
error={ addressError }
|
||||||
|
hint={
|
||||||
|
<FormattedMessage
|
||||||
|
id='addAddress.input.address.hint'
|
||||||
|
defaultMessage='the network address for the entry' />
|
||||||
|
}
|
||||||
|
label={
|
||||||
|
<FormattedMessage
|
||||||
|
id='addAddress.input.address.label'
|
||||||
|
defaultMessage='network address' />
|
||||||
|
}
|
||||||
|
onChange={ this.onEditAddress }
|
||||||
|
ref='inputAddress'
|
||||||
|
value={ address } />
|
||||||
<Input
|
<Input
|
||||||
label='address name'
|
|
||||||
hint='a descriptive name for the entry'
|
|
||||||
error={ nameError }
|
error={ nameError }
|
||||||
value={ name }
|
hint={
|
||||||
onChange={ this.onEditName } />
|
<FormattedMessage
|
||||||
|
id='addAddress.input.name.hint'
|
||||||
|
defaultMessage='a descriptive name for the entry' />
|
||||||
|
}
|
||||||
|
label={
|
||||||
|
<FormattedMessage
|
||||||
|
id='addAddress.input.name.label'
|
||||||
|
defaultMessage='address name' />
|
||||||
|
}
|
||||||
|
onChange={ this.onEditName }
|
||||||
|
ref='inputName'
|
||||||
|
value={ name } />
|
||||||
<Input
|
<Input
|
||||||
multiLine
|
hint={
|
||||||
rows={ 1 }
|
<FormattedMessage
|
||||||
label='(optional) address description'
|
id='addAddress.input.description.hint'
|
||||||
hint='an expanded description for the entry'
|
defaultMessage='an expanded description for the entry' />
|
||||||
value={ description }
|
}
|
||||||
onChange={ this.onEditDescription } />
|
label={
|
||||||
|
<FormattedMessage
|
||||||
|
id='addAddress.input.description.label'
|
||||||
|
defaultMessage='(optional) address description' />
|
||||||
|
}
|
||||||
|
onChange={ this.onEditDescription }
|
||||||
|
ref='inputDescription'
|
||||||
|
value={ description } />
|
||||||
</Form>
|
</Form>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
onEditAddress = (event, _address) => {
|
onEditAddress = (event, address) => {
|
||||||
const { contacts } = this.props;
|
this.store.setAddress(address);
|
||||||
let { address, addressError } = validateAddress(_address);
|
|
||||||
|
|
||||||
if (!addressError) {
|
|
||||||
const contact = contacts[address];
|
|
||||||
|
|
||||||
if (contact) {
|
|
||||||
addressError = ERRORS.duplicateAddress;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.setState({
|
|
||||||
address,
|
|
||||||
addressError
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onEditDescription = (event, description) => {
|
onEditDescription = (event, description) => {
|
||||||
this.setState({
|
this.store.setDescription(description);
|
||||||
description
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onEditName = (event, _name) => {
|
onEditName = (event, name) => {
|
||||||
const { name, nameError } = validateName(_name);
|
this.store.setName(name);
|
||||||
|
|
||||||
this.setState({
|
|
||||||
name,
|
|
||||||
nameError
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onAdd = () => {
|
onAdd = () => {
|
||||||
const { api } = this.context;
|
this.store.add();
|
||||||
const { address, name, description } = this.state;
|
|
||||||
|
|
||||||
Promise.all([
|
|
||||||
api.parity.setAccountName(address, name),
|
|
||||||
api.parity.setAccountMeta(address, {
|
|
||||||
description,
|
|
||||||
timestamp: Date.now(),
|
|
||||||
deleted: false
|
|
||||||
})
|
|
||||||
]).catch((error) => {
|
|
||||||
console.error('onAdd', error);
|
|
||||||
});
|
|
||||||
|
|
||||||
this.props.onClose();
|
this.props.onClose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
32
js/src/modals/AddAddress/addAddress.spec.js
Normal file
32
js/src/modals/AddAddress/addAddress.spec.js
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
|
||||||
|
// This file is part of Parity.
|
||||||
|
|
||||||
|
// Parity is free software: you can redistribute it and/or modify
|
||||||
|
// it under the terms of the GNU General Public License as published by
|
||||||
|
// the Free Software Foundation, either version 3 of the License, or
|
||||||
|
// (at your option) any later version.
|
||||||
|
|
||||||
|
// Parity is distributed in the hope that it will be useful,
|
||||||
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
// GNU General Public License for more details.
|
||||||
|
|
||||||
|
// You should have received a copy of the GNU General Public License
|
||||||
|
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import { shallow } from 'enzyme';
|
||||||
|
import React from 'react';
|
||||||
|
|
||||||
|
import AddAddress from './';
|
||||||
|
|
||||||
|
describe('modals/AddAddress', () => {
|
||||||
|
describe('rendering', () => {
|
||||||
|
it('renders defaults', () => {
|
||||||
|
expect(
|
||||||
|
shallow(
|
||||||
|
<AddAddress />
|
||||||
|
)
|
||||||
|
).to.be.ok;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
87
js/src/modals/AddAddress/store.js
Normal file
87
js/src/modals/AddAddress/store.js
Normal file
@ -0,0 +1,87 @@
|
|||||||
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
|
||||||
|
// This file is part of Parity.
|
||||||
|
|
||||||
|
// Parity is free software: you can redistribute it and/or modify
|
||||||
|
// it under the terms of the GNU General Public License as published by
|
||||||
|
// the Free Software Foundation, either version 3 of the License, or
|
||||||
|
// (at your option) any later version.
|
||||||
|
|
||||||
|
// Parity is distributed in the hope that it will be useful,
|
||||||
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
// GNU General Public License for more details.
|
||||||
|
|
||||||
|
// You should have received a copy of the GNU General Public License
|
||||||
|
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import { action, computed, transaction, observable } from 'mobx';
|
||||||
|
|
||||||
|
import { ERRORS, validateAddress, validateName } from '~/util/validation';
|
||||||
|
|
||||||
|
export default class Store {
|
||||||
|
@observable address = '';
|
||||||
|
@observable addressError = ERRORS.invalidAddress;
|
||||||
|
@observable createError = null;
|
||||||
|
@observable description = '';
|
||||||
|
@observable name = '';
|
||||||
|
@observable nameError = ERRORS.invalidName;
|
||||||
|
|
||||||
|
constructor (api, contacts) {
|
||||||
|
this._api = api;
|
||||||
|
this._contacts = contacts;
|
||||||
|
}
|
||||||
|
|
||||||
|
@computed get hasError () {
|
||||||
|
return !!(this.addressError || this.nameError);
|
||||||
|
}
|
||||||
|
|
||||||
|
@action setAddress = (_address) => {
|
||||||
|
let { address, addressError } = validateAddress(_address);
|
||||||
|
|
||||||
|
if (!addressError) {
|
||||||
|
const contact = this._contacts[address];
|
||||||
|
|
||||||
|
if (contact) {
|
||||||
|
addressError = ERRORS.duplicateAddress;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
transaction(() => {
|
||||||
|
this.address = address;
|
||||||
|
this.addressError = addressError;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@action setCreateError = (error) => {
|
||||||
|
this.createError = error;
|
||||||
|
}
|
||||||
|
|
||||||
|
@action setDescription = (description) => {
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
@action setName = (_name) => {
|
||||||
|
const { name, nameError } = validateName(_name);
|
||||||
|
|
||||||
|
transaction(() => {
|
||||||
|
this.name = name;
|
||||||
|
this.nameError = nameError;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
add () {
|
||||||
|
return Promise
|
||||||
|
.all([
|
||||||
|
this._api.parity.setAccountName(this.address, this.name),
|
||||||
|
this._api.parity.setAccountMeta(this.address, {
|
||||||
|
description: this.description,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
deleted: false
|
||||||
|
})
|
||||||
|
])
|
||||||
|
.catch((error) => {
|
||||||
|
console.warn('Store:add', error);
|
||||||
|
this.setCreateError(error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
128
js/src/modals/AddAddress/store.spec.js
Normal file
128
js/src/modals/AddAddress/store.spec.js
Normal file
@ -0,0 +1,128 @@
|
|||||||
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
|
||||||
|
// This file is part of Parity.
|
||||||
|
|
||||||
|
// Parity is free software: you can redistribute it and/or modify
|
||||||
|
// it under the terms of the GNU General Public License as published by
|
||||||
|
// the Free Software Foundation, either version 3 of the License, or
|
||||||
|
// (at your option) any later version.
|
||||||
|
|
||||||
|
// Parity is distributed in the hope that it will be useful,
|
||||||
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
// GNU General Public License for more details.
|
||||||
|
|
||||||
|
// You should have received a copy of the GNU General Public License
|
||||||
|
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import sinon from 'sinon';
|
||||||
|
|
||||||
|
import Store from './store';
|
||||||
|
|
||||||
|
import { TEST_ADDR_A, TEST_ADDR_B, TEST_CONTACTS } from './store.test.js';
|
||||||
|
|
||||||
|
describe('modals/AddAddress/store', () => {
|
||||||
|
let store;
|
||||||
|
|
||||||
|
describe('@action', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
store = new Store(null, TEST_CONTACTS);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('setAddress', () => {
|
||||||
|
it('successfully sets non-existent addresses', () => {
|
||||||
|
store.setAddress(TEST_ADDR_B);
|
||||||
|
|
||||||
|
expect(store.addressError).to.be.null;
|
||||||
|
expect(store.address).to.equal(TEST_ADDR_B);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails on invalid addresses', () => {
|
||||||
|
store.setAddress('0xinvalid');
|
||||||
|
|
||||||
|
expect(store.addressError).not.to.be.null;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails when an address is already added', () => {
|
||||||
|
store.setAddress(TEST_ADDR_A);
|
||||||
|
|
||||||
|
expect(store.addressError).not.to.be.null;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('setName', () => {
|
||||||
|
it('sucessfully sets valid names', () => {
|
||||||
|
const name = 'Test Name';
|
||||||
|
|
||||||
|
store.setName(name);
|
||||||
|
|
||||||
|
expect(store.nameError).to.be.null;
|
||||||
|
expect(store.name).to.equal(name);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails when name is invalid', () => {
|
||||||
|
store.setName(null);
|
||||||
|
|
||||||
|
expect(store.nameError).not.to.be.null;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('@computed', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
store = new Store(null, TEST_CONTACTS);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('hasError', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
store.setAddress(TEST_ADDR_B);
|
||||||
|
store.setName('Test Name');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns false proper inputs', () => {
|
||||||
|
expect(store.hasError).to.be.false;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns true with addressError', () => {
|
||||||
|
store.setAddress(TEST_ADDR_A);
|
||||||
|
|
||||||
|
expect(store.addressError).not.to.be.null;
|
||||||
|
expect(store.hasError).to.be.true;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns true with nameError', () => {
|
||||||
|
store.setName(null);
|
||||||
|
|
||||||
|
expect(store.nameError).not.to.be.null;
|
||||||
|
expect(store.hasError).to.be.true;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('methods', () => {
|
||||||
|
let api;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
api = {
|
||||||
|
parity: {
|
||||||
|
setAccountMeta: sinon.stub().resolves(true),
|
||||||
|
setAccountName: sinon.stub().resolves(true)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
store = new Store(api, {});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('add', () => {
|
||||||
|
it('calls setAccountMeta', () => {
|
||||||
|
store.add();
|
||||||
|
|
||||||
|
expect(api.parity.setAccountMeta).to.have.been.called;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('calls setAccountName', () => {
|
||||||
|
store.add();
|
||||||
|
|
||||||
|
expect(api.parity.setAccountName).to.have.been.called;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
28
js/src/modals/AddAddress/store.test.js
Normal file
28
js/src/modals/AddAddress/store.test.js
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
|
||||||
|
// This file is part of Parity.
|
||||||
|
|
||||||
|
// Parity is free software: you can redistribute it and/or modify
|
||||||
|
// it under the terms of the GNU General Public License as published by
|
||||||
|
// the Free Software Foundation, either version 3 of the License, or
|
||||||
|
// (at your option) any later version.
|
||||||
|
|
||||||
|
// Parity is distributed in the hope that it will be useful,
|
||||||
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
// GNU General Public License for more details.
|
||||||
|
|
||||||
|
// You should have received a copy of the GNU General Public License
|
||||||
|
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
const TEST_ADDR_A = '0x63Cf90D3f0410092FC0fca41846f596223979195';
|
||||||
|
const TEST_ADDR_B = '0x00A40dEfa9933e82244bE542Fa7F8748eCCdd457';
|
||||||
|
|
||||||
|
const TEST_CONTACTS = {
|
||||||
|
[TEST_ADDR_A]: { name: 'test', meta: {} }
|
||||||
|
};
|
||||||
|
|
||||||
|
export {
|
||||||
|
TEST_ADDR_A,
|
||||||
|
TEST_ADDR_B,
|
||||||
|
TEST_CONTACTS
|
||||||
|
};
|
@ -19,6 +19,8 @@ import { isEqual } from 'lodash';
|
|||||||
import { fetchBalances } from './balancesActions';
|
import { fetchBalances } from './balancesActions';
|
||||||
import { attachWallets } from './walletActions';
|
import { attachWallets } from './walletActions';
|
||||||
|
|
||||||
|
import MethodDecodingStore from '~/ui/MethodDecoding/methodDecodingStore';
|
||||||
|
|
||||||
export function personalAccountsInfo (accountsInfo) {
|
export function personalAccountsInfo (accountsInfo) {
|
||||||
const accounts = {};
|
const accounts = {};
|
||||||
const contacts = {};
|
const contacts = {};
|
||||||
@ -41,6 +43,9 @@ export function personalAccountsInfo (accountsInfo) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Load user contracts for Method Decoding
|
||||||
|
MethodDecodingStore.loadContracts(contracts);
|
||||||
|
|
||||||
return (dispatch) => {
|
return (dispatch) => {
|
||||||
const data = {
|
const data = {
|
||||||
accountsInfo,
|
accountsInfo,
|
||||||
|
@ -62,7 +62,7 @@ export default handleActions({
|
|||||||
signerSuccessConfirmRequest (state, action) {
|
signerSuccessConfirmRequest (state, action) {
|
||||||
const { id, txHash } = action.payload;
|
const { id, txHash } = action.payload;
|
||||||
const confirmed = Object.assign(
|
const confirmed = Object.assign(
|
||||||
state.pending.find(p => p.id === id),
|
state.pending.find(p => p.id === id) || { id },
|
||||||
{ result: txHash, status: 'confirmed' }
|
{ result: txHash, status: 'confirmed' }
|
||||||
);
|
);
|
||||||
|
|
||||||
|
119
js/src/routes.js
Normal file
119
js/src/routes.js
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
|
||||||
|
// This file is part of Parity.
|
||||||
|
|
||||||
|
// Parity is free software: you can redistribute it and/or modify
|
||||||
|
// it under the terms of the GNU General Public License as published by
|
||||||
|
// the Free Software Foundation, either version 3 of the License, or
|
||||||
|
// (at your option) any later version.
|
||||||
|
|
||||||
|
// Parity is distributed in the hope that it will be useful,
|
||||||
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
// GNU General Public License for more details.
|
||||||
|
|
||||||
|
// You should have received a copy of the GNU General Public License
|
||||||
|
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import {
|
||||||
|
Accounts, Account, Addresses, Address, Application,
|
||||||
|
Contract, Contracts, WriteContract, Wallet, Dapp, Dapps,
|
||||||
|
Settings, SettingsBackground, SettingsParity, SettingsProxy,
|
||||||
|
SettingsViews, Signer, Status
|
||||||
|
} from '~/views';
|
||||||
|
|
||||||
|
function handleDeprecatedRoute (nextState, replace) {
|
||||||
|
const { address } = nextState.params;
|
||||||
|
const redirectMap = {
|
||||||
|
account: 'accounts',
|
||||||
|
address: 'addresses',
|
||||||
|
contract: 'contracts'
|
||||||
|
};
|
||||||
|
|
||||||
|
const oldRoute = nextState.routes[0].path;
|
||||||
|
const newRoute = Object.keys(redirectMap).reduce((newRoute, key) => {
|
||||||
|
return newRoute.replace(new RegExp(`^/${key}`), '/' + redirectMap[key]);
|
||||||
|
}, oldRoute);
|
||||||
|
|
||||||
|
console.warn(`Route "${oldRoute}" is deprecated. Please use "${newRoute}"`);
|
||||||
|
replace(newRoute.replace(':address', address));
|
||||||
|
}
|
||||||
|
|
||||||
|
function redirectTo (path) {
|
||||||
|
return (nextState, replace) => {
|
||||||
|
replace(path);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const accountsRoutes = [
|
||||||
|
{ path: ':address', component: Account },
|
||||||
|
{ path: '/wallet/:address', component: Wallet }
|
||||||
|
];
|
||||||
|
|
||||||
|
const addressesRoutes = [
|
||||||
|
{ path: ':address', component: Address }
|
||||||
|
];
|
||||||
|
|
||||||
|
const contractsRoutes = [
|
||||||
|
{ path: 'develop', component: WriteContract },
|
||||||
|
{ path: ':address', component: Contract }
|
||||||
|
];
|
||||||
|
|
||||||
|
const settingsRoutes = [
|
||||||
|
{ path: 'background', component: SettingsBackground },
|
||||||
|
{ path: 'proxy', component: SettingsProxy },
|
||||||
|
{ path: 'views', component: SettingsViews },
|
||||||
|
{ path: 'parity', component: SettingsParity }
|
||||||
|
];
|
||||||
|
|
||||||
|
const statusRoutes = [
|
||||||
|
{ path: ':subpage', component: Status }
|
||||||
|
];
|
||||||
|
|
||||||
|
const routes = [
|
||||||
|
// Backward Compatible routes
|
||||||
|
{ path: '/account/:address', onEnter: handleDeprecatedRoute },
|
||||||
|
{ path: '/address/:address', onEnter: handleDeprecatedRoute },
|
||||||
|
{ path: '/contract/:address', onEnter: handleDeprecatedRoute },
|
||||||
|
|
||||||
|
{ path: '/', onEnter: redirectTo('/accounts') },
|
||||||
|
{ path: '/auth', onEnter: redirectTo('/accounts') },
|
||||||
|
{ path: '/settings', onEnter: redirectTo('/settings/views') },
|
||||||
|
|
||||||
|
{
|
||||||
|
path: '/',
|
||||||
|
component: Application,
|
||||||
|
childRoutes: [
|
||||||
|
{
|
||||||
|
path: 'accounts',
|
||||||
|
indexRoute: { component: Accounts },
|
||||||
|
childRoutes: accountsRoutes
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'addresses',
|
||||||
|
indexRoute: { component: Addresses },
|
||||||
|
childRoutes: addressesRoutes
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'contracts',
|
||||||
|
indexRoute: { component: Contracts },
|
||||||
|
childRoutes: contractsRoutes
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'status',
|
||||||
|
indexRoute: { component: Status },
|
||||||
|
childRoutes: statusRoutes
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'settings',
|
||||||
|
component: Settings,
|
||||||
|
childRoutes: settingsRoutes
|
||||||
|
},
|
||||||
|
|
||||||
|
{ path: 'apps', component: Dapps },
|
||||||
|
{ path: 'app/:id', component: Dapp },
|
||||||
|
{ path: 'signer', component: Signer }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
export default routes;
|
@ -16,6 +16,7 @@
|
|||||||
|
|
||||||
import React, { Component, PropTypes } from 'react';
|
import React, { Component, PropTypes } from 'react';
|
||||||
import { MenuItem } from 'material-ui';
|
import { MenuItem } from 'material-ui';
|
||||||
|
import { isEqual, pick } from 'lodash';
|
||||||
|
|
||||||
import AutoComplete from '../AutoComplete';
|
import AutoComplete from '../AutoComplete';
|
||||||
import IdentityIcon from '../../IdentityIcon';
|
import IdentityIcon from '../../IdentityIcon';
|
||||||
@ -31,19 +32,20 @@ export default class AddressSelect extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static propTypes = {
|
static propTypes = {
|
||||||
disabled: PropTypes.bool,
|
onChange: PropTypes.func.isRequired,
|
||||||
|
|
||||||
accounts: PropTypes.object,
|
accounts: PropTypes.object,
|
||||||
|
allowInput: PropTypes.bool,
|
||||||
|
balances: PropTypes.object,
|
||||||
contacts: PropTypes.object,
|
contacts: PropTypes.object,
|
||||||
contracts: PropTypes.object,
|
contracts: PropTypes.object,
|
||||||
wallets: PropTypes.object,
|
disabled: PropTypes.bool,
|
||||||
label: PropTypes.string,
|
|
||||||
hint: PropTypes.string,
|
|
||||||
error: PropTypes.string,
|
error: PropTypes.string,
|
||||||
value: PropTypes.string,
|
hint: PropTypes.string,
|
||||||
|
label: PropTypes.string,
|
||||||
tokens: PropTypes.object,
|
tokens: PropTypes.object,
|
||||||
onChange: PropTypes.func.isRequired,
|
value: PropTypes.string,
|
||||||
allowInput: PropTypes.bool,
|
wallets: PropTypes.object
|
||||||
balances: PropTypes.object
|
|
||||||
}
|
}
|
||||||
|
|
||||||
state = {
|
state = {
|
||||||
@ -53,6 +55,9 @@ export default class AddressSelect extends Component {
|
|||||||
value: ''
|
value: ''
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Cache autocomplete items
|
||||||
|
items = {}
|
||||||
|
|
||||||
entriesFromProps (props = this.props) {
|
entriesFromProps (props = this.props) {
|
||||||
const { accounts = {}, contacts = {}, contracts = {}, wallets = {} } = props;
|
const { accounts = {}, contacts = {}, contracts = {}, wallets = {} } = props;
|
||||||
|
|
||||||
@ -76,6 +81,15 @@ export default class AddressSelect extends Component {
|
|||||||
return { autocompleteEntries, entries };
|
return { autocompleteEntries, entries };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
shouldComponentUpdate (nextProps, nextState) {
|
||||||
|
const keys = [ 'error', 'value' ];
|
||||||
|
|
||||||
|
const prevValues = pick(this.props, keys);
|
||||||
|
const nextValues = pick(nextProps, keys);
|
||||||
|
|
||||||
|
return !isEqual(prevValues, nextValues);
|
||||||
|
}
|
||||||
|
|
||||||
componentWillMount () {
|
componentWillMount () {
|
||||||
const { value } = this.props;
|
const { value } = this.props;
|
||||||
const { entries, autocompleteEntries } = this.entriesFromProps();
|
const { entries, autocompleteEntries } = this.entriesFromProps();
|
||||||
@ -143,14 +157,21 @@ export default class AddressSelect extends Component {
|
|||||||
renderItem = (entry) => {
|
renderItem = (entry) => {
|
||||||
const { address, name } = entry;
|
const { address, name } = entry;
|
||||||
|
|
||||||
return {
|
const _balance = this.getBalance(address);
|
||||||
text: name && name.toUpperCase() || address,
|
const balance = _balance ? _balance.toNumber() : _balance;
|
||||||
value: this.renderMenuItem(address),
|
|
||||||
address
|
if (!this.items[address] || this.items[address].balance !== balance) {
|
||||||
};
|
this.items[address] = {
|
||||||
|
text: name && name.toUpperCase() || address,
|
||||||
|
value: this.renderMenuItem(address),
|
||||||
|
address, balance
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.items[address];
|
||||||
}
|
}
|
||||||
|
|
||||||
renderBalance (address) {
|
getBalance (address) {
|
||||||
const { balances = {} } = this.props;
|
const { balances = {} } = this.props;
|
||||||
const balance = balances[address];
|
const balance = balances[address];
|
||||||
|
|
||||||
@ -164,7 +185,12 @@ export default class AddressSelect extends Component {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const value = fromWei(ethToken.value);
|
return ethToken.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
renderBalance (address) {
|
||||||
|
const balance = this.getBalance(address);
|
||||||
|
const value = fromWei(balance);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={ styles.balance }>
|
<div className={ styles.balance }>
|
||||||
|
24
js/src/ui/Form/AutoComplete/autocomplete.css
Normal file
24
js/src/ui/Form/AutoComplete/autocomplete.css
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
/* 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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
.item {
|
||||||
|
&:last-child {
|
||||||
|
&.divider {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -21,13 +21,18 @@ import { PopoverAnimationVertical } from 'material-ui/Popover';
|
|||||||
|
|
||||||
import { isEqual } from 'lodash';
|
import { isEqual } from 'lodash';
|
||||||
|
|
||||||
|
import styles from './autocomplete.css';
|
||||||
|
|
||||||
// Hack to prevent "Unknown prop `disableFocusRipple` on <hr> tag" error
|
// Hack to prevent "Unknown prop `disableFocusRipple` on <hr> tag" error
|
||||||
class Divider extends Component {
|
class Divider extends Component {
|
||||||
static muiName = MUIDivider.muiName;
|
static muiName = MUIDivider.muiName;
|
||||||
|
|
||||||
render () {
|
render () {
|
||||||
return (
|
return (
|
||||||
<div style={ { margin: '0.25em 0' } }>
|
<div
|
||||||
|
style={ { margin: '0.25em 0' } }
|
||||||
|
className={ [styles.item, styles.divider].join(' ') }
|
||||||
|
>
|
||||||
<MUIDivider style={ { height: 2 } } />
|
<MUIDivider style={ { height: 2 } } />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@ -143,11 +148,16 @@ export default class AutoComplete extends Component {
|
|||||||
|
|
||||||
if (renderItem && typeof renderItem === 'function') {
|
if (renderItem && typeof renderItem === 'function') {
|
||||||
item = renderItem(entry);
|
item = renderItem(entry);
|
||||||
|
|
||||||
|
// Add the item class to the entry
|
||||||
|
const classNames = [ styles.item ].concat(item.value.props.className);
|
||||||
|
item.value = React.cloneElement(item.value, { className: classNames.join(' ') });
|
||||||
} else {
|
} else {
|
||||||
item = {
|
item = {
|
||||||
text: entry,
|
text: entry,
|
||||||
value: (
|
value: (
|
||||||
<MenuItem
|
<MenuItem
|
||||||
|
className={ styles.item }
|
||||||
primaryText={ entry }
|
primaryText={ entry }
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
@ -160,6 +170,7 @@ export default class AutoComplete extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
item.divider = currentDivider;
|
item.divider = currentDivider;
|
||||||
|
item.entry = entry;
|
||||||
|
|
||||||
return item;
|
return item;
|
||||||
}).filter((item) => item !== undefined);
|
}).filter((item) => item !== undefined);
|
||||||
@ -215,13 +226,8 @@ export default class AutoComplete extends Component {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { entries } = this.props;
|
const { dataSource } = this.state;
|
||||||
|
const { entry } = dataSource[idx];
|
||||||
const entriesArray = (entries instanceof Array)
|
|
||||||
? entries
|
|
||||||
: Object.values(entries);
|
|
||||||
|
|
||||||
const entry = entriesArray[idx];
|
|
||||||
|
|
||||||
this.handleOnChange(entry);
|
this.handleOnChange(entry);
|
||||||
this.setState({ entry, open: false });
|
this.setState({ entry, open: false });
|
||||||
|
@ -18,6 +18,8 @@ import React, { Component, PropTypes } from 'react';
|
|||||||
import { TextField } from 'material-ui';
|
import { TextField } from 'material-ui';
|
||||||
import { noop } from 'lodash';
|
import { noop } from 'lodash';
|
||||||
|
|
||||||
|
import { nodeOrStringProptype } from '~/util/proptypes';
|
||||||
|
|
||||||
import CopyToClipboard from '../../CopyToClipboard';
|
import CopyToClipboard from '../../CopyToClipboard';
|
||||||
|
|
||||||
import styles from './input.css';
|
import styles from './input.css';
|
||||||
@ -41,18 +43,21 @@ const NAME_ID = ' ';
|
|||||||
|
|
||||||
export default class Input extends Component {
|
export default class Input extends Component {
|
||||||
static propTypes = {
|
static propTypes = {
|
||||||
children: PropTypes.node,
|
|
||||||
className: PropTypes.string,
|
|
||||||
disabled: PropTypes.bool,
|
|
||||||
readOnly: PropTypes.bool,
|
|
||||||
allowCopy: PropTypes.oneOfType([
|
allowCopy: PropTypes.oneOfType([
|
||||||
PropTypes.string,
|
PropTypes.string,
|
||||||
PropTypes.bool
|
PropTypes.bool
|
||||||
]),
|
]),
|
||||||
floatCopy: PropTypes.bool,
|
children: PropTypes.node,
|
||||||
|
className: PropTypes.string,
|
||||||
|
disabled: PropTypes.bool,
|
||||||
error: PropTypes.string,
|
error: PropTypes.string,
|
||||||
hint: PropTypes.string,
|
readOnly: PropTypes.bool,
|
||||||
label: PropTypes.string,
|
floatCopy: PropTypes.bool,
|
||||||
|
hint: nodeOrStringProptype(),
|
||||||
|
hideUnderline: PropTypes.bool,
|
||||||
|
label: nodeOrStringProptype(),
|
||||||
|
max: PropTypes.any,
|
||||||
|
min: PropTypes.any,
|
||||||
multiLine: PropTypes.bool,
|
multiLine: PropTypes.bool,
|
||||||
onBlur: PropTypes.func,
|
onBlur: PropTypes.func,
|
||||||
onChange: PropTypes.func,
|
onChange: PropTypes.func,
|
||||||
@ -61,26 +66,26 @@ export default class Input extends Component {
|
|||||||
rows: PropTypes.number,
|
rows: PropTypes.number,
|
||||||
type: PropTypes.string,
|
type: PropTypes.string,
|
||||||
submitOnBlur: PropTypes.bool,
|
submitOnBlur: PropTypes.bool,
|
||||||
hideUnderline: PropTypes.bool,
|
style: PropTypes.object,
|
||||||
value: PropTypes.oneOfType([
|
value: PropTypes.oneOfType([
|
||||||
PropTypes.number, PropTypes.string
|
PropTypes.number,
|
||||||
]),
|
PropTypes.string
|
||||||
min: PropTypes.any,
|
])
|
||||||
max: PropTypes.any,
|
|
||||||
style: PropTypes.object
|
|
||||||
};
|
};
|
||||||
|
|
||||||
static defaultProps = {
|
static defaultProps = {
|
||||||
submitOnBlur: true,
|
|
||||||
readOnly: false,
|
|
||||||
allowCopy: false,
|
allowCopy: false,
|
||||||
hideUnderline: false,
|
hideUnderline: false,
|
||||||
floatCopy: false,
|
floatCopy: false,
|
||||||
|
readOnly: false,
|
||||||
|
submitOnBlur: true,
|
||||||
style: {}
|
style: {}
|
||||||
}
|
}
|
||||||
|
|
||||||
state = {
|
state = {
|
||||||
value: typeof this.props.value === 'undefined' ? '' : this.props.value
|
value: typeof this.props.value === 'undefined'
|
||||||
|
? ''
|
||||||
|
: this.props.value
|
||||||
}
|
}
|
||||||
|
|
||||||
componentWillReceiveProps (newProps) {
|
componentWillReceiveProps (newProps) {
|
||||||
@ -114,38 +119,29 @@ export default class Input extends Component {
|
|||||||
autoComplete='off'
|
autoComplete='off'
|
||||||
className={ className }
|
className={ className }
|
||||||
errorText={ error }
|
errorText={ error }
|
||||||
|
|
||||||
floatingLabelFixed
|
floatingLabelFixed
|
||||||
floatingLabelText={ label }
|
floatingLabelText={ label }
|
||||||
|
fullWidth
|
||||||
hintText={ hint }
|
hintText={ hint }
|
||||||
id={ NAME_ID }
|
id={ NAME_ID }
|
||||||
inputStyle={ inputStyle }
|
inputStyle={ inputStyle }
|
||||||
fullWidth
|
|
||||||
|
|
||||||
max={ max }
|
max={ max }
|
||||||
min={ min }
|
min={ min }
|
||||||
|
|
||||||
multiLine={ multiLine }
|
multiLine={ multiLine }
|
||||||
name={ NAME_ID }
|
name={ NAME_ID }
|
||||||
|
|
||||||
onBlur={ this.onBlur }
|
onBlur={ this.onBlur }
|
||||||
onChange={ this.onChange }
|
onChange={ this.onChange }
|
||||||
onKeyDown={ this.onKeyDown }
|
onKeyDown={ this.onKeyDown }
|
||||||
onPaste={ this.onPaste }
|
onPaste={ this.onPaste }
|
||||||
|
|
||||||
readOnly={ readOnly }
|
readOnly={ readOnly }
|
||||||
rows={ rows }
|
rows={ rows }
|
||||||
style={ textFieldStyle }
|
style={ textFieldStyle }
|
||||||
type={ type || 'text' }
|
type={ type || 'text' }
|
||||||
|
|
||||||
underlineDisabledStyle={ UNDERLINE_DISABLED }
|
underlineDisabledStyle={ UNDERLINE_DISABLED }
|
||||||
underlineStyle={ readOnly ? UNDERLINE_READONLY : UNDERLINE_NORMAL }
|
underlineStyle={ readOnly ? UNDERLINE_READONLY : UNDERLINE_NORMAL }
|
||||||
underlineFocusStyle={ readOnly ? { display: 'none' } : null }
|
underlineFocusStyle={ readOnly ? { display: 'none' } : null }
|
||||||
underlineShow={ !hideUnderline }
|
underlineShow={ !hideUnderline }
|
||||||
|
value={ value }>
|
||||||
value={ value }
|
|
||||||
>
|
|
||||||
{ children }
|
{ children }
|
||||||
</TextField>
|
</TextField>
|
||||||
</div>
|
</div>
|
||||||
@ -159,11 +155,14 @@ export default class Input extends Component {
|
|||||||
if (!allowCopy) {
|
if (!allowCopy) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const text = typeof allowCopy === 'string'
|
const text = typeof allowCopy === 'string'
|
||||||
? allowCopy
|
? allowCopy
|
||||||
: value;
|
: value;
|
||||||
|
|
||||||
const style = hideUnderline ? {} : { position: 'relative', top: '2px' };
|
const style = hideUnderline
|
||||||
|
? {}
|
||||||
|
: { position: 'relative', top: '2px' };
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={ styles.copy } style={ style }>
|
<div className={ styles.copy } style={ style }>
|
||||||
|
@ -18,28 +18,30 @@ import React, { Component, PropTypes } from 'react';
|
|||||||
import { connect } from 'react-redux';
|
import { connect } from 'react-redux';
|
||||||
import { bindActionCreators } from 'redux';
|
import { bindActionCreators } from 'redux';
|
||||||
|
|
||||||
import Input from '../Input';
|
|
||||||
import IdentityIcon from '../../IdentityIcon';
|
|
||||||
import util from '~/api/util';
|
import util from '~/api/util';
|
||||||
|
import { nodeOrStringProptype } from '~/util/proptypes';
|
||||||
|
|
||||||
|
import IdentityIcon from '../../IdentityIcon';
|
||||||
|
import Input from '../Input';
|
||||||
|
|
||||||
import styles from './inputAddress.css';
|
import styles from './inputAddress.css';
|
||||||
|
|
||||||
class InputAddress extends Component {
|
class InputAddress extends Component {
|
||||||
static propTypes = {
|
static propTypes = {
|
||||||
|
accountsInfo: PropTypes.object,
|
||||||
|
allowCopy: PropTypes.bool,
|
||||||
className: PropTypes.string,
|
className: PropTypes.string,
|
||||||
disabled: PropTypes.bool,
|
disabled: PropTypes.bool,
|
||||||
error: PropTypes.string,
|
error: PropTypes.string,
|
||||||
label: PropTypes.string,
|
hideUnderline: PropTypes.bool,
|
||||||
hint: PropTypes.string,
|
hint: nodeOrStringProptype(),
|
||||||
value: PropTypes.string,
|
label: nodeOrStringProptype(),
|
||||||
accountsInfo: PropTypes.object,
|
|
||||||
tokens: PropTypes.object,
|
|
||||||
text: PropTypes.bool,
|
|
||||||
onChange: PropTypes.func,
|
onChange: PropTypes.func,
|
||||||
onSubmit: PropTypes.func,
|
onSubmit: PropTypes.func,
|
||||||
hideUnderline: PropTypes.bool,
|
small: PropTypes.bool,
|
||||||
allowCopy: PropTypes.bool,
|
text: PropTypes.bool,
|
||||||
small: PropTypes.bool
|
tokens: PropTypes.object,
|
||||||
|
value: PropTypes.string
|
||||||
};
|
};
|
||||||
|
|
||||||
static defaultProps = {
|
static defaultProps = {
|
||||||
@ -49,8 +51,8 @@ class InputAddress extends Component {
|
|||||||
};
|
};
|
||||||
|
|
||||||
render () {
|
render () {
|
||||||
const { className, disabled, error, label, hint, value, text } = this.props;
|
const { className, disabled, error, hint, label, text, value } = this.props;
|
||||||
const { small, allowCopy, hideUnderline, onSubmit, accountsInfo, tokens } = this.props;
|
const { accountsInfo, allowCopy, hideUnderline, onSubmit, small, tokens } = this.props;
|
||||||
|
|
||||||
const account = accountsInfo[value] || tokens[value];
|
const account = accountsInfo[value] || tokens[value];
|
||||||
|
|
||||||
@ -68,17 +70,20 @@ class InputAddress extends Component {
|
|||||||
return (
|
return (
|
||||||
<div className={ containerClasses.join(' ') }>
|
<div className={ containerClasses.join(' ') }>
|
||||||
<Input
|
<Input
|
||||||
|
allowCopy={ allowCopy && (disabled ? value : false) }
|
||||||
className={ classes.join(' ') }
|
className={ classes.join(' ') }
|
||||||
disabled={ disabled }
|
disabled={ disabled }
|
||||||
label={ label }
|
|
||||||
hint={ hint }
|
|
||||||
error={ error }
|
error={ error }
|
||||||
value={ text && account ? account.name : value }
|
hideUnderline={ hideUnderline }
|
||||||
|
hint={ hint }
|
||||||
|
label={ label }
|
||||||
onChange={ this.handleInputChange }
|
onChange={ this.handleInputChange }
|
||||||
onSubmit={ onSubmit }
|
onSubmit={ onSubmit }
|
||||||
allowCopy={ allowCopy && (disabled ? value : false) }
|
value={
|
||||||
hideUnderline={ hideUnderline }
|
text && account
|
||||||
/>
|
? account.name
|
||||||
|
: value
|
||||||
|
} />
|
||||||
{ icon }
|
{ icon }
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@ -128,8 +133,8 @@ class InputAddress extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function mapStateToProps (state) {
|
function mapStateToProps (state) {
|
||||||
const { accountsInfo } = state.personal;
|
|
||||||
const { tokens } = state.balances;
|
const { tokens } = state.balances;
|
||||||
|
const { accountsInfo } = state.personal;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
accountsInfo,
|
accountsInfo,
|
||||||
|
@ -17,16 +17,14 @@
|
|||||||
import BigNumber from 'bignumber.js';
|
import BigNumber from 'bignumber.js';
|
||||||
import React, { Component, PropTypes } from 'react';
|
import React, { Component, PropTypes } from 'react';
|
||||||
import { connect } from 'react-redux';
|
import { connect } from 'react-redux';
|
||||||
import { bindActionCreators } from 'redux';
|
|
||||||
import CircularProgress from 'material-ui/CircularProgress';
|
import CircularProgress from 'material-ui/CircularProgress';
|
||||||
|
|
||||||
import Contracts from '~/contracts';
|
|
||||||
import { Input, InputAddress } from '../Form';
|
import { Input, InputAddress } from '../Form';
|
||||||
|
import MethodDecodingStore from './methodDecodingStore';
|
||||||
|
|
||||||
import styles from './methodDecoding.css';
|
import styles from './methodDecoding.css';
|
||||||
|
|
||||||
const ASCII_INPUT = /^[a-z0-9\s,?;.:/!()-_@'"#]+$/i;
|
const ASCII_INPUT = /^[a-z0-9\s,?;.:/!()-_@'"#]+$/i;
|
||||||
const CONTRACT_CREATE = '0x60606040';
|
|
||||||
const TOKEN_METHODS = {
|
const TOKEN_METHODS = {
|
||||||
'0xa9059cbb': 'transfer(to,value)'
|
'0xa9059cbb': 'transfer(to,value)'
|
||||||
};
|
};
|
||||||
@ -38,19 +36,17 @@ class MethodDecoding extends Component {
|
|||||||
|
|
||||||
static propTypes = {
|
static propTypes = {
|
||||||
address: PropTypes.string.isRequired,
|
address: PropTypes.string.isRequired,
|
||||||
tokens: PropTypes.object,
|
token: PropTypes.object,
|
||||||
transaction: PropTypes.object,
|
transaction: PropTypes.object,
|
||||||
historic: PropTypes.bool
|
historic: PropTypes.bool
|
||||||
}
|
}
|
||||||
|
|
||||||
state = {
|
state = {
|
||||||
contractAddress: null,
|
contractAddress: null,
|
||||||
method: null,
|
|
||||||
methodName: null,
|
methodName: null,
|
||||||
methodInputs: null,
|
methodInputs: null,
|
||||||
methodParams: null,
|
methodParams: null,
|
||||||
methodSignature: null,
|
methodSignature: null,
|
||||||
token: null,
|
|
||||||
isContract: false,
|
isContract: false,
|
||||||
isDeploy: false,
|
isDeploy: false,
|
||||||
isReceived: false,
|
isReceived: false,
|
||||||
@ -59,14 +55,29 @@ class MethodDecoding extends Component {
|
|||||||
inputType: 'auto'
|
inputType: 'auto'
|
||||||
}
|
}
|
||||||
|
|
||||||
componentWillMount () {
|
methodDecodingStore = MethodDecodingStore.get(this.context.api);
|
||||||
const lookupResult = this.lookup();
|
|
||||||
|
|
||||||
if (typeof lookupResult === 'object' && typeof lookupResult.then === 'function') {
|
componentWillMount () {
|
||||||
lookupResult.then(() => this.setState({ isLoading: false }));
|
const { address, transaction } = this.props;
|
||||||
} else {
|
|
||||||
this.setState({ isLoading: false });
|
this
|
||||||
}
|
.methodDecodingStore
|
||||||
|
.lookup(address, transaction)
|
||||||
|
.then((lookup) => {
|
||||||
|
const newState = {
|
||||||
|
methodName: lookup.name,
|
||||||
|
methodInputs: lookup.inputs,
|
||||||
|
methodParams: lookup.params,
|
||||||
|
methodSignature: lookup.signature,
|
||||||
|
|
||||||
|
isContract: lookup.contract,
|
||||||
|
isDeploy: lookup.deploy,
|
||||||
|
isLoading: false,
|
||||||
|
isReceived: lookup.received
|
||||||
|
};
|
||||||
|
|
||||||
|
this.setState(newState);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
render () {
|
render () {
|
||||||
@ -116,7 +127,8 @@ class MethodDecoding extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
renderAction () {
|
renderAction () {
|
||||||
const { methodName, methodInputs, methodSignature, token, isDeploy, isReceived, isContract } = this.state;
|
const { token } = this.props;
|
||||||
|
const { methodName, methodInputs, methodSignature, isDeploy, isReceived, isContract } = this.state;
|
||||||
|
|
||||||
if (isDeploy) {
|
if (isDeploy) {
|
||||||
return this.renderDeploy();
|
return this.renderDeploy();
|
||||||
@ -378,7 +390,7 @@ class MethodDecoding extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
renderTokenValue (value) {
|
renderTokenValue (value) {
|
||||||
const { token } = this.state;
|
const { token } = this.props;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<span className={ styles.tokenValue }>
|
<span className={ styles.tokenValue }>
|
||||||
@ -436,96 +448,18 @@ class MethodDecoding extends Component {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
lookup () {
|
|
||||||
const { transaction } = this.props;
|
|
||||||
|
|
||||||
if (!transaction) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { api } = this.context;
|
|
||||||
const { address, tokens } = this.props;
|
|
||||||
|
|
||||||
const isReceived = transaction.to === address;
|
|
||||||
const contractAddress = isReceived ? transaction.from : transaction.to;
|
|
||||||
const input = transaction.input || transaction.data;
|
|
||||||
|
|
||||||
const token = (tokens || {})[contractAddress];
|
|
||||||
this.setState({ token, isReceived, contractAddress });
|
|
||||||
|
|
||||||
if (!input || input === '0x') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { signature, paramdata } = api.util.decodeCallData(input);
|
|
||||||
this.setState({ methodSignature: signature, methodParams: paramdata });
|
|
||||||
|
|
||||||
if (!signature || signature === CONTRACT_CREATE || transaction.creates) {
|
|
||||||
this.setState({ isDeploy: true });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (contractAddress === '0x') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
return api.eth
|
|
||||||
.getCode(contractAddress || transaction.creates)
|
|
||||||
.then((bytecode) => {
|
|
||||||
const isContract = bytecode && /^(0x)?([0]*[1-9a-f]+[0]*)+$/.test(bytecode);
|
|
||||||
|
|
||||||
this.setState({ isContract });
|
|
||||||
|
|
||||||
if (!isContract) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
return Contracts.get()
|
|
||||||
.signatureReg
|
|
||||||
.lookup(signature)
|
|
||||||
.then((method) => {
|
|
||||||
let methodInputs = null;
|
|
||||||
let methodName = null;
|
|
||||||
|
|
||||||
if (method && method.length) {
|
|
||||||
const { methodParams } = this.state;
|
|
||||||
const abi = api.util.methodToAbi(method);
|
|
||||||
|
|
||||||
methodName = abi.name;
|
|
||||||
methodInputs = api.util
|
|
||||||
.decodeMethodInput(abi, methodParams)
|
|
||||||
.map((value, index) => {
|
|
||||||
const type = abi.inputs[index].type;
|
|
||||||
|
|
||||||
return { type, value };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
this.setState({
|
|
||||||
method,
|
|
||||||
methodName,
|
|
||||||
methodInputs,
|
|
||||||
bytecode
|
|
||||||
});
|
|
||||||
});
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
console.warn('lookup', error);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function mapStateToProps (state) {
|
function mapStateToProps (initState, initProps) {
|
||||||
const { tokens } = state.balances;
|
const { tokens } = initState.balances;
|
||||||
|
const { address } = initProps;
|
||||||
|
|
||||||
return { tokens };
|
const token = (tokens || {})[address];
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
return { token };
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function mapDispatchToProps (dispatch) {
|
|
||||||
return bindActionCreators({}, dispatch);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default connect(
|
export default connect(
|
||||||
mapStateToProps,
|
mapStateToProps
|
||||||
mapDispatchToProps
|
|
||||||
)(MethodDecoding);
|
)(MethodDecoding);
|
||||||
|
216
js/src/ui/MethodDecoding/methodDecodingStore.js
Normal file
216
js/src/ui/MethodDecoding/methodDecodingStore.js
Normal file
@ -0,0 +1,216 @@
|
|||||||
|
// 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 Contracts from '~/contracts';
|
||||||
|
import Abi from '~/abi';
|
||||||
|
import * as abis from '~/contracts/abi';
|
||||||
|
|
||||||
|
const CONTRACT_CREATE = '0x60606040';
|
||||||
|
|
||||||
|
let instance = null;
|
||||||
|
|
||||||
|
export default class MethodDecodingStore {
|
||||||
|
|
||||||
|
api = null;
|
||||||
|
|
||||||
|
_isContract = {};
|
||||||
|
_methods = {};
|
||||||
|
|
||||||
|
constructor (api, contracts = {}) {
|
||||||
|
this.api = api;
|
||||||
|
|
||||||
|
// Load the signatures from the local ABIs
|
||||||
|
Object.keys(abis).forEach((abiKey) => {
|
||||||
|
this.loadFromAbi(abis[abiKey]);
|
||||||
|
});
|
||||||
|
|
||||||
|
this.addContracts(contracts);
|
||||||
|
}
|
||||||
|
|
||||||
|
addContracts (contracts = {}) {
|
||||||
|
// Load the User defined contracts
|
||||||
|
Object.values(contracts).forEach((contract) => {
|
||||||
|
if (!contract || !contract.meta || !contract.meta.abi) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.loadFromAbi(contract.meta.abi);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
loadFromAbi (_abi) {
|
||||||
|
const abi = new Abi(_abi);
|
||||||
|
abi
|
||||||
|
.functions
|
||||||
|
.map((f) => ({ sign: f.signature, abi: f.abi }))
|
||||||
|
.forEach((mapping) => {
|
||||||
|
const sign = (/^0x/.test(mapping.sign) ? '' : '0x') + mapping.sign;
|
||||||
|
this._methods[sign] = mapping.abi;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
static get (api, contracts = {}) {
|
||||||
|
if (!instance) {
|
||||||
|
instance = new MethodDecodingStore(api, contracts);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set API if not set yet
|
||||||
|
if (!instance.api) {
|
||||||
|
instance.api = api;
|
||||||
|
}
|
||||||
|
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
static loadContracts (contracts = {}) {
|
||||||
|
if (!instance) {
|
||||||
|
// Just create the instance with null API
|
||||||
|
MethodDecodingStore.get(null, contracts);
|
||||||
|
} else {
|
||||||
|
instance.addContracts(contracts);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Looks up a transaction in the context of the given
|
||||||
|
* address
|
||||||
|
*
|
||||||
|
* @param {String} address The address contract
|
||||||
|
* @param {Object} transaction The transaction to lookup
|
||||||
|
* @return {Promise} The result of the lookup. Resolves with:
|
||||||
|
* {
|
||||||
|
* contract: Boolean,
|
||||||
|
* deploy: Boolean,
|
||||||
|
* inputs: Array,
|
||||||
|
* name: String,
|
||||||
|
* params: Array,
|
||||||
|
* received: Boolean,
|
||||||
|
* signature: String
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
lookup (address, transaction) {
|
||||||
|
const result = {};
|
||||||
|
|
||||||
|
if (!transaction) {
|
||||||
|
return Promise.resolve(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
const isReceived = transaction.to === address;
|
||||||
|
const contractAddress = isReceived ? transaction.from : transaction.to;
|
||||||
|
const input = transaction.input || transaction.data;
|
||||||
|
|
||||||
|
result.received = isReceived;
|
||||||
|
|
||||||
|
// No input, should be a ETH transfer
|
||||||
|
if (!input || input === '0x') {
|
||||||
|
return Promise.resolve(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { signature, paramdata } = this.api.util.decodeCallData(input);
|
||||||
|
result.signature = signature;
|
||||||
|
result.params = paramdata;
|
||||||
|
|
||||||
|
// Contract deployment
|
||||||
|
if (!signature || signature === CONTRACT_CREATE || transaction.creates) {
|
||||||
|
return Promise.resolve({ ...result, deploy: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
return this
|
||||||
|
.isContract(contractAddress || transaction.creates)
|
||||||
|
.then((isContract) => {
|
||||||
|
result.contract = isContract;
|
||||||
|
|
||||||
|
if (!isContract) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
return this
|
||||||
|
.fetchMethodAbi(signature)
|
||||||
|
.then((abi) => {
|
||||||
|
let methodName = null;
|
||||||
|
let methodInputs = null;
|
||||||
|
|
||||||
|
if (abi) {
|
||||||
|
methodName = abi.name;
|
||||||
|
methodInputs = this.api.util
|
||||||
|
.decodeMethodInput(abi, paramdata)
|
||||||
|
.map((value, index) => {
|
||||||
|
const type = abi.inputs[index].type;
|
||||||
|
return { type, value };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...result,
|
||||||
|
name: methodName,
|
||||||
|
inputs: methodInputs
|
||||||
|
};
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.warn('lookup', error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchMethodAbi (signature) {
|
||||||
|
if (this._methods[signature] !== undefined) {
|
||||||
|
return Promise.resolve(this._methods[signature]);
|
||||||
|
}
|
||||||
|
|
||||||
|
this._methods[signature] = Contracts.get()
|
||||||
|
.signatureReg
|
||||||
|
.lookup(signature)
|
||||||
|
.then((method) => {
|
||||||
|
let abi = null;
|
||||||
|
|
||||||
|
if (method && method.length) {
|
||||||
|
abi = this.api.util.methodToAbi(method);
|
||||||
|
}
|
||||||
|
|
||||||
|
this._methods[signature] = abi;
|
||||||
|
return this._methods[signature];
|
||||||
|
});
|
||||||
|
|
||||||
|
return Promise.resolve(this._methods[signature]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks (and caches) if the given address is a
|
||||||
|
* Contract or not, from its fetched bytecode
|
||||||
|
*/
|
||||||
|
isContract (contractAddress) {
|
||||||
|
// If zero address, it isn't a contract
|
||||||
|
if (/^(0x)?0*$/.test(contractAddress)) {
|
||||||
|
return Promise.resolve(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this._isContract[contractAddress]) {
|
||||||
|
return Promise.resolve(this._isContract[contractAddress]);
|
||||||
|
}
|
||||||
|
|
||||||
|
this._isContract[contractAddress] = this.api.eth
|
||||||
|
.getCode(contractAddress)
|
||||||
|
.then((bytecode) => {
|
||||||
|
// Is a contract if the address contains *valid* bytecode
|
||||||
|
const _isContract = bytecode && /^(0x)?([0]*[1-9a-f]+[0]*)+$/.test(bytecode);
|
||||||
|
|
||||||
|
this._isContract[contractAddress] = _isContract;
|
||||||
|
return this._isContract[contractAddress];
|
||||||
|
});
|
||||||
|
|
||||||
|
return Promise.resolve(this._isContract[contractAddress]);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -55,21 +55,21 @@ class Modal extends Component {
|
|||||||
const contentStyle = muiTheme.parity.getBackgroundStyle(null, settings.backgroundSeed);
|
const contentStyle = muiTheme.parity.getBackgroundStyle(null, settings.backgroundSeed);
|
||||||
const header = (
|
const header = (
|
||||||
<Title
|
<Title
|
||||||
current={ current }
|
|
||||||
busy={ busy }
|
busy={ busy }
|
||||||
waiting={ waiting }
|
current={ current }
|
||||||
steps={ steps }
|
steps={ steps }
|
||||||
title={ title } />
|
title={ title }
|
||||||
|
waiting={ waiting } />
|
||||||
);
|
);
|
||||||
const classes = `${styles.dialog} ${className}`;
|
const classes = `${styles.dialog} ${className}`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog
|
<Dialog
|
||||||
actions={ actions }
|
actions={ actions }
|
||||||
|
actionsContainerClassName={ styles.actions }
|
||||||
actionsContainerStyle={ ACTIONS_STYLE }
|
actionsContainerStyle={ ACTIONS_STYLE }
|
||||||
autoDetectWindowHeight={ false }
|
autoDetectWindowHeight={ false }
|
||||||
autoScrollBodyContent
|
autoScrollBodyContent
|
||||||
actionsContainerClassName={ styles.actions }
|
|
||||||
bodyClassName={ styles.body }
|
bodyClassName={ styles.body }
|
||||||
className={ classes }
|
className={ classes }
|
||||||
contentClassName={ styles.content }
|
contentClassName={ styles.content }
|
||||||
@ -82,7 +82,12 @@ class Modal extends Component {
|
|||||||
style={ DIALOG_STYLE }
|
style={ DIALOG_STYLE }
|
||||||
title={ header }
|
title={ header }
|
||||||
titleStyle={ TITLE_STYLE }>
|
titleStyle={ TITLE_STYLE }>
|
||||||
<Container light compact={ compact } style={ { transition: 'none' } }>
|
<Container
|
||||||
|
compact={ compact }
|
||||||
|
light
|
||||||
|
style={
|
||||||
|
{ transition: 'none' }
|
||||||
|
}>
|
||||||
{ children }
|
{ children }
|
||||||
</Container>
|
</Container>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
208
js/src/util/dapps.js
Normal file
208
js/src/util/dapps.js
Normal file
@ -0,0 +1,208 @@
|
|||||||
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
|
||||||
|
// This file is part of Parity.
|
||||||
|
|
||||||
|
// Parity is free software: you can redistribute it and/or modify
|
||||||
|
// it under the terms of the GNU General Public License as published by
|
||||||
|
// the Free Software Foundation, either version 3 of the License, or
|
||||||
|
// (at your option) any later version.
|
||||||
|
|
||||||
|
// Parity is distributed in the hope that it will be useful,
|
||||||
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
// GNU General Public License for more details.
|
||||||
|
|
||||||
|
// You should have received a copy of the GNU General Public License
|
||||||
|
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import BigNumber from 'bignumber.js';
|
||||||
|
import { pick, range, uniq } from 'lodash';
|
||||||
|
|
||||||
|
import Contracts from '~/contracts';
|
||||||
|
import { hashToImageUrl } from '~/redux/util';
|
||||||
|
import { bytesToHex } from '~/api/util/format';
|
||||||
|
|
||||||
|
import builtinApps from '~/views/Dapps/builtin.json';
|
||||||
|
|
||||||
|
function getHost (api) {
|
||||||
|
const host = process.env.DAPPS_URL ||
|
||||||
|
(
|
||||||
|
process.env.NODE_ENV === 'production'
|
||||||
|
? api.dappsUrl
|
||||||
|
: ''
|
||||||
|
);
|
||||||
|
|
||||||
|
if (host === '/') {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
return host;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscribeToChanges (api, dappReg, callback) {
|
||||||
|
return dappReg
|
||||||
|
.getContract()
|
||||||
|
.then((dappRegContract) => {
|
||||||
|
const dappRegInstance = dappRegContract.instance;
|
||||||
|
|
||||||
|
const signatures = ['MetaChanged', 'OwnerChanged', 'Registered']
|
||||||
|
.map((event) => dappRegInstance[event].signature);
|
||||||
|
|
||||||
|
return api.eth
|
||||||
|
.newFilter({
|
||||||
|
fromBlock: '0',
|
||||||
|
toBlock: 'latest',
|
||||||
|
address: dappRegInstance.address,
|
||||||
|
topics: [ signatures ]
|
||||||
|
})
|
||||||
|
.then((filterId) => {
|
||||||
|
return api
|
||||||
|
.subscribe('eth_blockNumber', () => {
|
||||||
|
if (filterId > -1) {
|
||||||
|
api.eth
|
||||||
|
.getFilterChanges(filterId)
|
||||||
|
.then((logs) => {
|
||||||
|
return dappRegContract.parseEventLogs(logs);
|
||||||
|
})
|
||||||
|
.then((events) => {
|
||||||
|
if (events.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return uniq IDs which changed meta-data
|
||||||
|
const ids = uniq(events.map((event) => bytesToHex(event.params.id.value)));
|
||||||
|
callback(ids);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then((blockSubId) => {
|
||||||
|
return {
|
||||||
|
block: blockSubId,
|
||||||
|
filter: filterId
|
||||||
|
};
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fetchBuiltinApps () {
|
||||||
|
const { dappReg } = Contracts.get();
|
||||||
|
|
||||||
|
return Promise
|
||||||
|
.all(builtinApps.map((app) => dappReg.getImage(app.id)))
|
||||||
|
.then((imageIds) => {
|
||||||
|
return builtinApps.map((app, index) => {
|
||||||
|
app.type = 'builtin';
|
||||||
|
app.image = hashToImageUrl(imageIds[index]);
|
||||||
|
return app;
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.warn('DappsStore:fetchBuiltinApps', error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fetchLocalApps (api) {
|
||||||
|
return fetch(`${getHost(api)}/api/apps`)
|
||||||
|
.then((response) => {
|
||||||
|
return response.ok
|
||||||
|
? response.json()
|
||||||
|
: [];
|
||||||
|
})
|
||||||
|
.then((apps) => {
|
||||||
|
return apps
|
||||||
|
.map((app) => {
|
||||||
|
app.type = 'local';
|
||||||
|
app.visible = true;
|
||||||
|
return app;
|
||||||
|
})
|
||||||
|
.filter((app) => app.id && !['ui'].includes(app.id));
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.warn('DappsStore:fetchLocal', error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fetchRegistryAppIds () {
|
||||||
|
const { dappReg } = Contracts.get();
|
||||||
|
|
||||||
|
return dappReg
|
||||||
|
.count()
|
||||||
|
.then((count) => {
|
||||||
|
const promises = range(0, count.toNumber()).map((index) => dappReg.at(index));
|
||||||
|
return Promise.all(promises);
|
||||||
|
})
|
||||||
|
.then((appsInfo) => {
|
||||||
|
const appIds = appsInfo
|
||||||
|
.map(([appId, owner]) => bytesToHex(appId))
|
||||||
|
.filter((appId) => {
|
||||||
|
return (new BigNumber(appId)).gt(0) && !builtinApps.find((app) => app.id === appId);
|
||||||
|
});
|
||||||
|
|
||||||
|
return appIds;
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.warn('DappsStore:fetchRegistryAppIds', error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fetchRegistryApp (api, dappReg, appId) {
|
||||||
|
return Promise
|
||||||
|
.all([
|
||||||
|
dappReg.getImage(appId),
|
||||||
|
dappReg.getContent(appId),
|
||||||
|
dappReg.getManifest(appId)
|
||||||
|
])
|
||||||
|
.then(([ imageId, contentId, manifestId ]) => {
|
||||||
|
const app = {
|
||||||
|
id: appId,
|
||||||
|
image: hashToImageUrl(imageId),
|
||||||
|
contentHash: bytesToHex(contentId).substr(2),
|
||||||
|
manifestHash: bytesToHex(manifestId).substr(2),
|
||||||
|
type: 'network',
|
||||||
|
visible: true
|
||||||
|
};
|
||||||
|
|
||||||
|
return fetchManifest(api, app.manifestHash)
|
||||||
|
.then((manifest) => {
|
||||||
|
if (manifest) {
|
||||||
|
app.manifestHash = null;
|
||||||
|
|
||||||
|
// Add usefull manifest fields to app
|
||||||
|
Object.assign(app, pick(manifest, ['author', 'description', 'name', 'version']));
|
||||||
|
}
|
||||||
|
|
||||||
|
return app;
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.then((app) => {
|
||||||
|
// Keep dapps that has a Manifest File and an Id
|
||||||
|
const dapp = (app.manifestHash || !app.id) ? null : app;
|
||||||
|
return dapp;
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.warn('DappsStore:fetchRegistryApp', error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fetchManifest (api, manifestHash) {
|
||||||
|
if (/^(0x)?0+/.test(manifestHash)) {
|
||||||
|
return Promise.resolve(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
return fetch(
|
||||||
|
`${getHost(api)}/api/content/${manifestHash}/`,
|
||||||
|
{ redirect: 'follow', mode: 'cors' }
|
||||||
|
)
|
||||||
|
.then((response) => {
|
||||||
|
return response.ok
|
||||||
|
? response.json()
|
||||||
|
: null;
|
||||||
|
})
|
||||||
|
.then((manifest) => {
|
||||||
|
return manifest;
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.warn('DappsStore:fetchManifest', error);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
@ -19,7 +19,7 @@ import { connect } from 'react-redux';
|
|||||||
import { bindActionCreators } from 'redux';
|
import { bindActionCreators } from 'redux';
|
||||||
|
|
||||||
import etherscan from '~/3rdparty/etherscan';
|
import etherscan from '~/3rdparty/etherscan';
|
||||||
import { Container, TxList } from '~/ui';
|
import { Container, TxList, Loading } from '~/ui';
|
||||||
|
|
||||||
import styles from './transactions.css';
|
import styles from './transactions.css';
|
||||||
|
|
||||||
@ -60,19 +60,32 @@ class Transactions extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
render () {
|
render () {
|
||||||
const { address } = this.props;
|
|
||||||
const { hashes } = this.state;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container title='transactions'>
|
<Container title='transactions'>
|
||||||
<TxList
|
{ this.renderTransactionList() }
|
||||||
address={ address }
|
|
||||||
hashes={ hashes } />
|
|
||||||
{ this.renderEtherscanFooter() }
|
{ this.renderEtherscanFooter() }
|
||||||
</Container>
|
</Container>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
renderTransactionList () {
|
||||||
|
const { address } = this.props;
|
||||||
|
const { hashes, loading } = this.state;
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<Loading />
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<TxList
|
||||||
|
address={ address }
|
||||||
|
hashes={ hashes }
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
renderEtherscanFooter () {
|
renderEtherscanFooter () {
|
||||||
const { traceMode } = this.props;
|
const { traceMode } = this.props;
|
||||||
|
|
||||||
|
@ -31,7 +31,7 @@ export default class Dapp extends Component {
|
|||||||
params: PropTypes.object
|
params: PropTypes.object
|
||||||
};
|
};
|
||||||
|
|
||||||
store = new DappsStore(this.context.api);
|
store = DappsStore.get(this.context.api);
|
||||||
|
|
||||||
render () {
|
render () {
|
||||||
const { dappsUrl } = this.context.api;
|
const { dappsUrl } = this.context.api;
|
||||||
|
@ -36,7 +36,7 @@ export default class Dapps extends Component {
|
|||||||
api: PropTypes.object.isRequired
|
api: PropTypes.object.isRequired
|
||||||
}
|
}
|
||||||
|
|
||||||
store = new DappsStore(this.context.api);
|
store = DappsStore.get(this.context.api);
|
||||||
|
|
||||||
render () {
|
render () {
|
||||||
let externalOverlay = null;
|
let externalOverlay = null;
|
||||||
|
@ -14,17 +14,21 @@
|
|||||||
// 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 BigNumber from 'bignumber.js';
|
|
||||||
import { action, computed, observable, transaction } from 'mobx';
|
import { action, computed, observable, transaction } from 'mobx';
|
||||||
import store from 'store';
|
import store from 'store';
|
||||||
|
|
||||||
import Contracts from '~/contracts';
|
import Contracts from '~/contracts';
|
||||||
import { hashToImageUrl } from '~/redux/util';
|
import {
|
||||||
|
fetchBuiltinApps, fetchLocalApps,
|
||||||
import builtinApps from './builtin.json';
|
fetchRegistryAppIds, fetchRegistryApp,
|
||||||
|
subscribeToChanges
|
||||||
|
} from '~/util/dapps';
|
||||||
|
|
||||||
const LS_KEY_DISPLAY = 'displayApps';
|
const LS_KEY_DISPLAY = 'displayApps';
|
||||||
const LS_KEY_EXTERNAL_ACCEPT = 'acceptExternal';
|
const LS_KEY_EXTERNAL_ACCEPT = 'acceptExternal';
|
||||||
|
const BUILTIN_APPS_KEY = 'BUILTIN_APPS_KEY';
|
||||||
|
|
||||||
|
let instance = null;
|
||||||
|
|
||||||
export default class DappsStore {
|
export default class DappsStore {
|
||||||
@observable apps = [];
|
@observable apps = [];
|
||||||
@ -32,23 +36,138 @@ export default class DappsStore {
|
|||||||
@observable modalOpen = false;
|
@observable modalOpen = false;
|
||||||
@observable externalOverlayVisible = true;
|
@observable externalOverlayVisible = true;
|
||||||
|
|
||||||
|
_api = null;
|
||||||
|
_subscriptions = {};
|
||||||
|
|
||||||
|
_cachedApps = {};
|
||||||
_manifests = {};
|
_manifests = {};
|
||||||
|
_registryAppsIds = null;
|
||||||
|
|
||||||
constructor (api) {
|
constructor (api) {
|
||||||
this._api = api;
|
this._api = api;
|
||||||
|
|
||||||
this.loadExternalOverlay();
|
this.loadExternalOverlay();
|
||||||
this.readDisplayApps();
|
this.loadApps();
|
||||||
|
this.subscribeToChanges();
|
||||||
|
}
|
||||||
|
|
||||||
|
loadApps () {
|
||||||
|
const { dappReg } = Contracts.get();
|
||||||
|
|
||||||
Promise
|
Promise
|
||||||
.all([
|
.all([
|
||||||
this._fetchBuiltinApps(),
|
this.fetchBuiltinApps().then((apps) => this.addApps(apps)),
|
||||||
this._fetchLocalApps(),
|
this.fetchLocalApps().then((apps) => this.addApps(apps)),
|
||||||
this._fetchRegistryApps()
|
this.fetchRegistryApps(dappReg).then((apps) => this.addApps(apps))
|
||||||
])
|
])
|
||||||
.then(this.writeDisplayApps);
|
.then(this.writeDisplayApps);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static get (api) {
|
||||||
|
if (!instance) {
|
||||||
|
instance = new DappsStore(api);
|
||||||
|
} else {
|
||||||
|
instance.loadApps();
|
||||||
|
}
|
||||||
|
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
subscribeToChanges () {
|
||||||
|
const { dappReg } = Contracts.get();
|
||||||
|
|
||||||
|
// Unsubscribe from previous subscriptions, if any
|
||||||
|
if (this._subscriptions.block) {
|
||||||
|
this._api.unsubscribe(this._subscriptions.block);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this._subscriptions.filter) {
|
||||||
|
this._api.eth.uninstallFilter(this._subscriptions.filter);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Subscribe to dapps reg changes
|
||||||
|
subscribeToChanges(this._api, dappReg, (appIds) => {
|
||||||
|
const updates = appIds.map((appId) => {
|
||||||
|
return this.fetchRegistryApp(dappReg, appId, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
Promise
|
||||||
|
.all(updates)
|
||||||
|
.then((apps) => {
|
||||||
|
this.addApps(apps);
|
||||||
|
});
|
||||||
|
}).then((subscriptions) => {
|
||||||
|
this._subscriptions = subscriptions;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchBuiltinApps (force = false) {
|
||||||
|
if (!force && this._cachedApps[BUILTIN_APPS_KEY] !== undefined) {
|
||||||
|
return Promise.resolve(this._cachedApps[BUILTIN_APPS_KEY]);
|
||||||
|
}
|
||||||
|
|
||||||
|
this._cachedApps[BUILTIN_APPS_KEY] = fetchBuiltinApps()
|
||||||
|
.then((apps) => {
|
||||||
|
this._cachedApps[BUILTIN_APPS_KEY] = apps;
|
||||||
|
return apps;
|
||||||
|
});
|
||||||
|
|
||||||
|
return Promise.resolve(this._cachedApps[BUILTIN_APPS_KEY]);
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchLocalApps () {
|
||||||
|
return fetchLocalApps(this._api);
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchRegistryAppIds (force = false) {
|
||||||
|
if (!force && this._registryAppsIds) {
|
||||||
|
return Promise.resolve(this._registryAppsIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
this._registryAppsIds = fetchRegistryAppIds()
|
||||||
|
.then((appIds) => {
|
||||||
|
this._registryAppsIds = appIds;
|
||||||
|
return this._registryAppsIds;
|
||||||
|
});
|
||||||
|
|
||||||
|
return Promise.resolve(this._registryAppsIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchRegistryApp (dappReg, appId, force = false) {
|
||||||
|
if (!force && this._cachedApps[appId] !== undefined) {
|
||||||
|
return Promise.resolve(this._cachedApps[appId]);
|
||||||
|
}
|
||||||
|
|
||||||
|
this._cachedApps[appId] = fetchRegistryApp(this._api, dappReg, appId)
|
||||||
|
.then((dapp) => {
|
||||||
|
this._cachedApps[appId] = dapp;
|
||||||
|
return dapp;
|
||||||
|
});
|
||||||
|
|
||||||
|
return Promise.resolve(this._cachedApps[appId]);
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchRegistryApps (dappReg) {
|
||||||
|
return this
|
||||||
|
.fetchRegistryAppIds()
|
||||||
|
.then((appIds) => {
|
||||||
|
const promises = appIds.map((appId) => {
|
||||||
|
// Fetch the Dapp and display it ASAP
|
||||||
|
return this
|
||||||
|
.fetchRegistryApp(dappReg, appId)
|
||||||
|
.then((app) => {
|
||||||
|
if (app) {
|
||||||
|
this.addApps([ app ]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return app;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return Promise.all(promises);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
@computed get sortedBuiltin () {
|
@computed get sortedBuiltin () {
|
||||||
return this.apps.filter((app) => app.type === 'builtin');
|
return this.apps.filter((app) => app.type === 'builtin');
|
||||||
}
|
}
|
||||||
@ -112,9 +231,17 @@ export default class DappsStore {
|
|||||||
store.set(LS_KEY_DISPLAY, this.displayApps);
|
store.set(LS_KEY_DISPLAY, this.displayApps);
|
||||||
}
|
}
|
||||||
|
|
||||||
@action addApps = (apps) => {
|
@action addApps = (_apps) => {
|
||||||
transaction(() => {
|
transaction(() => {
|
||||||
|
const apps = _apps.filter((app) => app);
|
||||||
|
|
||||||
|
// Get new apps IDs if available
|
||||||
|
const newAppsIds = apps
|
||||||
|
.map((app) => app.id)
|
||||||
|
.filter((id) => id);
|
||||||
|
|
||||||
this.apps = this.apps
|
this.apps = this.apps
|
||||||
|
.filter((app) => !app.id || !newAppsIds.includes(app.id))
|
||||||
.concat(apps || [])
|
.concat(apps || [])
|
||||||
.sort((a, b) => a.name.localeCompare(b.name));
|
.sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
|
||||||
@ -128,159 +255,4 @@ export default class DappsStore {
|
|||||||
this.displayApps = Object.assign({}, this.displayApps, visibility);
|
this.displayApps = Object.assign({}, this.displayApps, visibility);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
_getHost (api) {
|
|
||||||
const host = process.env.DAPPS_URL || (process.env.NODE_ENV === 'production'
|
|
||||||
? this._api.dappsUrl
|
|
||||||
: '');
|
|
||||||
|
|
||||||
if (host === '/') {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
|
|
||||||
return host;
|
|
||||||
}
|
|
||||||
|
|
||||||
_fetchBuiltinApps () {
|
|
||||||
const { dappReg } = Contracts.get();
|
|
||||||
|
|
||||||
return Promise
|
|
||||||
.all(builtinApps.map((app) => dappReg.getImage(app.id)))
|
|
||||||
.then((imageIds) => {
|
|
||||||
this.addApps(
|
|
||||||
builtinApps.map((app, index) => {
|
|
||||||
app.type = 'builtin';
|
|
||||||
app.image = hashToImageUrl(imageIds[index]);
|
|
||||||
return app;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
console.warn('DappsStore:fetchBuiltinApps', error);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
_fetchLocalApps () {
|
|
||||||
return fetch(`${this._getHost()}/api/apps`)
|
|
||||||
.then((response) => {
|
|
||||||
return response.ok
|
|
||||||
? response.json()
|
|
||||||
: [];
|
|
||||||
})
|
|
||||||
.then((apps) => {
|
|
||||||
return apps
|
|
||||||
.map((app) => {
|
|
||||||
app.type = 'local';
|
|
||||||
app.visible = true;
|
|
||||||
return app;
|
|
||||||
})
|
|
||||||
.filter((app) => app.id && !['ui'].includes(app.id));
|
|
||||||
})
|
|
||||||
.then(this.addApps)
|
|
||||||
.catch((error) => {
|
|
||||||
console.warn('DappsStore:fetchLocal', error);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
_fetchRegistryApps () {
|
|
||||||
const { dappReg } = Contracts.get();
|
|
||||||
|
|
||||||
return dappReg
|
|
||||||
.count()
|
|
||||||
.then((_count) => {
|
|
||||||
const count = _count.toNumber();
|
|
||||||
const promises = [];
|
|
||||||
|
|
||||||
for (let index = 0; index < count; index++) {
|
|
||||||
promises.push(dappReg.at(index));
|
|
||||||
}
|
|
||||||
|
|
||||||
return Promise.all(promises);
|
|
||||||
})
|
|
||||||
.then((appsInfo) => {
|
|
||||||
const appIds = appsInfo
|
|
||||||
.map(([appId, owner]) => this._api.util.bytesToHex(appId))
|
|
||||||
.filter((appId) => {
|
|
||||||
return (new BigNumber(appId)).gt(0) && !builtinApps.find((app) => app.id === appId);
|
|
||||||
});
|
|
||||||
|
|
||||||
return Promise
|
|
||||||
.all([
|
|
||||||
Promise.all(appIds.map((appId) => dappReg.getImage(appId))),
|
|
||||||
Promise.all(appIds.map((appId) => dappReg.getContent(appId))),
|
|
||||||
Promise.all(appIds.map((appId) => dappReg.getManifest(appId)))
|
|
||||||
])
|
|
||||||
.then(([imageIds, contentIds, manifestIds]) => {
|
|
||||||
return appIds.map((appId, index) => {
|
|
||||||
const app = {
|
|
||||||
id: appId,
|
|
||||||
image: hashToImageUrl(imageIds[index]),
|
|
||||||
contentHash: this._api.util.bytesToHex(contentIds[index]).substr(2),
|
|
||||||
manifestHash: this._api.util.bytesToHex(manifestIds[index]).substr(2),
|
|
||||||
type: 'network',
|
|
||||||
visible: true
|
|
||||||
};
|
|
||||||
|
|
||||||
return app;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
})
|
|
||||||
.then((apps) => {
|
|
||||||
return Promise
|
|
||||||
.all(apps.map((app) => this._fetchManifest(app.manifestHash)))
|
|
||||||
.then((manifests) => {
|
|
||||||
return apps.map((app, index) => {
|
|
||||||
const manifest = manifests[index];
|
|
||||||
|
|
||||||
if (manifest) {
|
|
||||||
app.manifestHash = null;
|
|
||||||
Object.keys(manifest)
|
|
||||||
.filter((key) => ['author', 'description', 'name', 'version'].includes(key))
|
|
||||||
.forEach((key) => {
|
|
||||||
app[key] = manifest[key];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return app;
|
|
||||||
});
|
|
||||||
})
|
|
||||||
.then((apps) => {
|
|
||||||
return apps.filter((app) => {
|
|
||||||
return !app.manifestHash && app.id;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
})
|
|
||||||
.then(this.addApps)
|
|
||||||
.catch((error) => {
|
|
||||||
console.warn('DappsStore:fetchRegistry', error);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
_fetchManifest (manifestHash) {
|
|
||||||
if (/^(0x)?0+/.test(manifestHash)) {
|
|
||||||
return Promise.resolve(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this._manifests[manifestHash]) {
|
|
||||||
return Promise.resolve(this._manifests[manifestHash]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return fetch(`${this._getHost()}/api/content/${manifestHash}/`, { redirect: 'follow', mode: 'cors' })
|
|
||||||
.then((response) => {
|
|
||||||
return response.ok
|
|
||||||
? response.json()
|
|
||||||
: null;
|
|
||||||
})
|
|
||||||
.then((manifest) => {
|
|
||||||
if (manifest) {
|
|
||||||
this._manifests[manifestHash] = manifest;
|
|
||||||
}
|
|
||||||
|
|
||||||
return manifest;
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
console.warn('DappsStore:fetchManifest', error);
|
|
||||||
return null;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -32,6 +32,10 @@
|
|||||||
flex: 1;
|
flex: 1;
|
||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
|
|
||||||
|
// Fallback for browsers not supporting `calc`
|
||||||
|
min-height: 90vh;
|
||||||
|
min-height: calc(100vh - 8em);
|
||||||
|
|
||||||
> * {
|
> * {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
|
|
||||||
|
@ -15,11 +15,13 @@
|
|||||||
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
import 'isomorphic-fetch';
|
import 'isomorphic-fetch';
|
||||||
|
import 'mock-local-storage';
|
||||||
|
|
||||||
import es6Promise from 'es6-promise';
|
import es6Promise from 'es6-promise';
|
||||||
es6Promise.polyfill();
|
es6Promise.polyfill();
|
||||||
|
|
||||||
import 'mock-local-storage';
|
import injectTapEventPlugin from 'react-tap-event-plugin';
|
||||||
|
injectTapEventPlugin();
|
||||||
|
|
||||||
import chai from 'chai';
|
import chai from 'chai';
|
||||||
import chaiAsPromised from 'chai-as-promised';
|
import chaiAsPromised from 'chai-as-promised';
|
||||||
|
@ -18,7 +18,7 @@
|
|||||||
|
|
||||||
use std::sync::{Arc, Weak};
|
use std::sync::{Arc, Weak};
|
||||||
use transient_hashmap::TransientHashMap;
|
use transient_hashmap::TransientHashMap;
|
||||||
use util::{U256, Mutex};
|
use util::{U256, Mutex, Hashable};
|
||||||
|
|
||||||
use ethcore::account_provider::AccountProvider;
|
use ethcore::account_provider::AccountProvider;
|
||||||
use ethcore::miner::MinerService;
|
use ethcore::miner::MinerService;
|
||||||
@ -180,7 +180,8 @@ impl<C: 'static, M: 'static> EthSigning for SigningQueueClient<C, M> where
|
|||||||
C: MiningBlockChainClient,
|
C: MiningBlockChainClient,
|
||||||
M: MinerService,
|
M: MinerService,
|
||||||
{
|
{
|
||||||
fn sign(&self, ready: Ready<RpcH520>, address: RpcH160, hash: RpcH256) {
|
fn sign(&self, ready: Ready<RpcH520>, address: RpcH160, data: RpcBytes) {
|
||||||
|
let hash = data.0.sha3().into();
|
||||||
let res = self.active().and_then(|_| self.dispatch(RpcConfirmationPayload::Signature((address, hash).into())));
|
let res = self.active().and_then(|_| self.dispatch(RpcConfirmationPayload::Signature((address, hash).into())));
|
||||||
self.handle_dispatch(res, |response| {
|
self.handle_dispatch(res, |response| {
|
||||||
match response {
|
match response {
|
||||||
|
@ -17,6 +17,7 @@
|
|||||||
//! Unsafe Signing RPC implementation.
|
//! Unsafe Signing RPC implementation.
|
||||||
|
|
||||||
use std::sync::{Arc, Weak};
|
use std::sync::{Arc, Weak};
|
||||||
|
use util::Hashable;
|
||||||
|
|
||||||
use ethcore::account_provider::AccountProvider;
|
use ethcore::account_provider::AccountProvider;
|
||||||
use ethcore::miner::MinerService;
|
use ethcore::miner::MinerService;
|
||||||
@ -83,7 +84,8 @@ impl<C: 'static, M: 'static> EthSigning for SigningUnsafeClient<C, M> where
|
|||||||
C: MiningBlockChainClient,
|
C: MiningBlockChainClient,
|
||||||
M: MinerService,
|
M: MinerService,
|
||||||
{
|
{
|
||||||
fn sign(&self, ready: Ready<RpcH520>, address: RpcH160, hash: RpcH256) {
|
fn sign(&self, ready: Ready<RpcH520>, address: RpcH160, data: RpcBytes) {
|
||||||
|
let hash = data.0.sha3().into();
|
||||||
let result = match self.handle(RpcConfirmationPayload::Signature((address, hash).into())) {
|
let result = match self.handle(RpcConfirmationPayload::Signature((address, hash).into())) {
|
||||||
Ok(RpcConfirmationResponse::Signature(signature)) => Ok(signature),
|
Ok(RpcConfirmationResponse::Signature(signature)) => Ok(signature),
|
||||||
Err(e) => Err(e),
|
Err(e) => Err(e),
|
||||||
|
@ -105,13 +105,13 @@ impl SyncProvider for TestSyncProvider {
|
|||||||
first_seen: 10,
|
first_seen: 10,
|
||||||
propagated_to: map![
|
propagated_to: map![
|
||||||
128.into() => 16
|
128.into() => 16
|
||||||
]
|
],
|
||||||
},
|
},
|
||||||
5.into() => TransactionStats {
|
5.into() => TransactionStats {
|
||||||
first_seen: 16,
|
first_seen: 16,
|
||||||
propagated_to: map![
|
propagated_to: map![
|
||||||
16.into() => 1
|
16.into() => 1
|
||||||
]
|
],
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
@ -18,11 +18,11 @@ use std::str::FromStr;
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::{Instant, Duration};
|
use std::time::{Instant, Duration};
|
||||||
use rustc_serialize::hex::ToHex;
|
use rustc_serialize::hex::{FromHex, ToHex};
|
||||||
use time::get_time;
|
use time::get_time;
|
||||||
use rlp;
|
use rlp;
|
||||||
|
|
||||||
use util::{Uint, U256, Address, H256, FixedHash, Mutex};
|
use util::{Uint, U256, Address, H256, FixedHash, Mutex, Hashable};
|
||||||
use ethcore::account_provider::AccountProvider;
|
use ethcore::account_provider::AccountProvider;
|
||||||
use ethcore::client::{TestBlockChainClient, EachBlockWith, Executed, TransactionId};
|
use ethcore::client::{TestBlockChainClient, EachBlockWith, Executed, TransactionId};
|
||||||
use ethcore::log_entry::{LocalizedLogEntry, LogEntry};
|
use ethcore::log_entry::{LocalizedLogEntry, LogEntry};
|
||||||
@ -294,8 +294,8 @@ fn rpc_eth_sign() {
|
|||||||
|
|
||||||
let account = tester.accounts_provider.new_account("abcd").unwrap();
|
let account = tester.accounts_provider.new_account("abcd").unwrap();
|
||||||
tester.accounts_provider.unlock_account_permanently(account, "abcd".into()).unwrap();
|
tester.accounts_provider.unlock_account_permanently(account, "abcd".into()).unwrap();
|
||||||
let message = H256::from("0x0cc175b9c0f1b6a831c399e26977266192eb5ffee6ae2fec3ad71c777531578f");
|
let message = "0cc175b9c0f1b6a831c399e26977266192eb5ffee6ae2fec3ad71c777531578f".from_hex().unwrap();
|
||||||
let signed = tester.accounts_provider.sign(account, None, message).unwrap();
|
let signed = tester.accounts_provider.sign(account, None, message.sha3()).unwrap();
|
||||||
|
|
||||||
let req = r#"{
|
let req = r#"{
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
|
@ -26,7 +26,7 @@ use v1::types::ConfirmationResponse;
|
|||||||
use v1::tests::helpers::TestMinerService;
|
use v1::tests::helpers::TestMinerService;
|
||||||
use v1::tests::mocked::parity;
|
use v1::tests::mocked::parity;
|
||||||
|
|
||||||
use util::{Address, FixedHash, Uint, U256, H256, ToPretty};
|
use util::{Address, FixedHash, Uint, U256, ToPretty, Hashable};
|
||||||
use ethcore::account_provider::AccountProvider;
|
use ethcore::account_provider::AccountProvider;
|
||||||
use ethcore::client::TestBlockChainClient;
|
use ethcore::client::TestBlockChainClient;
|
||||||
use ethcore::transaction::{Transaction, Action};
|
use ethcore::transaction::{Transaction, Action};
|
||||||
@ -186,11 +186,11 @@ fn should_check_status_of_request_when_its_resolved() {
|
|||||||
fn should_sign_if_account_is_unlocked() {
|
fn should_sign_if_account_is_unlocked() {
|
||||||
// given
|
// given
|
||||||
let tester = eth_signing();
|
let tester = eth_signing();
|
||||||
let hash: H256 = 5.into();
|
let data = vec![5u8];
|
||||||
let acc = tester.accounts.new_account("test").unwrap();
|
let acc = tester.accounts.new_account("test").unwrap();
|
||||||
tester.accounts.unlock_account_permanently(acc, "test".into()).unwrap();
|
tester.accounts.unlock_account_permanently(acc, "test".into()).unwrap();
|
||||||
|
|
||||||
let signature = tester.accounts.sign(acc, None, hash).unwrap();
|
let signature = tester.accounts.sign(acc, None, data.sha3()).unwrap();
|
||||||
|
|
||||||
// when
|
// when
|
||||||
let request = r#"{
|
let request = r#"{
|
||||||
@ -198,7 +198,7 @@ fn should_sign_if_account_is_unlocked() {
|
|||||||
"method": "eth_sign",
|
"method": "eth_sign",
|
||||||
"params": [
|
"params": [
|
||||||
""#.to_owned() + format!("0x{:?}", acc).as_ref() + r#"",
|
""#.to_owned() + format!("0x{:?}", acc).as_ref() + r#"",
|
||||||
""# + format!("0x{:?}", hash).as_ref() + r#""
|
""# + format!("0x{}", data.to_hex()).as_ref() + r#""
|
||||||
],
|
],
|
||||||
"id": 1
|
"id": 1
|
||||||
}"#;
|
}"#;
|
||||||
|
@ -17,14 +17,14 @@
|
|||||||
//! Eth rpc interface.
|
//! Eth rpc interface.
|
||||||
|
|
||||||
use v1::helpers::auto_args::{WrapAsync, Ready};
|
use v1::helpers::auto_args::{WrapAsync, Ready};
|
||||||
use v1::types::{H160, H256, H520, TransactionRequest, RichRawTransaction};
|
use v1::types::{Bytes, H160, H256, H520, TransactionRequest, RichRawTransaction};
|
||||||
|
|
||||||
build_rpc_trait! {
|
build_rpc_trait! {
|
||||||
/// Signing methods implementation relying on unlocked accounts.
|
/// Signing methods implementation relying on unlocked accounts.
|
||||||
pub trait EthSigning {
|
pub trait EthSigning {
|
||||||
/// Signs the data with given address signature.
|
/// Signs the hash of data with given address signature.
|
||||||
#[rpc(async, name = "eth_sign")]
|
#[rpc(async, name = "eth_sign")]
|
||||||
fn sign(&self, Ready<H520>, H160, H256);
|
fn sign(&self, Ready<H520>, H160, Bytes);
|
||||||
|
|
||||||
/// Sends transaction; will block waiting for signer to return the
|
/// Sends transaction; will block waiting for signer to return the
|
||||||
/// transaction hash.
|
/// transaction hash.
|
||||||
|
@ -157,7 +157,7 @@ impl From<SyncTransactionStats> for TransactionStats {
|
|||||||
propagated_to: s.propagated_to
|
propagated_to: s.propagated_to
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(id, count)| (id.into(), count))
|
.map(|(id, count)| (id.into(), count))
|
||||||
.collect()
|
.collect(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -208,7 +208,7 @@ mod tests {
|
|||||||
first_seen: 100,
|
first_seen: 100,
|
||||||
propagated_to: map![
|
propagated_to: map![
|
||||||
10.into() => 50
|
10.into() => 50
|
||||||
]
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
let serialized = serde_json::to_string(&stats).unwrap();
|
let serialized = serde_json::to_string(&stats).unwrap();
|
||||||
|
@ -144,7 +144,7 @@ pub struct EthSync {
|
|||||||
network: NetworkService,
|
network: NetworkService,
|
||||||
/// Main (eth/par) protocol handler
|
/// Main (eth/par) protocol handler
|
||||||
sync_handler: Arc<SyncProtocolHandler>,
|
sync_handler: Arc<SyncProtocolHandler>,
|
||||||
/// Light (les) protocol handler
|
/// Light (les) protocol handler
|
||||||
light_proto: Option<Arc<LightProtocol>>,
|
light_proto: Option<Arc<LightProtocol>>,
|
||||||
/// The main subprotocol name
|
/// The main subprotocol name
|
||||||
subprotocol_name: [u8; 3],
|
subprotocol_name: [u8; 3],
|
||||||
@ -155,7 +155,7 @@ pub struct EthSync {
|
|||||||
impl EthSync {
|
impl EthSync {
|
||||||
/// Creates and register protocol with the network service
|
/// Creates and register protocol with the network service
|
||||||
pub fn new(params: Params) -> Result<Arc<EthSync>, NetworkError> {
|
pub fn new(params: Params) -> Result<Arc<EthSync>, NetworkError> {
|
||||||
let pruning_info = params.chain.pruning_info();
|
let pruning_info = params.chain.pruning_info();
|
||||||
let light_proto = match params.config.serve_light {
|
let light_proto = match params.config.serve_light {
|
||||||
false => None,
|
false => None,
|
||||||
true => Some({
|
true => Some({
|
||||||
@ -297,7 +297,7 @@ impl ChainNotify for EthSync {
|
|||||||
Some(lp) => lp,
|
Some(lp) => lp,
|
||||||
None => return,
|
None => return,
|
||||||
};
|
};
|
||||||
|
|
||||||
let chain_info = self.sync_handler.chain.chain_info();
|
let chain_info = self.sync_handler.chain.chain_info();
|
||||||
light_proto.make_announcement(context, Announcement {
|
light_proto.make_announcement(context, Announcement {
|
||||||
head_hash: chain_info.best_block_hash,
|
head_hash: chain_info.best_block_hash,
|
||||||
@ -323,7 +323,7 @@ impl ChainNotify for EthSync {
|
|||||||
// register the warp sync subprotocol
|
// register the warp sync subprotocol
|
||||||
self.network.register_protocol(self.sync_handler.clone(), WARP_SYNC_PROTOCOL_ID, SNAPSHOT_SYNC_PACKET_COUNT, &[1u8])
|
self.network.register_protocol(self.sync_handler.clone(), WARP_SYNC_PROTOCOL_ID, SNAPSHOT_SYNC_PACKET_COUNT, &[1u8])
|
||||||
.unwrap_or_else(|e| warn!("Error registering snapshot sync protocol: {:?}", e));
|
.unwrap_or_else(|e| warn!("Error registering snapshot sync protocol: {:?}", e));
|
||||||
|
|
||||||
// register the light protocol.
|
// register the light protocol.
|
||||||
if let Some(light_proto) = self.light_proto.as_ref().map(|x| x.clone()) {
|
if let Some(light_proto) = self.light_proto.as_ref().map(|x| x.clone()) {
|
||||||
self.network.register_protocol(light_proto, self.light_subprotocol_name, ::light::net::PACKET_COUNT, ::light::net::PROTOCOL_VERSIONS)
|
self.network.register_protocol(light_proto, self.light_subprotocol_name, ::light::net::PACKET_COUNT, ::light::net::PROTOCOL_VERSIONS)
|
||||||
@ -335,6 +335,11 @@ impl ChainNotify for EthSync {
|
|||||||
self.sync_handler.snapshot_service.abort_restore();
|
self.sync_handler.snapshot_service.abort_restore();
|
||||||
self.network.stop().unwrap_or_else(|e| warn!("Error stopping network: {:?}", e));
|
self.network.stop().unwrap_or_else(|e| warn!("Error stopping network: {:?}", e));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn transactions_received(&self, hashes: Vec<H256>, peer_id: PeerId) {
|
||||||
|
let mut sync = self.sync_handler.sync.write();
|
||||||
|
sync.transactions_received(hashes, peer_id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// LES event handler.
|
/// LES event handler.
|
||||||
@ -344,7 +349,7 @@ struct TxRelay(Arc<BlockChainClient>);
|
|||||||
impl LightHandler for TxRelay {
|
impl LightHandler for TxRelay {
|
||||||
fn on_transactions(&self, ctx: &EventContext, relay: &[::ethcore::transaction::SignedTransaction]) {
|
fn on_transactions(&self, ctx: &EventContext, relay: &[::ethcore::transaction::SignedTransaction]) {
|
||||||
trace!(target: "les", "Relaying {} transactions from peer {}", relay.len(), ctx.peer());
|
trace!(target: "les", "Relaying {} transactions from peer {}", relay.len(), ctx.peer());
|
||||||
self.0.queue_transactions(relay.iter().map(|tx| ::rlp::encode(tx).to_vec()).collect())
|
self.0.queue_transactions(relay.iter().map(|tx| ::rlp::encode(tx).to_vec()).collect(), ctx.peer())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -547,4 +552,4 @@ pub struct ServiceConfiguration {
|
|||||||
pub net: NetworkConfiguration,
|
pub net: NetworkConfiguration,
|
||||||
/// IPC path.
|
/// IPC path.
|
||||||
pub io_path: String,
|
pub io_path: String,
|
||||||
}
|
}
|
||||||
|
@ -432,6 +432,13 @@ impl ChainSync {
|
|||||||
self.transactions_stats.stats()
|
self.transactions_stats.stats()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Updates transactions were received by a peer
|
||||||
|
pub fn transactions_received(&mut self, hashes: Vec<H256>, peer_id: PeerId) {
|
||||||
|
if let Some(mut peer_info) = self.peers.get_mut(&peer_id) {
|
||||||
|
peer_info.last_sent_transactions.extend(&hashes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Abort all sync activity
|
/// Abort all sync activity
|
||||||
pub fn abort(&mut self, io: &mut SyncIo) {
|
pub fn abort(&mut self, io: &mut SyncIo) {
|
||||||
self.reset_and_continue(io);
|
self.reset_and_continue(io);
|
||||||
@ -1409,7 +1416,7 @@ impl ChainSync {
|
|||||||
let tx = rlp.as_raw().to_vec();
|
let tx = rlp.as_raw().to_vec();
|
||||||
transactions.push(tx);
|
transactions.push(tx);
|
||||||
}
|
}
|
||||||
io.chain().queue_transactions(transactions);
|
io.chain().queue_transactions(transactions, peer_id);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -112,7 +112,7 @@ mod tests {
|
|||||||
propagated_to: hash_map![
|
propagated_to: hash_map![
|
||||||
enodeid1 => 2,
|
enodeid1 => 2,
|
||||||
enodeid2 => 1
|
enodeid2 => 1
|
||||||
]
|
],
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -99,7 +99,7 @@ pub use stats::NetworkStats;
|
|||||||
pub use session::SessionInfo;
|
pub use session::SessionInfo;
|
||||||
|
|
||||||
use io::TimerToken;
|
use io::TimerToken;
|
||||||
pub use node_table::is_valid_node_url;
|
pub use node_table::{is_valid_node_url, NodeId};
|
||||||
|
|
||||||
const PROTOCOL_VERSION: u32 = 4;
|
const PROTOCOL_VERSION: u32 = 4;
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user