diff --git a/Cargo.lock b/Cargo.lock index 2a8b2ce09..b8e14e5fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1249,7 +1249,7 @@ dependencies = [ [[package]] name = "parity-ui-precompiled" version = "1.4.0" -source = "git+https://github.com/ethcore/js-precompiled.git#76e3cbf0c68acb72174e666216d15a5fff5100d6" +source = "git+https://github.com/ethcore/js-precompiled.git#7bf550e482ef274480d1fd7e1ceb2efddd747dbd" dependencies = [ "parity-dapps-glue 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] diff --git a/ethcore/src/pod_account.rs b/ethcore/src/pod_account.rs index afee32f94..0882b688c 100644 --- a/ethcore/src/pod_account.rs +++ b/ethcore/src/pod_account.rs @@ -89,7 +89,7 @@ impl From for PodAccount { let key: U256 = key.into(); let value: U256 = value.into(); (H256::from(key), H256::from(value)) - }).collect() + }).collect(), } } } @@ -99,8 +99,12 @@ impl From for PodAccount { PodAccount { balance: a.balance.map_or_else(U256::zero, Into::into), nonce: a.nonce.map_or_else(U256::zero, Into::into), - code: a.code.map(Into::into).or_else(|| Some(Vec::new())), - storage: BTreeMap::new() + code: Some(a.code.map_or_else(Vec::new, Into::into)), + storage: a.storage.map_or_else(BTreeMap::new, |s| s.into_iter().map(|(key, value)| { + let key: U256 = key.into(); + let value: U256 = value.into(); + (H256::from(key), H256::from(value)) + }).collect()), } } } @@ -112,7 +116,7 @@ impl fmt::Display for PodAccount { self.nonce, self.code.as_ref().map_or(0, |c| c.len()), self.code.as_ref().map_or_else(H256::new, |c| c.sha3()), - self.storage.len() + self.storage.len(), ) } } diff --git a/ethcore/src/snapshot/error.rs b/ethcore/src/snapshot/error.rs index d634057dc..d417695f0 100644 --- a/ethcore/src/snapshot/error.rs +++ b/ethcore/src/snapshot/error.rs @@ -45,6 +45,8 @@ pub enum Error { MissingCode(Vec), /// Unrecognized code encoding. UnrecognizedCodeState(u8), + /// Restoration aborted. + RestorationAborted, /// Trie error. Trie(TrieError), /// Decoder error. @@ -67,6 +69,7 @@ impl fmt::Display for Error { a pruned database. Please re-run with the --pruning archive flag."), Error::MissingCode(ref missing) => write!(f, "Incomplete snapshot: {} contract codes not found.", missing.len()), Error::UnrecognizedCodeState(state) => write!(f, "Unrecognized code encoding ({})", state), + Error::RestorationAborted => write!(f, "Snapshot restoration aborted."), Error::Io(ref err) => err.fmt(f), Error::Decoder(ref err) => err.fmt(f), Error::Trie(ref err) => err.fmt(f), diff --git a/ethcore/src/snapshot/mod.rs b/ethcore/src/snapshot/mod.rs index 22c44ba3b..f4d791593 100644 --- a/ethcore/src/snapshot/mod.rs +++ b/ethcore/src/snapshot/mod.rs @@ -407,30 +407,28 @@ impl StateRebuilder { } /// Feed an uncompressed state chunk into the rebuilder. - pub fn feed(&mut self, chunk: &[u8]) -> Result<(), ::error::Error> { + pub fn feed(&mut self, chunk: &[u8], flag: &AtomicBool) -> Result<(), ::error::Error> { let rlp = UntrustedRlp::new(chunk); let empty_rlp = StateAccount::new_basic(U256::zero(), U256::zero()).rlp(); - let account_fat_rlps: Vec<_> = rlp.iter().map(|r| r.as_raw()).collect(); let mut pairs = Vec::with_capacity(rlp.item_count()); // initialize the pairs vector with empty values so we have slots to write into. pairs.resize(rlp.item_count(), (H256::new(), Vec::new())); - let chunk_size = account_fat_rlps.len() / ::num_cpus::get() + 1; + let status = try!(rebuild_accounts( + self.db.as_hashdb_mut(), + rlp, + &mut pairs, + &self.code_map, + flag + )); - // new code contained within this chunk. - let mut chunk_code = HashMap::new(); - - for (account_chunk, out_pairs_chunk) in account_fat_rlps.chunks(chunk_size).zip(pairs.chunks_mut(chunk_size)) { - let code_map = &self.code_map; - let status = try!(rebuild_accounts(self.db.as_hashdb_mut(), account_chunk, out_pairs_chunk, code_map)); - chunk_code.extend(status.new_code); - for (addr_hash, code_hash) in status.missing_code { - self.missing_code.entry(code_hash).or_insert_with(Vec::new).push(addr_hash); - } + for (addr_hash, code_hash) in status.missing_code { + self.missing_code.entry(code_hash).or_insert_with(Vec::new).push(addr_hash); } + // patch up all missing code. must be done after collecting all new missing code entries. - for (code_hash, code) in chunk_code { + for (code_hash, code) in status.new_code { for addr_hash in self.missing_code.remove(&code_hash).unwrap_or_else(Vec::new) { let mut db = AccountDBMut::from_hash(self.db.as_hashdb_mut(), addr_hash); db.emplace(code_hash, DBValue::from_slice(&code)); @@ -450,6 +448,8 @@ impl StateRebuilder { }; for (hash, thin_rlp) in pairs { + if !flag.load(Ordering::SeqCst) { return Err(Error::RestorationAborted.into()) } + if &thin_rlp[..] != &empty_rlp[..] { self.bloom.set(&*hash); } @@ -487,17 +487,18 @@ struct RebuiltStatus { } // rebuild a set of accounts and their storage. -// returns +// returns a status detailing newly-loaded code and accounts missing code. fn rebuild_accounts( db: &mut HashDB, - account_chunk: &[&[u8]], + account_fat_rlps: UntrustedRlp, out_chunk: &mut [(H256, Bytes)], - code_map: &HashMap + code_map: &HashMap, + abort_flag: &AtomicBool ) -> Result { let mut status = RebuiltStatus::default(); - for (account_pair, out) in account_chunk.into_iter().zip(out_chunk) { - let account_rlp = UntrustedRlp::new(account_pair); + for (account_rlp, out) in account_fat_rlps.into_iter().zip(out_chunk) { + if !abort_flag.load(Ordering::SeqCst) { return Err(Error::RestorationAborted.into()) } let hash: H256 = try!(account_rlp.val_at(0)); let fat_rlp = try!(account_rlp.at(1)); @@ -580,7 +581,7 @@ impl BlockRebuilder { /// Feed the rebuilder an uncompressed block chunk. /// Returns the number of blocks fed or any errors. - pub fn feed(&mut self, chunk: &[u8], engine: &Engine) -> Result { + pub fn feed(&mut self, chunk: &[u8], engine: &Engine, abort_flag: &AtomicBool) -> Result { use basic_types::Seal::With; use util::U256; use util::triehash::ordered_trie_root; @@ -601,6 +602,8 @@ impl BlockRebuilder { let parent_total_difficulty = try!(rlp.val_at::(2)); for idx in 3..item_count { + if !abort_flag.load(Ordering::SeqCst) { return Err(Error::RestorationAborted.into()) } + let pair = try!(rlp.at(idx)); let abridged_rlp = try!(pair.at(0)).as_raw().to_owned(); let abridged_block = AbridgedBlock::from_raw(abridged_rlp); diff --git a/ethcore/src/snapshot/service.rs b/ethcore/src/snapshot/service.rs index 16f7c6ec6..c0d34a6a9 100644 --- a/ethcore/src/snapshot/service.rs +++ b/ethcore/src/snapshot/service.rs @@ -118,12 +118,12 @@ impl Restoration { }) } - // feeds a state chunk - fn feed_state(&mut self, hash: H256, chunk: &[u8]) -> Result<(), Error> { + // feeds a state chunk, aborts early if `flag` becomes false. + fn feed_state(&mut self, hash: H256, chunk: &[u8], flag: &AtomicBool) -> Result<(), Error> { if self.state_chunks_left.remove(&hash) { let len = try!(snappy::decompress_into(chunk, &mut self.snappy_buffer)); - try!(self.state.feed(&self.snappy_buffer[..len])); + try!(self.state.feed(&self.snappy_buffer[..len], flag)); if let Some(ref mut writer) = self.writer.as_mut() { try!(writer.write_state_chunk(hash, chunk)); @@ -134,11 +134,11 @@ impl Restoration { } // feeds a block chunk - fn feed_blocks(&mut self, hash: H256, chunk: &[u8], engine: &Engine) -> Result<(), Error> { + fn feed_blocks(&mut self, hash: H256, chunk: &[u8], engine: &Engine, flag: &AtomicBool) -> Result<(), Error> { if self.block_chunks_left.remove(&hash) { let len = try!(snappy::decompress_into(chunk, &mut self.snappy_buffer)); - try!(self.blocks.feed(&self.snappy_buffer[..len], engine)); + try!(self.blocks.feed(&self.snappy_buffer[..len], engine, flag)); if let Some(ref mut writer) = self.writer.as_mut() { try!(writer.write_block_chunk(hash, chunk)); } @@ -224,6 +224,7 @@ pub struct Service { db_restore: Arc, progress: super::Progress, taking_snapshot: AtomicBool, + restoring_snapshot: AtomicBool, } impl Service { @@ -244,6 +245,7 @@ impl Service { db_restore: params.db_restore, progress: Default::default(), taking_snapshot: AtomicBool::new(false), + restoring_snapshot: AtomicBool::new(false), }; // create the root snapshot dir if it doesn't exist. @@ -436,6 +438,8 @@ impl Service { state_chunks_done: self.state_chunks.load(Ordering::SeqCst) as u32, block_chunks_done: self.block_chunks.load(Ordering::SeqCst) as u32, }; + + self.restoring_snapshot.store(true, Ordering::SeqCst); Ok(()) } @@ -490,8 +494,8 @@ impl Service { }; (match is_state { - true => rest.feed_state(hash, chunk), - false => rest.feed_blocks(hash, chunk, &*self.engine), + true => rest.feed_state(hash, chunk, &self.restoring_snapshot), + false => rest.feed_blocks(hash, chunk, &*self.engine, &self.restoring_snapshot), }.map(|_| rest.is_done()), rest.db.clone()) }; @@ -573,6 +577,7 @@ impl SnapshotService for Service { } fn abort_restore(&self) { + self.restoring_snapshot.store(false, Ordering::SeqCst); *self.restoration.lock() = None; *self.status.lock() = RestorationStatus::Inactive; } diff --git a/ethcore/src/snapshot/tests/blocks.rs b/ethcore/src/snapshot/tests/blocks.rs index 12efcda77..18637bad1 100644 --- a/ethcore/src/snapshot/tests/blocks.rs +++ b/ethcore/src/snapshot/tests/blocks.rs @@ -17,10 +17,11 @@ //! Block chunker and rebuilder tests. use devtools::RandomTempPath; +use error::Error; use blockchain::generator::{ChainGenerator, ChainIterator, BlockFinalizer}; use blockchain::BlockChain; -use snapshot::{chunk_blocks, BlockRebuilder, Progress}; +use snapshot::{chunk_blocks, BlockRebuilder, Error as SnapshotError, Progress}; use snapshot::io::{PackedReader, PackedWriter, SnapshotReader, SnapshotWriter}; use util::{Mutex, snappy}; @@ -28,6 +29,7 @@ use util::kvdb::{Database, DatabaseConfig}; use std::collections::HashMap; use std::sync::Arc; +use std::sync::atomic::AtomicBool; fn chunk_and_restore(amount: u64) { let mut canon_chain = ChainGenerator::default(); @@ -75,10 +77,11 @@ fn chunk_and_restore(amount: u64) { let mut rebuilder = BlockRebuilder::new(new_chain, new_db.clone(), &manifest).unwrap(); let reader = PackedReader::new(&snapshot_path).unwrap().unwrap(); let engine = ::engines::NullEngine::new(Default::default(), Default::default()); + let flag = AtomicBool::new(true); for chunk_hash in &reader.manifest().block_hashes { let compressed = reader.chunk(*chunk_hash).unwrap(); let chunk = snappy::decompress(&compressed).unwrap(); - rebuilder.feed(&chunk, &engine).unwrap(); + rebuilder.feed(&chunk, &engine, &flag).unwrap(); } rebuilder.finalize(HashMap::new()).unwrap(); @@ -93,3 +96,46 @@ fn chunk_and_restore_500() { chunk_and_restore(500) } #[test] fn chunk_and_restore_40k() { chunk_and_restore(40000) } + +#[test] +fn checks_flag() { + use ::rlp::{RlpStream, Stream}; + use util::H256; + + let mut stream = RlpStream::new_list(5); + + stream.append(&100u64) + .append(&H256::default()) + .append(&(!0u64)); + + stream.append_empty_data().append_empty_data(); + + let genesis = { + let mut canon_chain = ChainGenerator::default(); + let mut finalizer = BlockFinalizer::default(); + canon_chain.generate(&mut finalizer).unwrap() + }; + + let chunk = stream.out(); + let path = RandomTempPath::create_dir(); + + let db_cfg = DatabaseConfig::with_columns(::db::NUM_COLUMNS); + let db = Arc::new(Database::open(&db_cfg, path.as_str()).unwrap()); + let chain = BlockChain::new(Default::default(), &genesis, db.clone()); + let engine = ::engines::NullEngine::new(Default::default(), Default::default()); + + let manifest = ::snapshot::ManifestData { + state_hashes: Vec::new(), + block_hashes: Vec::new(), + state_root: ::util::sha3::SHA3_NULL_RLP, + block_number: 102, + block_hash: H256::default(), + }; + + let mut rebuilder = BlockRebuilder::new(chain, db.clone(), &manifest).unwrap(); + + match rebuilder.feed(&chunk, &engine, &AtomicBool::new(false)) { + Err(Error::Snapshot(SnapshotError::RestorationAborted)) => {} + _ => panic!("Wrong result on abort flag set") + } +} \ No newline at end of file diff --git a/ethcore/src/snapshot/tests/state.rs b/ethcore/src/snapshot/tests/state.rs index e1d4df5f9..05537fa96 100644 --- a/ethcore/src/snapshot/tests/state.rs +++ b/ethcore/src/snapshot/tests/state.rs @@ -16,10 +16,12 @@ //! State snapshotting tests. -use snapshot::{chunk_state, Progress, StateRebuilder}; +use snapshot::{chunk_state, Error as SnapshotError, Progress, StateRebuilder}; use snapshot::io::{PackedReader, PackedWriter, SnapshotReader, SnapshotWriter}; use super::helpers::{compare_dbs, StateProducer}; +use error::Error; + use rand::{XorShiftRng, SeedableRng}; use util::hash::H256; use util::journaldb::{self, Algorithm}; @@ -29,6 +31,7 @@ use util::Mutex; use devtools::RandomTempPath; use std::sync::Arc; +use std::sync::atomic::AtomicBool; #[test] fn snap_and_restore() { @@ -65,11 +68,13 @@ fn snap_and_restore() { let mut rebuilder = StateRebuilder::new(new_db.clone(), Algorithm::Archive); let reader = PackedReader::new(&snap_file).unwrap().unwrap(); + let flag = AtomicBool::new(true); + for chunk_hash in &reader.manifest().state_hashes { let raw = reader.chunk(*chunk_hash).unwrap(); let chunk = ::util::snappy::decompress(&raw).unwrap(); - rebuilder.feed(&chunk).unwrap(); + rebuilder.feed(&chunk, &flag).unwrap(); } assert_eq!(rebuilder.state_root(), state_root); @@ -82,3 +87,52 @@ fn snap_and_restore() { compare_dbs(&old_db, new_db.as_hashdb()); } + +#[test] +fn checks_flag() { + let mut producer = StateProducer::new(); + let mut rng = XorShiftRng::from_seed([5, 6, 7, 8]); + let mut old_db = MemoryDB::new(); + let db_cfg = DatabaseConfig::with_columns(::db::NUM_COLUMNS); + + for _ in 0..10 { + producer.tick(&mut rng, &mut old_db); + } + + let snap_dir = RandomTempPath::create_dir(); + let mut snap_file = snap_dir.as_path().to_owned(); + snap_file.push("SNAP"); + + let state_root = producer.state_root(); + let writer = Mutex::new(PackedWriter::new(&snap_file).unwrap()); + + let state_hashes = chunk_state(&old_db, &state_root, &writer, &Progress::default()).unwrap(); + + writer.into_inner().finish(::snapshot::ManifestData { + state_hashes: state_hashes, + block_hashes: Vec::new(), + state_root: state_root, + block_number: 0, + block_hash: H256::default(), + }).unwrap(); + + let mut db_path = snap_dir.as_path().to_owned(); + db_path.push("db"); + { + let new_db = Arc::new(Database::open(&db_cfg, &db_path.to_string_lossy()).unwrap()); + let mut rebuilder = StateRebuilder::new(new_db.clone(), Algorithm::Archive); + let reader = PackedReader::new(&snap_file).unwrap().unwrap(); + + let flag = AtomicBool::new(false); + + for chunk_hash in &reader.manifest().state_hashes { + let raw = reader.chunk(*chunk_hash).unwrap(); + let chunk = ::util::snappy::decompress(&raw).unwrap(); + + match rebuilder.feed(&chunk, &flag) { + Err(Error::Snapshot(SnapshotError::RestorationAborted)) => {}, + _ => panic!("unexpected result when feeding with flag off"), + } + } + } +} \ No newline at end of file diff --git a/ethcore/src/spec/spec.rs b/ethcore/src/spec/spec.rs index 2babfb708..6bfb1bcc1 100644 --- a/ethcore/src/spec/spec.rs +++ b/ethcore/src/spec/spec.rs @@ -162,7 +162,7 @@ impl Spec { /// Get the configured Network ID. pub fn network_id(&self) -> usize { self.params.network_id } - /// Get the configured Network ID. + /// Get the configured subprotocol name. pub fn subprotocol_name(&self) -> String { self.params.subprotocol_name.clone() } /// Get the configured network fork block. diff --git a/js/README.md b/js/README.md index 41252bc91..5ed26e0cf 100644 --- a/js/README.md +++ b/js/README.md @@ -7,6 +7,6 @@ JavaScript APIs and UIs for Parity. 0. Install [Node](https://nodejs.org/) if not already available 0. Change to the `js` directory inside `parity/` 0. Install the npm modules via `npm install` -0. Parity should be run with `parity --signer-no-validation [...options]` (where `options` can be `--chain testnet`) +0. Parity should be run with `parity --ui-no-validation [...options]` (where `options` can be `--chain testnet`) 0. Start the development environment via `npm start` 0. Connect to the [UI](http://localhost:3000) diff --git a/js/package.json b/js/package.json index 549d55dc8..1e2da7d5b 100644 --- a/js/package.json +++ b/js/package.json @@ -1,6 +1,6 @@ { "name": "parity.js", - "version": "0.2.31", + "version": "0.2.38", "main": "release/index.js", "jsnext:main": "src/index.js", "author": "Parity Team ", @@ -100,6 +100,7 @@ "postcss-loader": "^0.8.1", "postcss-nested": "^1.0.0", "postcss-simple-vars": "^3.0.0", + "raw-loader": "^0.5.1", "react-addons-test-utils": "^15.3.0", "react-copy-to-clipboard": "^4.2.3", "react-hot-loader": "^1.3.0", @@ -118,6 +119,7 @@ "dependencies": { "bignumber.js": "^2.3.0", "blockies": "0.0.2", + "brace": "^0.9.0", "bytes": "^2.4.0", "chart.js": "^2.3.0", "es6-promise": "^3.2.1", @@ -138,9 +140,11 @@ "moment": "^2.14.1", "qs": "^6.3.0", "react": "^15.2.1", + "react-ace": "^4.0.0", "react-addons-css-transition-group": "^15.2.1", "react-chartjs-2": "^1.5.0", "react-dom": "^15.2.1", + "react-dropzone": "^3.7.3", "react-redux": "^4.4.5", "react-router": "^2.6.1", "react-router-redux": "^4.0.5", @@ -152,10 +156,13 @@ "redux-thunk": "^2.1.0", "rlp": "^2.0.0", "scryptsy": "^2.0.0", + "solc": "ngotchac/solc-js", "store": "^1.3.20", "utf8": "^2.1.1", + "valid-url": "^1.0.9", "validator": "^5.7.0", "web3": "^0.17.0-beta", - "whatwg-fetch": "^1.0.0" + "whatwg-fetch": "^1.0.0", + "worker-loader": "^0.7.1" } } diff --git a/js/src/api/contract/contract.js b/js/src/api/contract/contract.js index 44e66c925..8d556a118 100644 --- a/js/src/api/contract/contract.js +++ b/js/src/api/contract/contract.js @@ -309,7 +309,6 @@ export default class Contract { try { subscriptions[idx].callback(null, this.parseEventLogs(logs)); } catch (error) { - this.unsubscribe(idx); console.error('_sendSubscriptionChanges', error); } }); diff --git a/js/src/api/subscriptions/manager.js b/js/src/api/subscriptions/manager.js index 08f1a9e53..bc9632592 100644 --- a/js/src/api/subscriptions/manager.js +++ b/js/src/api/subscriptions/manager.js @@ -107,7 +107,6 @@ export default class Manager { callback(error, data); } catch (error) { console.error(`Unable to update callback for subscriptionId ${subscriptionId}`, error); - this.unsubscribe(subscriptionId); } } diff --git a/js/src/contracts/snippets/human-standard-token.sol b/js/src/contracts/snippets/human-standard-token.sol new file mode 100644 index 000000000..db05bbc7d --- /dev/null +++ b/js/src/contracts/snippets/human-standard-token.sol @@ -0,0 +1,60 @@ +/* +This Token Contract implements the standard token functionality (https://github.com/ethereum/EIPs/issues/20) as well as the following OPTIONAL extras intended for use by humans. + +In other words. This is intended for deployment in something like a Token Factory or Mist wallet, and then used by humans. +Imagine coins, currencies, shares, voting weight, etc. +Machine-based, rapid creation of many tokens would not necessarily need these extra features or will be minted in other manners. + +1) Initial Finite Supply (upon creation one specifies how much is minted). +2) In the absence of a token registry: Optional Decimal, Symbol & Name. +3) Optional approveAndCall() functionality to notify a contract if an approval() has occurred. + +.*/ + +import "StandardToken.sol"; + +contract HumanStandardToken is StandardToken { + + function () { + //if ether is sent to this address, send it back. + throw; + } + + /* Public variables of the token */ + + /* + NOTE: + The following variables are OPTIONAL vanities. One does not have to include them. + They allow one to customise the token contract & in no way influences the core functionality. + Some wallets/interfaces might not even bother to look at this information. + */ + string public name; //fancy name: eg Simon Bucks + uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. + string public symbol; //An identifier: eg SBX + string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme. + + function HumanStandardToken( + uint256 _initialAmount, + string _tokenName, + uint8 _decimalUnits, + string _tokenSymbol + ) { + balances[msg.sender] = _initialAmount; // Give the creator all initial tokens + totalSupply = _initialAmount; // Update total supply + name = _tokenName; // Set the name for display purposes + decimals = _decimalUnits; // Amount of decimals for display purposes + symbol = _tokenSymbol; // Set the symbol for display purposes + } + + /* Approves and then calls the receiving contract */ + function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + + //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. + //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) + //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. + if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } + return true; + } +} diff --git a/js/src/contracts/snippets/standard-token.sol b/js/src/contracts/snippets/standard-token.sol new file mode 100644 index 000000000..3d91e5510 --- /dev/null +++ b/js/src/contracts/snippets/standard-token.sol @@ -0,0 +1,55 @@ +/* +You should inherit from StandardToken or, for a token like you would want to +deploy in something like Mist, see HumanStandardToken.sol. +(This implements ONLY the standard functions and NOTHING else. +If you deploy this, you won't have anything useful.) + +Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20 +.*/ + +import "Token.sol"; + +contract StandardToken is Token { + + function transfer(address _to, uint256 _value) returns (bool success) { + //Default assumes totalSupply can't be over max (2^256 - 1). + //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. + //Replace the if with this one instead. + //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { + if (balances[msg.sender] >= _value && _value > 0) { + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } else { return false; } + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + //same as above. Replace this line with the following if you want to protect against wrapping uints. + //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } else { return false; } + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} diff --git a/js/src/contracts/snippets/token.sol b/js/src/contracts/snippets/token.sol new file mode 100644 index 000000000..d54c5c424 --- /dev/null +++ b/js/src/contracts/snippets/token.sol @@ -0,0 +1,47 @@ +// Abstract contract for the full ERC 20 Token standard +// https://github.com/ethereum/EIPs/issues/20 + +contract Token { + /* This is a slight change to the ERC20 base standard. + function totalSupply() constant returns (uint256 supply); + is replaced with: + uint256 public totalSupply; + This automatically creates a getter function for the totalSupply. + This is moved to the base contract since public getter functions are not + currently recognised as an implementation of the matching abstract + function by the compiler. + */ + /// total amount of tokens + uint256 public totalSupply; + + /// @param _owner The address from which the balance will be retrieved + /// @return The balance + function balanceOf(address _owner) constant returns (uint256 balance); + + /// @notice send `_value` token to `_to` from `msg.sender` + /// @param _to The address of the recipient + /// @param _value The amount of token to be transferred + /// @return Whether the transfer was successful or not + function transfer(address _to, uint256 _value) returns (bool success); + + /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` + /// @param _from The address of the sender + /// @param _to The address of the recipient + /// @param _value The amount of token to be transferred + /// @return Whether the transfer was successful or not + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + + /// @notice `msg.sender` approves `_addr` to spend `_value` tokens + /// @param _spender The address of the account able to transfer the tokens + /// @param _value The amount of wei to be approved for transfer + /// @return Whether the approval was successful or not + function approve(address _spender, uint256 _value) returns (bool success); + + /// @param _owner The address of the account owning tokens + /// @param _spender The address of the account able to transfer the tokens + /// @return Amount of remaining tokens allowed to spent + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} diff --git a/js/src/dapps/githubhint/services.js b/js/src/dapps/githubhint/services.js index c9d260b73..d4f7fc6b2 100644 --- a/js/src/dapps/githubhint/services.js +++ b/js/src/dapps/githubhint/services.js @@ -28,26 +28,26 @@ export function attachInterface () { return Promise .all([ registry.getAddress.call({}, [api.util.sha3('githubhint'), 'A']), - api.eth.accounts(), api.parity.accounts() ]); }) - .then(([address, addresses, accountsInfo]) => { - accountsInfo = accountsInfo || {}; + .then(([address, accountsInfo]) => { console.log(`githubhint was found at ${address}`); const contract = api.newContract(abis.githubhint, address); - const accounts = addresses.reduce((obj, address) => { - const info = accountsInfo[address] || {}; + const accounts = Object + .keys(accountsInfo) + .filter((address) => accountsInfo[address].uuid) + .reduce((obj, address) => { + const account = accountsInfo[address]; - return Object.assign(obj, { - [address]: { - address, - name: info.name, - uuid: info.uuid - } - }); - }, {}); + return Object.assign(obj, { + [address]: { + address, + name: account.name + } + }); + }, {}); const fromAddress = Object.keys(accounts)[0]; return { diff --git a/js/src/dapps/registry/Application/application.css b/js/src/dapps/registry/Application/application.css index ebdb23baa..b46afbcf7 100644 --- a/js/src/dapps/registry/Application/application.css +++ b/js/src/dapps/registry/Application/application.css @@ -49,3 +49,15 @@ padding-bottom: 0 !important; } } + +.warning { + background: #f80; + bottom: 0; + color: #fff; + left: 0; + opacity: 1; + padding: 1.5em; + position: fixed; + right: 50%; + z-index: 100; +} diff --git a/js/src/dapps/registry/Application/application.js b/js/src/dapps/registry/Application/application.js index e763069a5..5102e5d57 100644 --- a/js/src/dapps/registry/Application/application.js +++ b/js/src/dapps/registry/Application/application.js @@ -53,6 +53,7 @@ export default class Application extends Component { }; render () { + const { api } = window.parity; const { actions, accounts, contacts, @@ -60,9 +61,11 @@ export default class Application extends Component { lookup, events } = this.props; + let warning = null; return (
+ { warning }

RΞgistry

@@ -70,13 +73,11 @@ export default class Application extends Component { { contract && fee ? (
- { this.renderActions() } - -

- The Registry is provided by the contract at { contract.address }. -

+
+ WARNING: The name registry is experimental. Please ensure that you understand the risks, benefits & consequences of registering a name before doing so. A non-refundable fee of { api.util.fromWei(fee).toFormat(3) }ETH is required for all registrations. +
) : ( diff --git a/js/src/dapps/registry/addresses/actions.js b/js/src/dapps/registry/addresses/actions.js index 2341d716c..666196e88 100644 --- a/js/src/dapps/registry/addresses/actions.js +++ b/js/src/dapps/registry/addresses/actions.js @@ -19,18 +19,16 @@ import { api } from '../parity'; export const set = (addresses) => ({ type: 'addresses set', addresses }); export const fetch = () => (dispatch) => { - return Promise - .all([ - api.eth.accounts(), - api.parity.accounts() - ]) - .then(([ accounts, data ]) => { - data = data || {}; - const addresses = Object.keys(data) - .filter((address) => data[address] && !data[address].meta.deleted) + return api.parity + .accounts() + .then((accountsInfo) => { + const addresses = Object + .keys(accountsInfo) + .filter((address) => accountsInfo[address] && !accountsInfo[address].meta.deleted) .map((address) => ({ - ...data[address], address, - isAccount: accounts.includes(address) + ...accountsInfo[address], + address, + isAccount: !!accountsInfo[address].uuid })); dispatch(set(addresses)); }) diff --git a/js/src/dapps/signaturereg/Import/import.js b/js/src/dapps/signaturereg/Import/import.js index dcf2b3f98..90edf9415 100644 --- a/js/src/dapps/signaturereg/Import/import.js +++ b/js/src/dapps/signaturereg/Import/import.js @@ -146,7 +146,7 @@ export default class Import extends Component { } sortFunctions = (a, b) => { - return a.name.localeCompare(b.name); + return (a.name || '').localeCompare(b.name || ''); } countFunctions () { diff --git a/js/src/dapps/signaturereg/services.js b/js/src/dapps/signaturereg/services.js index 54394c4b8..eab498fc4 100644 --- a/js/src/dapps/signaturereg/services.js +++ b/js/src/dapps/signaturereg/services.js @@ -49,26 +49,26 @@ export function attachInterface (callback) { return Promise .all([ registry.getAddress.call({}, [api.util.sha3('signaturereg'), 'A']), - api.eth.accounts(), api.parity.accounts() ]); }) - .then(([address, addresses, accountsInfo]) => { - accountsInfo = accountsInfo || {}; + .then(([address, accountsInfo]) => { console.log(`signaturereg was found at ${address}`); const contract = api.newContract(abis.signaturereg, address); - const accounts = addresses.reduce((obj, address) => { - const info = accountsInfo[address] || {}; + const accounts = Object + .keys(accountsInfo) + .filter((address) => accountsInfo[address].uuid) + .reduce((obj, address) => { + const info = accountsInfo[address] || {}; - return Object.assign(obj, { - [address]: { - address, - name: info.name || 'Unnamed', - uuid: info.uuid - } - }); - }, {}); + return Object.assign(obj, { + [address]: { + address, + name: info.name || 'Unnamed' + } + }); + }, {}); const fromAddress = Object.keys(accounts)[0]; return { diff --git a/js/src/dapps/tokenreg/Accounts/actions.js b/js/src/dapps/tokenreg/Accounts/actions.js index 58a74dfd8..a310baf7d 100644 --- a/js/src/dapps/tokenreg/Accounts/actions.js +++ b/js/src/dapps/tokenreg/Accounts/actions.js @@ -35,16 +35,13 @@ export const setSelectedAccount = (address) => ({ }); export const loadAccounts = () => (dispatch) => { - Promise - .all([ - api.eth.accounts(), - api.parity.accounts() - ]) - .then(([ accounts, accountsInfo ]) => { - accountsInfo = accountsInfo || {}; - - const accountsList = accounts - .map(address => ({ + api.parity + .accounts() + .then((accountsInfo) => { + const accountsList = Object + .keys(accountsInfo) + .filter((address) => accountsInfo[address].uuid) + .map((address) => ({ ...accountsInfo[address], address })); diff --git a/js/src/dapps/tokenreg/Application/application.css b/js/src/dapps/tokenreg/Application/application.css index 07bc74b40..033147ae3 100644 --- a/js/src/dapps/tokenreg/Application/application.css +++ b/js/src/dapps/tokenreg/Application/application.css @@ -20,3 +20,15 @@ flex-direction: column; align-items: center; } + +.warning { + background: #f80; + bottom: 0; + color: #fff; + left: 0; + opacity: 1; + padding: 1.5em; + position: fixed; + right: 50%; + z-index: 100; +} diff --git a/js/src/dapps/tokenreg/Application/application.js b/js/src/dapps/tokenreg/Application/application.js index e48922b05..6a94f5c9c 100644 --- a/js/src/dapps/tokenreg/Application/application.js +++ b/js/src/dapps/tokenreg/Application/application.js @@ -17,6 +17,8 @@ import React, { Component, PropTypes } from 'react'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; +import { api } from '../parity'; + import Loading from '../Loading'; import Status from '../Status'; import Tokens from '../Tokens'; @@ -59,6 +61,9 @@ export default class Application extends Component { +
+ WARNING: The token registry is experimental. Please ensure that you understand the steps, risks, benefits & consequences of registering a token before doing so. A non-refundable fee of { api.util.fromWei(contract.fee).toFormat(3) }ETH is required for all registrations. +
); } diff --git a/js/src/dapps/tokenreg/Status/status.css b/js/src/dapps/tokenreg/Status/status.css index 27ef53607..7333194b7 100644 --- a/js/src/dapps/tokenreg/Status/status.css +++ b/js/src/dapps/tokenreg/Status/status.css @@ -31,6 +31,12 @@ .title { font-size: 3rem; font-weight: 300; - margin-top: 0; + margin: 0; text-transform: uppercase; } + +.byline { + font-size: 1.25em; + opacity: 0.75; + margin: 0 0 1.75em 0; +} diff --git a/js/src/dapps/tokenreg/Status/status.js b/js/src/dapps/tokenreg/Status/status.js index f8c7b347a..4ca47a6ea 100644 --- a/js/src/dapps/tokenreg/Status/status.js +++ b/js/src/dapps/tokenreg/Status/status.js @@ -29,17 +29,12 @@ export default class Status extends Component { }; render () { - const { address, fee } = this.props; + const { fee } = this.props; return (

Token Registry

- - - +

A global registry of all recognised tokens on the network

+ diff --git a/js/src/modals/DeployContract/DetailsStep/detailsStep.js b/js/src/modals/DeployContract/DetailsStep/detailsStep.js index 67c5586f0..1773fd0da 100644 --- a/js/src/modals/DeployContract/DetailsStep/detailsStep.js +++ b/js/src/modals/DeployContract/DetailsStep/detailsStep.js @@ -235,7 +235,7 @@ class TypedInput extends Component { export default class DetailsStep extends Component { static contextTypes = { api: PropTypes.object.isRequired - } + }; static propTypes = { accounts: PropTypes.object.isRequired, @@ -256,16 +256,33 @@ export default class DetailsStep extends Component { onFromAddressChange: PropTypes.func.isRequired, onDescriptionChange: PropTypes.func.isRequired, onNameChange: PropTypes.func.isRequired, - onParamsChange: PropTypes.func.isRequired - } + onParamsChange: PropTypes.func.isRequired, + readOnly: PropTypes.bool + }; + + static defaultProps = { + readOnly: false + }; state = { inputs: [] } + componentDidMount () { + const { abi, code } = this.props; + + if (abi) { + this.onAbiChange(abi); + } + + if (code) { + this.onCodeChange(code); + } + } + render () { const { accounts } = this.props; - const { abi, abiError, code, codeError, fromAddress, fromAddressError, name, nameError } = this.props; + const { abi, abiError, code, codeError, fromAddress, fromAddressError, name, nameError, readOnly } = this.props; return (
@@ -287,13 +304,15 @@ export default class DetailsStep extends Component { hint='the abi of the contract to deploy' error={ abiError } value={ abi } - onSubmit={ this.onAbiChange } /> + onSubmit={ this.onAbiChange } + readOnly={ readOnly } /> + onSubmit={ this.onCodeChange } + readOnly={ readOnly } /> { this.renderConstructorInputs() }
); diff --git a/js/src/modals/DeployContract/deployContract.js b/js/src/modals/DeployContract/deployContract.js index 3bcea7c29..d38851ccb 100644 --- a/js/src/modals/DeployContract/deployContract.js +++ b/js/src/modals/DeployContract/deployContract.js @@ -36,8 +36,17 @@ export default class DeployContract extends Component { static propTypes = { accounts: PropTypes.object.isRequired, - onClose: PropTypes.func.isRequired - } + onClose: PropTypes.func.isRequired, + abi: PropTypes.string, + code: PropTypes.string, + readOnly: PropTypes.bool, + source: PropTypes.string + }; + + static defaultProps = { + readOnly: false, + source: '' + }; state = { abi: '', @@ -57,6 +66,31 @@ export default class DeployContract extends Component { deployError: null } + componentWillMount () { + const { abi, code } = this.props; + + if (abi && code) { + this.setState({ abi, code }); + } + } + + componentWillReceiveProps (nextProps) { + const { abi, code } = nextProps; + const newState = {}; + + if (abi !== this.props.abi) { + newState.abi = abi; + } + + if (code !== this.props.code) { + newState.code = code; + } + + if (Object.keys(newState).length) { + this.setState(newState); + } + } + render () { const { step, deployError } = this.state; @@ -116,7 +150,7 @@ export default class DeployContract extends Component { } renderStep () { - const { accounts } = this.props; + const { accounts, readOnly } = this.props; const { address, deployError, step, deployState, txhash } = this.state; if (deployError) { @@ -130,6 +164,7 @@ export default class DeployContract extends Component { return ( { const { api, store } = this.context; + const { source } = this.props; const { abiParsed, code, description, name, params, fromAddress } = this.state; const options = { data: code, @@ -220,6 +256,7 @@ export default class DeployContract extends Component { contract: true, timestamp: Date.now(), deleted: false, + source, description }) ]) diff --git a/js/src/modals/LoadContract/index.js b/js/src/modals/LoadContract/index.js new file mode 100644 index 000000000..be5e62af5 --- /dev/null +++ b/js/src/modals/LoadContract/index.js @@ -0,0 +1,17 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +export default from './loadContract'; diff --git a/js/src/modals/LoadContract/loadContract.css b/js/src/modals/LoadContract/loadContract.css new file mode 100644 index 000000000..f3144eeb8 --- /dev/null +++ b/js/src/modals/LoadContract/loadContract.css @@ -0,0 +1,52 @@ +/* Copyright 2015, 2016 Ethcore (UK) Ltd. +/* This file is part of Parity. +/* +/* Parity is free software: you can redistribute it and/or modify +/* it under the terms of the GNU General Public License as published by +/* the Free Software Foundation, either version 3 of the License, or +/* (at your option) any later version. +/* +/* Parity is distributed in the hope that it will be useful, +/* but WITHOUT ANY WARRANTY; without even the implied warranty of +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +/* GNU General Public License for more details. +/* +/* You should have received a copy of the GNU General Public License +/* along with Parity. If not, see . +*/ + +.loadContainer { + display: flex; + flex-direction: row; + + > * { + flex: 50%; + width: 0; + } +} + +.editor { + display: flex; + flex-direction: column; + padding-left: 1em; + + p { + line-height: 48px; + height: 48px; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + + margin: 0; + font-size: 1.2em; + } +} + +.confirmRemoval { + text-align: center; + + .editor { + text-align: left; + margin-top: 0.5em; + } +} diff --git a/js/src/modals/LoadContract/loadContract.js b/js/src/modals/LoadContract/loadContract.js new file mode 100644 index 000000000..3de55561a --- /dev/null +++ b/js/src/modals/LoadContract/loadContract.js @@ -0,0 +1,284 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import React, { Component, PropTypes } from 'react'; + +import ContentClear from 'material-ui/svg-icons/content/clear'; +import CheckIcon from 'material-ui/svg-icons/navigation/check'; +import DeleteIcon from 'material-ui/svg-icons/action/delete'; + +import { List, ListItem, makeSelectable } from 'material-ui/List'; +import { Subheader, IconButton, Tabs, Tab } from 'material-ui'; +import moment from 'moment'; + +import { Button, Modal, Editor } from '../../ui'; + +import styles from './loadContract.css'; + +const SelectableList = makeSelectable(List); + +const SELECTED_STYLE = { + backgroundColor: 'rgba(255, 255, 255, 0.1)' +}; + +export default class LoadContract extends Component { + + static propTypes = { + onClose: PropTypes.func.isRequired, + onLoad: PropTypes.func.isRequired, + onDelete: PropTypes.func.isRequired, + contracts: PropTypes.object.isRequired, + snippets: PropTypes.object.isRequired + }; + + state = { + selected: -1, + deleteRequest: false, + deleteId: -1 + }; + + render () { + const { deleteRequest } = this.state; + + const title = deleteRequest + ? 'confirm removal' + : 'view contracts'; + + return ( + + { this.renderBody() } + + ); + } + + renderBody () { + if (this.state.deleteRequest) { + return this.renderConfirmRemoval(); + } + + const { contracts, snippets } = this.props; + + const contractsTab = Object.keys(contracts).length === 0 + ? null + : ( + + { this.renderEditor() } + + + Saved Contracts + { this.renderContracts(contracts) } + + + ); + + return ( +
+ + { contractsTab } + + + { this.renderEditor() } + + + Contract Snippets + { this.renderContracts(snippets, false) } + + + +
+ ); + } + + renderConfirmRemoval () { + const { deleteId } = this.state; + const { name, timestamp, sourcecode } = this.props.contracts[deleteId]; + + return ( +
+

+ Are you sure you want to remove the following + contract from your saved contracts? +

+ + +
+ +
+
+ ); + } + + renderEditor () { + const { contracts, snippets } = this.props; + const { selected } = this.state; + + const mergedContracts = Object.assign({}, contracts, snippets); + + if (selected === -1 || !mergedContracts[selected]) { + return null; + } + + const { sourcecode, name } = mergedContracts[selected]; + + return ( +
+

{ name }

+ +
+ ); + } + + renderContracts (contracts, removable = true) { + const { selected } = this.state; + + return Object + .values(contracts) + .map((contract) => { + const { id, name, timestamp, description } = contract; + const onDelete = () => this.onDeleteRequest(id); + + const secondaryText = description || `Saved ${moment(timestamp).fromNow()}`; + const remove = removable + ? ( + + + + ) + : null; + + return ( + + ); + }); + } + + renderDialogActions () { + const { deleteRequest } = this.state; + + if (deleteRequest) { + return [ +
+ ); + } + + renderModal () { + const { title, renderValidation } = this.props; + const { show, step } = this.state; + + if (!show) { + return null; + } + + const hasSteps = typeof renderValidation === 'function'; + + const steps = hasSteps ? [ 'select a file', 'validate' ] : null; + + return ( + + { this.renderBody() } + + ); + } + + renderActions () { + const { validate } = this.state; + + const cancelBtn = ( +
); } + renderDetails (contract) { + const { showDetailsDialog } = this.state; + + if (!showDetailsDialog) { + return null; + } + + const cancelBtn = ( +