diff --git a/.gitignore b/.gitignore index 3226ea5a2..47546d0ed 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,5 @@ # Build artifacts out/ + +.vscode diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index c1fdabd12..5ce186600 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,4 +1,6 @@ stages: + - test + - js-build - build variables: GIT_DEPTH: "3" @@ -6,17 +8,18 @@ variables: RUST_BACKTRACE: "1" RUSTFLAGS: "" CARGOFLAGS: "" + NIGHTLY: "nigtly" cache: - key: "$CI_BUILD_NAME/$CI_BUILD_REF_NAME" + key: "$CI_BUILD_STAGE/$CI_BUILD_REF_NAME" untracked: true linux-stable: stage: build image: ethcore/rust:stable only: - - master - beta - tags - stable + - triggers script: - cargo build --release $CARGOFLAGS - strip target/release/parity @@ -43,10 +46,10 @@ linux-stable-14.04: stage: build image: ethcore/rust-14.04:latest only: - - master - beta - tags - stable + - triggers script: - cargo build --release $CARGOFLAGS - strip target/release/parity @@ -73,10 +76,10 @@ linux-beta: stage: build image: ethcore/rust:beta only: - - master - beta - tags - stable + - triggers script: - cargo build --release $CARGOFLAGS - strip target/release/parity @@ -92,10 +95,10 @@ linux-nightly: stage: build image: ethcore/rust:nightly only: - - master - beta - tags - stable + - triggers script: - cargo build --release $CARGOFLAGS - strip target/release/parity @@ -111,10 +114,10 @@ linux-centos: stage: build image: ethcore/rust-centos:latest only: - - master - beta - tags - stable + - triggers script: - export CXX="g++" - export CC="gcc" @@ -132,14 +135,47 @@ linux-centos: paths: - target/release/parity name: "x86_64-unknown-centos-gnu_parity" +linux-i686: + stage: build + image: ethcore/rust-i686:latest + only: + - beta + - tags + - stable + - triggers + script: + - export HOST_CC=gcc + - export HOST_CXX=g++ + - cargo build --target i686-unknown-linux-gnu --release $CARGOFLAGS + - strip target/i686-unknown-linux-gnu/release/parity + - md5sum target/i686-unknown-linux-gnu/release/parity >> parity.md5 + - sh scripts/deb-build.sh i386 + - cp target/i686-unknown-linux-gnu/release/parity deb/usr/bin/parity + - export VER=$(grep -m 1 version Cargo.toml | awk '{print $3}' | tr -d '"' | tr -d "\n") + - dpkg-deb -b deb "parity_"$VER"_i386.deb" + - md5sum "parity_"$VER"_i386.deb" >> "parity_"$VER"_i386.deb.md5" + - aws configure set aws_access_key_id $s3_key + - aws configure set aws_secret_access_key $s3_secret + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/i686-unknown-linux-gnu/parity --body target/i686-unknown-linux-gnu/release/parity + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/i686-unknown-linux-gnu/parity.md5 --body parity.md5 + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/i686-unknown-linux-gnu/"parity_"$VER"_i386.deb" --body "parity_"$VER"_i386.deb" + - aws s3api put-object --bucket builds-parity --key $CI_BUILD_REF_NAME/i686-unknown-linux-gnu/"parity_"$VER"_i386.deb.md5" --body "parity_"$VER"_i386.deb.md5" + tags: + - rust + - rust-i686 + artifacts: + paths: + - target/i686-unknown-linux-gnu/release/parity + name: "i686-unknown-linux-gnu" + allow_failure: true linux-armv7: stage: build image: ethcore/rust-armv7:latest only: - - master - beta - tags - stable + - triggers script: - export CC=arm-linux-gnueabihf-gcc - export CXX=arm-linux-gnueabihf-g++ @@ -176,10 +212,10 @@ linux-arm: stage: build image: ethcore/rust-arm:latest only: - - master - beta - tags - stable + - triggers script: - export CC=arm-linux-gnueabihf-gcc - export CXX=arm-linux-gnueabihf-g++ @@ -219,6 +255,7 @@ linux-armv6: - beta - tags - stable + - triggers script: - export CC=arm-linux-gnueabi-gcc - export CXX=arm-linux-gnueabi-g++ @@ -248,10 +285,10 @@ linux-aarch64: stage: build image: ethcore/rust-aarch64:latest only: - - master - beta - tags - stable + - triggers script: - export CC=aarch64-linux-gnu-gcc - export CXX=aarch64-linux-gnu-g++ @@ -287,10 +324,10 @@ linux-aarch64: darwin: stage: build only: - - master - beta - tags - stable + - triggers script: - cargo build --release $CARGOFLAGS - rm -rf parity.md5 @@ -306,12 +343,15 @@ darwin: - target/release/parity name: "x86_64-apple-darwin_parity" windows: + cache: + key: "%CI_BUILD_STAGE%/%CI_BUILD_REF_NAME%" + untracked: true stage: build only: - - master - beta - tags - stable + - triggers script: - set INCLUDE=C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Include;C:\vs2015\VC\include;C:\Program Files (x86)\Windows Kits\10\Include\10.0.10240.0\ucrt - set LIB=C:\vs2015\VC\lib;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\ucrt\x64 @@ -322,6 +362,8 @@ windows: - curl -sL --url "https://github.com/ethcore/win-build/raw/master/SimpleFC.dll" -o nsis\SimpleFC.dll - curl -sL --url "https://github.com/ethcore/win-build/raw/master/vc_redist.x64.exe" -o nsis\vc_redist.x64.exe - signtool sign /f %keyfile% /p %certpass% target\release\parity.exe + - msbuild windows\ptray\ptray.vcxproj /p:Platform=x64 /p:Configuration=Release + - signtool sign /f %keyfile% /p %certpass% windows\ptray\x64\release\ptray.exe - cd nsis - makensis.exe installer.nsi - copy installer.exe InstallParity.exe @@ -353,39 +395,100 @@ windows: - target/release/parity.pdb - nsis/InstallParity.exe name: "x86_64-pc-windows-msvc_parity" -#test-darwin: -# stage: build -# before_script: -# - git submodule update --init --recursive -# script: -# - export RUST_BACKTRACE=1 -# - ./test.sh $CARGOFLAGS --no-release -# tags: -# - osx -#test-windows: -# stage: build -# before_script: -# - git submodule update --init --recursive -# script: -# - set RUST_BACKTRACE=1 -# - cargo test --features json-tests -p rlp -p ethash -p ethcore -p ethcore-bigint -p ethcore-dapps -p ethcore-rpc -p ethcore-signer -p ethcore-util -p ethcore-network -p ethcore-io -p ethkey -p ethstore -p ethsync -p ethcore-ipc -p ethcore-ipc-tests -p ethcore-ipc-nano -p parity %CARGOFLAGS% --verbose --release -# tags: -# - rust-windows -# allow_failure: true -test-linux: - stage: build +test-darwin: + stage: test + only: + - triggers before_script: - git submodule update --init --recursive script: - export RUST_BACKTRACE=1 - ./test.sh $CARGOFLAGS --no-release tags: - - rust-test + - osx + allow_failure: true +test-windows: + stage: test + only: + - triggers + before_script: + - git submodule update --init --recursive + script: + - set RUST_BACKTRACE=1 + - cargo test --features json-tests -p rlp -p ethash -p ethcore -p ethcore-bigint -p ethcore-dapps -p ethcore-rpc -p ethcore-signer -p ethcore-util -p ethcore-network -p ethcore-io -p ethkey -p ethstore -p ethsync -p ethcore-ipc -p ethcore-ipc-tests -p ethcore-ipc-nano -p parity %CARGOFLAGS% --verbose --release + tags: + - rust-windows + allow_failure: true +test-rust-stable: + stage: test + image: ethcore/rust:stable + before_script: + - git submodule update --init --recursive + - export JS_FILES_MODIFIED=$(git --no-pager diff --name-only CI_BUILD_REF CI_BUILD_REF@{1} | grep \.js | wc -l) + - echo $JS_FILES_MODIFIED + - if [ -z $JS_FILES_MODIFIED ]; then echo "skip js test"; fi + script: + - export RUST_BACKTRACE=1 + - echo $JS_FILES_MODIFIED + - if [ -z $JS_FILES_MODIFIED ]; then echo "skip js test"; else ./test.sh $CARGOFLAGS --no-release; fi + tags: + - rust + - rust-stable +test-rust-beta: + stage: test + only: + - triggers + image: ethcore/rust:beta + before_script: + - git submodule update --init --recursive + - export JS_FILES_MODIFIED=$(git --no-pager diff --name-only CI_BUILD_REF CI_BUILD_REF@{1} | grep \.js | wc -l) + - echo $JS_FILES_MODIFIED + - if [ -z $JS_FILES_MODIFIED ]; then echo "skip js test"; fi + script: + - export RUST_BACKTRACE=1 + - echo $JS_FILES_MODIFIED + - if [ -z $JS_FILES_MODIFIED ]; then echo "skip js test"; else ./test.sh $CARGOFLAGS --no-release; fi + tags: + - rust + - rust-beta + allow_failure: true +test-rust-nightly: + stage: test + only: + - triggers + image: ethcore/rust:nightly + before_script: + - git submodule update --init --recursive + - export JS_FILES_MODIFIED=$(git --no-pager diff --name-only CI_BUILD_REF CI_BUILD_REF@{1} | grep \.js | wc -l) + - echo $JS_FILES_MODIFIED + - if [ -z $JS_FILES_MODIFIED ]; then echo "skip js test"; fi + script: + - export RUST_BACKTRACE=1 + - echo $JS_FILES_MODIFIED + - if [ -z $JS_FILES_MODIFIED ]; then echo "skip js test"; else ./test.sh $CARGOFLAGS --no-release; fi + tags: + - rust + - rust-nightly + allow_failure: true +js-tests: + stage: test + image: ethcore/rust:stable + before_script: + - ./js/scripts/install-deps.sh + script: + - ./js/scripts/lint.sh + - ./js/scripts/test.sh + - ./js/scripts/build.sh + tags: + - javascript-test js-release: - stage: build - image: ethcore/javascript:latest + stage: js-build only: - master + - beta + - stable + - tags + image: ethcore/rust:stable before_script: - ./js/scripts/install-deps.sh script: @@ -393,30 +496,3 @@ js-release: - ./js/scripts/release.sh tags: - javascript -js-lint: - stage: build - image: ethcore/javascript:latest - before_script: - - ./js/scripts/install-deps.sh - script: - - ./js/scripts/lint.sh - tags: - - javascript-test -js-test: - stage: build - image: ethcore/javascript:latest - before_script: - - ./js/scripts/install-deps.sh - script: - - ./js/scripts/test.sh - tags: - - javascript-test -js-pack: - stage: build - image: ethcore/javascript:latest - before_script: - - ./js/scripts/install-deps.sh - script: - - ./js/scripts/build.sh - tags: - - javascript-test diff --git a/Cargo.lock b/Cargo.lock index b5e47dde2..b69b439c2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ [root] name = "parity" -version = "1.4.0" +version = "1.5.0" dependencies = [ "ansi_term 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", "clippy 0.0.96 (registry+https://github.com/rust-lang/crates.io-index)", @@ -8,21 +8,21 @@ dependencies = [ "daemonize 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "docopt 0.6.80 (registry+https://github.com/rust-lang/crates.io-index)", "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", - "ethcore 1.4.0", - "ethcore-dapps 1.4.0", + "ethcore 1.5.0", + "ethcore-dapps 1.5.0", "ethcore-devtools 1.4.0", - "ethcore-io 1.4.0", + "ethcore-io 1.5.0", "ethcore-ipc 1.4.0", "ethcore-ipc-codegen 1.4.0", "ethcore-ipc-hypervisor 1.2.0", "ethcore-ipc-nano 1.4.0", "ethcore-ipc-tests 0.1.0", - "ethcore-logger 1.4.0", - "ethcore-rpc 1.4.0", - "ethcore-signer 1.4.0", + "ethcore-logger 1.5.0", + "ethcore-rpc 1.5.0", + "ethcore-signer 1.5.0", "ethcore-stratum 1.4.0", - "ethcore-util 1.4.0", - "ethsync 1.4.0", + "ethcore-util 1.5.0", + "ethsync 1.5.0", "fdlimit 0.1.0", "hyper 0.9.10 (registry+https://github.com/rust-lang/crates.io-index)", "isatty 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -185,7 +185,7 @@ version = "1.1.1" source = "git+https://github.com/ethcore/rust-ctrlc.git#f4927770f89eca80ec250911eea3adcbf579ac48" dependencies = [ "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -194,7 +194,7 @@ name = "daemonize" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -244,7 +244,7 @@ source = "git+https://github.com/ethcore/rust-secp256k1#a9a0b1be1f39560ca86e8fc8 dependencies = [ "arrayvec 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)", "gcc 0.3.35 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -274,7 +274,7 @@ dependencies = [ [[package]] name = "ethcore" -version = "1.4.0" +version = "1.5.0" dependencies = [ "bit-set 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "bloomchain 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -285,11 +285,11 @@ dependencies = [ "ethash 1.4.0", "ethcore-bloom-journal 0.1.0", "ethcore-devtools 1.4.0", - "ethcore-io 1.4.0", + "ethcore-io 1.5.0", "ethcore-ipc 1.4.0", "ethcore-ipc-codegen 1.4.0", "ethcore-ipc-nano 1.4.0", - "ethcore-util 1.4.0", + "ethcore-util 1.5.0", "ethjson 0.1.0", "ethkey 0.2.0", "ethstore 0.1.0", @@ -312,7 +312,7 @@ dependencies = [ [[package]] name = "ethcore-bigint" -version = "0.1.1" +version = "0.1.2" dependencies = [ "heapsize 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", @@ -329,14 +329,14 @@ dependencies = [ [[package]] name = "ethcore-dapps" -version = "1.4.0" +version = "1.5.0" dependencies = [ "clippy 0.0.96 (registry+https://github.com/rust-lang/crates.io-index)", "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "ethabi 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "ethcore-devtools 1.4.0", - "ethcore-rpc 1.4.0", - "ethcore-util 1.4.0", + "ethcore-rpc 1.5.0", + "ethcore-util 1.5.0", "fetch 0.1.0", "hyper 0.9.4 (git+https://github.com/ethcore/hyper)", "jsonrpc-core 3.0.2 (registry+https://github.com/rust-lang/crates.io-index)", @@ -352,6 +352,7 @@ dependencies = [ "serde 0.8.4 (registry+https://github.com/rust-lang/crates.io-index)", "serde_codegen 0.8.4 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", + "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", "unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "url 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "zip 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)", @@ -366,11 +367,11 @@ dependencies = [ [[package]] name = "ethcore-io" -version = "1.4.0" +version = "1.5.0" dependencies = [ "crossbeam 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.6.0 (git+https://github.com/carllerche/mio)", + "mio 0.6.1 (git+https://github.com/carllerche/mio)", "parking_lot 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", "slab 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -380,7 +381,7 @@ name = "ethcore-ipc" version = "1.4.0" dependencies = [ "ethcore-devtools 1.4.0", - "ethcore-util 1.4.0", + "ethcore-util 1.5.0", "nanomsg 0.5.1 (git+https://github.com/ethcore/nanomsg.rs.git)", "semver 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -427,7 +428,7 @@ dependencies = [ "ethcore-ipc 1.4.0", "ethcore-ipc-codegen 1.4.0", "ethcore-ipc-nano 1.4.0", - "ethcore-util 1.4.0", + "ethcore-util 1.5.0", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "nanomsg 0.5.1 (git+https://github.com/ethcore/nanomsg.rs.git)", "semver 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -435,10 +436,10 @@ dependencies = [ [[package]] name = "ethcore-logger" -version = "1.4.0" +version = "1.5.0" dependencies = [ "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", - "ethcore-util 1.4.0", + "ethcore-util 1.5.0", "isatty 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", @@ -448,19 +449,19 @@ dependencies = [ [[package]] name = "ethcore-network" -version = "1.4.0" +version = "1.5.0" dependencies = [ "ansi_term 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", "bytes 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "ethcore-devtools 1.4.0", - "ethcore-io 1.4.0", - "ethcore-util 1.4.0", + "ethcore-io 1.5.0", + "ethcore-util 1.5.0", "ethcrypto 0.1.0", "ethkey 0.2.0", "igd 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.6.0 (git+https://github.com/carllerche/mio)", + "mio 0.6.1 (git+https://github.com/carllerche/mio)", "parking_lot 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "rlp 0.1.0", @@ -473,20 +474,20 @@ dependencies = [ [[package]] name = "ethcore-rpc" -version = "1.4.0" +version = "1.5.0" dependencies = [ "clippy 0.0.96 (registry+https://github.com/rust-lang/crates.io-index)", "ethash 1.4.0", - "ethcore 1.4.0", + "ethcore 1.5.0", "ethcore-devtools 1.4.0", - "ethcore-io 1.4.0", + "ethcore-io 1.5.0", "ethcore-ipc 1.4.0", - "ethcore-util 1.4.0", + "ethcore-util 1.5.0", "ethcrypto 0.1.0", "ethjson 0.1.0", "ethkey 0.2.0", "ethstore 0.1.0", - "ethsync 1.4.0", + "ethsync 1.5.0", "fetch 0.1.0", "json-ipc-server 0.2.4 (git+https://github.com/ethcore/json-ipc-server.git)", "jsonrpc-core 3.0.2 (registry+https://github.com/rust-lang/crates.io-index)", @@ -503,14 +504,14 @@ dependencies = [ [[package]] name = "ethcore-signer" -version = "1.4.0" +version = "1.5.0" dependencies = [ "clippy 0.0.96 (registry+https://github.com/rust-lang/crates.io-index)", "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "ethcore-devtools 1.4.0", - "ethcore-io 1.4.0", - "ethcore-rpc 1.4.0", - "ethcore-util 1.4.0", + "ethcore-io 1.5.0", + "ethcore-rpc 1.5.0", + "ethcore-util 1.5.0", "jsonrpc-core 3.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-dapps-glue 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -529,7 +530,7 @@ dependencies = [ "ethcore-ipc 1.4.0", "ethcore-ipc-codegen 1.4.0", "ethcore-ipc-nano 1.4.0", - "ethcore-util 1.4.0", + "ethcore-util 1.5.0", "json-tcp-server 0.1.0 (git+https://github.com/ethcore/json-tcp-server)", "jsonrpc-core 3.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -540,7 +541,7 @@ dependencies = [ [[package]] name = "ethcore-util" -version = "1.4.0" +version = "1.5.0" dependencies = [ "ansi_term 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", "arrayvec 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)", @@ -548,13 +549,13 @@ dependencies = [ "elastic-array 0.6.0 (git+https://github.com/ethcore/elastic-array)", "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "eth-secp256k1 0.5.4 (git+https://github.com/ethcore/rust-secp256k1)", - "ethcore-bigint 0.1.1", + "ethcore-bigint 0.1.2", "ethcore-bloom-journal 0.1.0", "ethcore-devtools 1.4.0", "heapsize 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "itertools 0.4.13 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "lru-cache 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", @@ -579,7 +580,7 @@ name = "ethcrypto" version = "0.1.0" dependencies = [ "eth-secp256k1 0.5.4 (git+https://github.com/ethcore/rust-secp256k1)", - "ethcore-bigint 0.1.1", + "ethcore-bigint 0.1.2", "ethkey 0.2.0", "rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)", "tiny-keccak 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", @@ -589,7 +590,7 @@ dependencies = [ name = "ethjson" version = "0.1.0" dependencies = [ - "ethcore-util 1.4.0", + "ethcore-util 1.5.0", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "serde 0.8.4 (registry+https://github.com/rust-lang/crates.io-index)", "serde_codegen 0.8.4 (registry+https://github.com/rust-lang/crates.io-index)", @@ -602,7 +603,7 @@ version = "0.2.0" dependencies = [ "docopt 0.6.80 (registry+https://github.com/rust-lang/crates.io-index)", "eth-secp256k1 0.5.4 (git+https://github.com/ethcore/rust-secp256k1)", - "ethcore-bigint 0.1.1", + "ethcore-bigint 0.1.2", "lazy_static 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", @@ -618,7 +619,7 @@ dependencies = [ "ethkey 0.2.0", "itertools 0.4.13 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)", @@ -632,17 +633,17 @@ dependencies = [ [[package]] name = "ethsync" -version = "1.4.0" +version = "1.5.0" dependencies = [ "clippy 0.0.96 (registry+https://github.com/rust-lang/crates.io-index)", "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", - "ethcore 1.4.0", - "ethcore-io 1.4.0", + "ethcore 1.5.0", + "ethcore-io 1.5.0", "ethcore-ipc 1.4.0", "ethcore-ipc-codegen 1.4.0", "ethcore-ipc-nano 1.4.0", - "ethcore-network 1.4.0", - "ethcore-util 1.4.0", + "ethcore-network 1.5.0", + "ethcore-util 1.5.0", "heapsize 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", @@ -663,7 +664,7 @@ dependencies = [ name = "fdlimit" version = "0.1.0" dependencies = [ - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -681,7 +682,7 @@ name = "flate2" version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "miniz-sys 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -802,7 +803,7 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -894,7 +895,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "libc" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -930,7 +931,7 @@ name = "memchr" version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -958,7 +959,7 @@ version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "gcc 0.3.35 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -967,7 +968,7 @@ version = "0.5.1" source = "git+https://github.com/ethcore/mio?branch=v0.5.x#3842d3b250ffd7bd9b16f9586b875ddcbac2b0dd" dependencies = [ "bytes 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "miow 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", @@ -983,7 +984,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "bytes 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "miow 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", @@ -999,7 +1000,7 @@ version = "0.6.0-dev" source = "git+https://github.com/ethcore/mio?branch=timer-fix#31eccc40ece3d47abaefaf23bb2114033175b972" dependencies = [ "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "miow 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1010,16 +1011,16 @@ dependencies = [ [[package]] name = "mio" -version = "0.6.0" -source = "git+https://github.com/carllerche/mio#9f17b70d6fecbf912168267ea74cf536f2cba705" +version = "0.6.1" +source = "git+https://github.com/carllerche/mio#56f8663510196fdca04bdf7c5f4d60b24297826f" dependencies = [ "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "lazycell 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "miow 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)", - "nix 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "nix 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "slab 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1050,7 +1051,7 @@ name = "nanomsg" version = "0.5.1" source = "git+https://github.com/ethcore/nanomsg.rs.git#c40fe442c9afaea5b38009a3d992ca044dcceb00" dependencies = [ - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "nanomsg-sys 0.5.0 (git+https://github.com/ethcore/nanomsg.rs.git)", ] @@ -1060,7 +1061,7 @@ version = "0.5.0" source = "git+https://github.com/ethcore/nanomsg.rs.git#c40fe442c9afaea5b38009a3d992ca044dcceb00" dependencies = [ "gcc 0.3.35 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1070,7 +1071,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cfg-if 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", "ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1081,7 +1082,7 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "bitflags 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1091,7 +1092,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "bitflags 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "cfg-if 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "semver 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)", + "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "nix" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", "semver 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)", "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1181,7 +1195,7 @@ name = "num_cpus" version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1235,7 +1249,7 @@ dependencies = [ [[package]] name = "parity-ui-precompiled" version = "1.4.0" -source = "git+https://github.com/ethcore/js-precompiled.git#8e8432d2986c29e9ff4c338cb4d2a11bc9c3c557" +source = "git+https://github.com/ethcore/js-precompiled.git#4c885041fd0bbb0ef012a97679abad3d04802713" dependencies = [ "parity-dapps-glue 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1246,7 +1260,7 @@ version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "smallvec 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1266,7 +1280,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "smallvec 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1405,7 +1419,7 @@ name = "rand" version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1449,7 +1463,7 @@ name = "rlp" version = "0.1.0" dependencies = [ "elastic-array 0.6.0 (git+https://github.com/ethcore/elastic-array)", - "ethcore-bigint 0.1.1", + "ethcore-bigint 0.1.2", "lazy_static 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1459,7 +1473,7 @@ name = "rocksdb" version = "0.4.5" source = "git+https://github.com/ethcore/rust-rocksdb#64c63ccbe1f62c2e2b39262486f9ba813793af58" dependencies = [ - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "rocksdb-sys 0.3.0 (git+https://github.com/ethcore/rust-rocksdb)", ] @@ -1469,7 +1483,7 @@ version = "0.3.0" source = "git+https://github.com/ethcore/rust-rocksdb#64c63ccbe1f62c2e2b39262486f9ba813793af58" dependencies = [ "gcc 0.3.35 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1489,7 +1503,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "termios 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1500,7 +1514,7 @@ version = "0.2.36" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "gcc 0.3.35 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1671,7 +1685,7 @@ name = "syntex_errors" version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "syntex_pos 0.42.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1693,7 +1707,7 @@ version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "bitflags 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "term 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1706,7 +1720,7 @@ version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "bitflags 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", "syntex_errors 0.42.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1747,7 +1761,7 @@ name = "termios" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1756,7 +1770,7 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1773,7 +1787,7 @@ version = "0.1.35" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)", "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -2012,7 +2026,7 @@ dependencies = [ "checksum language-tags 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a91d884b6667cd606bb5a69aa0c99ba811a115fc68915e7056ec08a46e93199a" "checksum lazy_static 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "49247ec2a285bb3dcb23cbd9c35193c025e7251bfce77c1d5da97e6362dffe7f" "checksum lazycell 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ce12306c4739d86ee97c23139f3a34ddf0387bbf181bc7929d287025a8c3ef6b" -"checksum libc 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)" = "23e3757828fa702a20072c37ff47938e9dd331b92fac6e223d26d4b7a55f7ee2" +"checksum libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)" = "408014cace30ee0f767b1c4517980646a573ec61a57957aeeabcac8ac0a02e8d" "checksum linked-hash-map 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "bda158e0dabeb97ee8a401f4d17e479d6b891a14de0bba79d5cc2d4d325b5e48" "checksum linked-hash-map 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6d262045c5b87c0861b3f004610afd0e2c851e2908d08b6c870cbb9d5f494ecd" "checksum log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "ab83497bf8bf4ed2a74259c1c802351fcd67a65baa86394b6ba73c36f4838054" @@ -2024,8 +2038,8 @@ dependencies = [ "checksum miniz-sys 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "9d1f4d337a01c32e1f2122510fed46393d53ca35a7f429cb0450abaedfa3ed54" "checksum mio 0.5.1 (git+https://github.com/ethcore/mio?branch=v0.5.x)" = "" "checksum mio 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a637d1ca14eacae06296a008fa7ad955347e34efcb5891cfd8ba05491a37907e" -"checksum mio 0.6.0 (git+https://github.com/carllerche/mio)" = "" "checksum mio 0.6.0-dev (git+https://github.com/ethcore/mio?branch=timer-fix)" = "" +"checksum mio 0.6.1 (git+https://github.com/carllerche/mio)" = "" "checksum miow 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d5bfc6782530ac8ace97af10a540054a37126b63b0702ddaaa243b73b5745b9a" "checksum msdos_time 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "c04b68cc63a8480fb2550343695f7be72effdec953a9d4508161c3e69041c7d8" "checksum nanomsg 0.5.1 (git+https://github.com/ethcore/nanomsg.rs.git)" = "" @@ -2033,6 +2047,7 @@ dependencies = [ "checksum net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)" = "6a816012ca11cb47009693c1e0c6130e26d39e4d97ee2a13c50e868ec83e3204" "checksum nix 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f05c2fc965fc1cd6b73fa57fa7b89f288178737f2f3ce9e63e4a6a141189000e" "checksum nix 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7a7bb1da2be7da3cbffda73fc681d509ffd9e665af478d2bee1907cee0bc64b2" +"checksum nix 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a0d95c5fa8b641c10ad0b8887454ebaafa3c92b5cd5350f8fc693adafd178e7b" "checksum nodrop 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "4d9a22dbcebdeef7bf275cbf444d6521d4e7a2fee187b72d80dba0817120dd8f" "checksum nom 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6caab12c5f97aa316cb249725aa32115118e1522b445e26c257dd77cad5ffd4e" "checksum num 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)" = "c04bd954dbf96f76bab6e5bd6cef6f1ce1262d15268ce4f926d2b5b778fa7af2" diff --git a/Cargo.toml b/Cargo.toml index dc802a0fd..fe72d67ec 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] description = "Ethcore client." name = "parity" -version = "1.4.0" +version = "1.5.0" license = "GPL-3.0" authors = ["Ethcore "] build = "build.rs" diff --git a/README.md b/README.md index 08c04c097..fc5cd9762 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,12 @@ # [Parity](https://ethcore.io/parity.html) ### Fast, light, and robust Ethereum implementation -[![Join the chat at https://gitter.im/ethcore/parity.js](https://badges.gitter.im/ethcore/parity.js.svg)](https://gitter.im/ethcore/parity.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![Build Status][travis-image]][travis-url] [![build status](https://gitlab.ethcore.io/Mirrors/ethcore-parity/badges/master/build.svg)](https://gitlab.ethcore.io/Mirrors/ethcore-parity/commits/master) [![Coverage Status][coveralls-image]][coveralls-url] [![GPLv3][license-image]][license-url] -[![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![Join the chat at https://gitter.im/ethcore/parity][gitter-image]][gitter-url] [![GPLv3][license-image]][license-url] +### Join the chat! + +Parity [![Join the chat at https://gitter.im/ethcore/parity][gitter-image]][gitter-url] and +parity.js [![Join the chat at https://gitter.im/ethcore/parity.js](https://badges.gitter.im/ethcore/parity.js.svg)](https://gitter.im/ethcore/parity.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [Internal Documentation][doc-url] @@ -21,7 +24,7 @@ Be sure to check out [our wiki][wiki-url] for more information. [doc-url]: https://ethcore.github.io/parity/ethcore/index.html [wiki-url]: https://github.com/ethcore/parity/wiki -**Requires Rust version 1.12.0 to build** +**Parity requires Rust version 1.12.0 to build** ---- @@ -31,12 +34,15 @@ Be sure to check out [our wiki][wiki-url] for more information. Parity's goal is to be the fastest, lightest, and most secure Ethereum client. We are developing Parity using the sophisticated and cutting-edge Rust programming language. Parity is licensed under the GPLv3, and can be used for all your Ethereum needs. -By default, Parity will run a JSONRPC server on `127.0.0.1:8545`. This is fully configurable and supports a number -of RPC APIs. +Parity comes with a built-in wallet. To access [Parity Wallet](http://127.0.0.1:8080/) this simply go to http://127.0.0.1:8080/. It +includes various functionality allowing you to: +- create and manage your Ethereum accounts; +- manage your Ether and any Ethereum tokens; +- create and register your own tokens; +- and much more. -Parity also runs a server for running decentralized apps, or "Dapps", on `http://127.0.0.1:8080`. -This includes a few useful Dapps, including Ethereum Wallet, Maker OTC, and a node status page. -In a near-future release, it will be easy to install Dapps and use them through this web interface. +By default, Parity will also run a JSONRPC server on `127.0.0.1:8545`. This is fully configurable and supports a number +of RPC APIs. If you run into an issue while using parity, feel free to file one in this repository or hop on our [gitter chat room][gitter-url] to ask a question. We are glad to help! @@ -56,7 +62,14 @@ We recommend installing Rust through [rustup](https://www.rustup.rs/). If you do ```bash $ curl https://sh.rustup.rs -sSf | sh ``` + + Parity also requires `gcc`, `g++` and `make` packages to be installed. +- OSX: + ```bash + $ curl https://sh.rustup.rs -sSf | sh + ``` + `clang` and `make` are required. These come with Xcode command line tools or can be installed with homebrew. - Windows Make sure you have Visual Studio 2015 with C++ support installed. Next, download and run the rustup installer from diff --git a/appveyor.yml b/appveyor.yml index 75a2da7cb..ad6b2b2a3 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -38,6 +38,8 @@ after_test: - cargo build --verbose --release - ps: if($env:cert) { Start-FileDownload $env:cert -FileName $env:keyfile } - ps: if($env:cert) { signtool sign /f $env:keyfile /p $env:certpass target\release\parity.exe } + - msbuild windows\ptray\ptray.vcxproj /p:Platform=x64 /p:Configuration=Release + - ps: if($env:cert) { signtool sign /f $env:keyfile /p $env:certpass windows\ptray\x64\release\ptray.exe } - makensis.exe nsis\installer.nsi - ps: if($env:cert) { signtool sign /f $env:keyfile /p $env:certpass nsis\installer.exe } diff --git a/dapps/Cargo.toml b/dapps/Cargo.toml index ddc23c87c..f6e9d102d 100644 --- a/dapps/Cargo.toml +++ b/dapps/Cargo.toml @@ -1,7 +1,7 @@ [package] description = "Parity Dapps crate" name = "ethcore-dapps" -version = "1.4.0" +version = "1.5.0" license = "GPL-3.0" authors = ["Ethcore { dapps_path: PathBuf, @@ -71,12 +72,13 @@ impl ContentFetcher { } } - fn still_syncing() -> Box { + fn still_syncing(port: Option) -> Box { Box::new(ContentHandler::error( StatusCode::ServiceUnavailable, "Sync In Progress", "Your node is still syncing. We cannot resolve any content before it's fully synced.", - Some("Refresh") + Some("Refresh"), + port, )) } @@ -143,19 +145,19 @@ impl ContentFetcher { match content { // Don't serve dapps if we are still syncing (but serve content) Some(URLHintResult::Dapp(_)) if self.sync.is_major_importing() => { - (None, Self::still_syncing()) + (None, Self::still_syncing(self.embeddable_at)) }, Some(URLHintResult::Dapp(dapp)) => { let (handler, fetch_control) = ContentFetcherHandler::new( dapp.url(), control, - path.using_dapps_domains, DappInstaller { id: content_id.clone(), dapps_path: self.dapps_path.clone(), on_done: Box::new(on_done), embeddable_at: self.embeddable_at, - } + }, + self.embeddable_at, ); (Some(ContentStatus::Fetching(fetch_control)), Box::new(handler) as Box) @@ -164,19 +166,19 @@ impl ContentFetcher { let (handler, fetch_control) = ContentFetcherHandler::new( content.url, control, - path.using_dapps_domains, ContentInstaller { id: content_id.clone(), mime: content.mime, content_path: self.dapps_path.clone(), on_done: Box::new(on_done), - } + }, + self.embeddable_at, ); (Some(ContentStatus::Fetching(fetch_control)), Box::new(handler) as Box) }, None if self.sync.is_major_importing() => { - (None, Self::still_syncing()) + (None, Self::still_syncing(self.embeddable_at)) }, None => { // This may happen when sync status changes in between @@ -185,7 +187,8 @@ impl ContentFetcher { StatusCode::NotFound, "Resource Not Found", "Requested resource was not found.", - None + None, + self.embeddable_at, )) as Box) }, } @@ -255,6 +258,17 @@ impl ContentValidator for ContentInstaller { // Create dir try!(fs::create_dir_all(&self.content_path)); + // Validate hash + let mut file_reader = io::BufReader::new(try!(fs::File::open(&path))); + let hash = try!(sha3(&mut file_reader)); + let id = try!(self.id.as_str().parse().map_err(|_| ValidationError::InvalidContentId)); + if id != hash { + return Err(ValidationError::HashMismatch { + expected: id, + got: hash, + }); + } + // And prepare path for a file let filename = path.file_name().expect("We always fetch a file."); let mut content_path = self.content_path.clone(); @@ -266,7 +280,7 @@ impl ContentValidator for ContentInstaller { try!(fs::copy(&path, &content_path)); - Ok((self.id.clone(), LocalPageEndpoint::single_file(content_path, self.mime.clone()))) + Ok((self.id.clone(), LocalPageEndpoint::single_file(content_path, self.mime.clone(), PageCache::Enabled))) } fn done(&self, endpoint: Option) { @@ -372,7 +386,7 @@ impl ContentValidator for DappInstaller { try!(manifest_file.write_all(manifest_str.as_bytes())); // Create endpoint - let app = LocalPageEndpoint::new(target, manifest.clone().into(), self.embeddable_at); + let app = LocalPageEndpoint::new(target, manifest.clone().into(), PageCache::Enabled, self.embeddable_at); // Return modified app manifest Ok((manifest.id.clone(), app)) @@ -412,7 +426,7 @@ mod tests { version: "".into(), author: "".into(), icon_url: "".into(), - }, None); + }, Default::default(), None); // when fetcher.set_status("test", ContentStatus::Ready(handler)); diff --git a/dapps/src/apps/fs.rs b/dapps/src/apps/fs.rs index e7a11fc8e..104b33035 100644 --- a/dapps/src/apps/fs.rs +++ b/dapps/src/apps/fs.rs @@ -18,7 +18,7 @@ use std::io; use std::io::Read; use std::fs; use std::path::PathBuf; -use page::LocalPageEndpoint; +use page::{LocalPageEndpoint, PageCache}; use endpoint::{Endpoints, EndpointInfo}; use apps::manifest::{MANIFEST_FILENAME, deserialize_manifest}; @@ -102,7 +102,7 @@ pub fn local_endpoints(dapps_path: String, signer_port: Option) -> Endpoint for dapp in local_dapps(dapps_path) { pages.insert( dapp.id, - Box::new(LocalPageEndpoint::new(dapp.path, dapp.info, signer_port)) + Box::new(LocalPageEndpoint::new(dapp.path, dapp.info, PageCache::Disabled, signer_port)) ); } pages diff --git a/dapps/src/apps/mod.rs b/dapps/src/apps/mod.rs index a7b97d37c..11919d6d2 100644 --- a/dapps/src/apps/mod.rs +++ b/dapps/src/apps/mod.rs @@ -33,14 +33,6 @@ pub const RPC_PATH : &'static str = "rpc"; pub const API_PATH : &'static str = "api"; pub const UTILS_PATH : &'static str = "parity-utils"; -pub fn redirection_address(using_dapps_domains: bool, app_id: &str) -> String { - if using_dapps_domains { - format!("http://{}{}/", app_id, DAPPS_DOMAIN) - } else { - format!("/{}/", app_id) - } -} - pub fn utils() -> Box { Box::new(PageEndpoint::with_prefix(parity_ui::App::default(), UTILS_PATH.to_owned())) } diff --git a/dapps/src/handlers/content.rs b/dapps/src/handlers/content.rs index 6bde9cf84..a67fbcd0b 100644 --- a/dapps/src/handlers/content.rs +++ b/dapps/src/handlers/content.rs @@ -48,11 +48,7 @@ impl ContentHandler { Self::new_embeddable(code, content, mime!(Text/Html), embeddable_at) } - pub fn error(code: StatusCode, title: &str, message: &str, details: Option<&str>) -> Self { - Self::error_embeddable(code, title, message, details, None) - } - - pub fn error_embeddable(code: StatusCode, title: &str, message: &str, details: Option<&str>, embeddable_at: Option) -> Self { + pub fn error(code: StatusCode, title: &str, message: &str, details: Option<&str>, embeddable_at: Option) -> Self { Self::html(code, format!( include_str!("../error_tpl.html"), title=title, diff --git a/dapps/src/handlers/fetch.rs b/dapps/src/handlers/fetch.rs index 639fc7497..1a0221bff 100644 --- a/dapps/src/handlers/fetch.rs +++ b/dapps/src/handlers/fetch.rs @@ -22,14 +22,14 @@ use std::sync::{mpsc, Arc}; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Instant, Duration}; use util::Mutex; +use url::Url; use fetch::{Client, Fetch, FetchResult}; use hyper::{server, Decoder, Encoder, Next, Method, Control}; use hyper::net::HttpStream; use hyper::status::StatusCode; -use handlers::{ContentHandler, Redirection}; -use apps::redirection_address; +use handlers::{ContentHandler, Redirection, extract_url}; use page::LocalPageEndpoint; const FETCH_TIMEOUT: u64 = 30; @@ -136,8 +136,9 @@ pub struct ContentFetcherHandler { control: Option, status: FetchState, client: Option, - using_dapps_domains: bool, installer: H, + request_url: Option, + embeddable_at: Option, } impl Drop for ContentFetcherHandler { @@ -155,8 +156,9 @@ impl ContentFetcherHandler { pub fn new( url: String, control: Control, - using_dapps_domains: bool, - handler: H) -> (Self, Arc) { + handler: H, + embeddable_at: Option, + ) -> (Self, Arc) { let fetch_control = Arc::new(FetchControl::default()); let client = Client::default(); @@ -165,8 +167,9 @@ impl ContentFetcherHandler { control: Some(control), client: Some(client), status: FetchState::NotStarted(url), - using_dapps_domains: using_dapps_domains, installer: handler, + request_url: None, + embeddable_at: embeddable_at, }; (handler, fetch_control) @@ -189,6 +192,7 @@ impl ContentFetcherHandler { impl server::Handler for ContentFetcherHandler { fn on_request(&mut self, request: server::Request) -> Next { + self.request_url = extract_url(&request); let status = if let FetchState::NotStarted(ref url) = self.status { Some(match *request.method() { // Start fetching content @@ -204,6 +208,7 @@ impl server::Handler for ContentFetcherHandler< "Unable To Start Dapp Download", "Could not initialize download of the dapp. It might be a problem with the remote server.", Some(&format!("{}", e)), + self.embeddable_at, )), } }, @@ -213,6 +218,7 @@ impl server::Handler for ContentFetcherHandler< "Method Not Allowed", "Only GET requests are allowed.", None, + self.embeddable_at, )), }) } else { None }; @@ -234,7 +240,8 @@ impl server::Handler for ContentFetcherHandler< StatusCode::GatewayTimeout, "Download Timeout", &format!("Could not fetch content within {} seconds.", FETCH_TIMEOUT), - None + None, + self.embeddable_at, ); Self::close_client(&mut self.client); (Some(FetchState::Error(timeout)), Next::write()) @@ -255,12 +262,15 @@ impl server::Handler for ContentFetcherHandler< StatusCode::BadGateway, "Invalid Dapp", "Downloaded bundle does not contain a valid content.", - Some(&format!("{:?}", e)) + Some(&format!("{:?}", e)), + self.embeddable_at, )) }, Ok((id, result)) => { - let address = redirection_address(self.using_dapps_domains, &id); - FetchState::Done(id, result, Redirection::new(&address)) + let url: String = self.request_url.take() + .map(|url| url.raw.into_string()) + .expect("Request URL always read in on_request; qed"); + FetchState::Done(id, result, Redirection::new(&url)) }, }; // Remove temporary zip file @@ -274,6 +284,7 @@ impl server::Handler for ContentFetcherHandler< "Download Error", "There was an error when fetching the content.", Some(&format!("{:?}", e)), + self.embeddable_at, ); (Some(FetchState::Error(error)), Next::write()) }, diff --git a/dapps/src/lib.rs b/dapps/src/lib.rs index 0041dbedf..4394d1183 100644 --- a/dapps/src/lib.rs +++ b/dapps/src/lib.rs @@ -44,6 +44,7 @@ #![cfg_attr(feature="nightly", plugin(clippy))] extern crate hyper; +extern crate time; extern crate url as url_lib; extern crate unicase; extern crate serde; diff --git a/dapps/src/page/builtin.rs b/dapps/src/page/builtin.rs index c4f56556e..bf5bf088f 100644 --- a/dapps/src/page/builtin.rs +++ b/dapps/src/page/builtin.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use page::handler; +use page::{handler, PageCache}; use std::sync::Arc; use endpoint::{Endpoint, EndpointInfo, EndpointPath, Handler}; use parity_dapps::{WebApp, File, Info}; @@ -80,6 +80,7 @@ impl Endpoint for PageEndpoint { prefix: self.prefix.clone(), path: path, file: handler::ServedFile::new(self.safe_to_embed_at_port.clone()), + cache: PageCache::Disabled, safe_to_embed_at_port: self.safe_to_embed_at_port.clone(), }) } diff --git a/dapps/src/page/handler.rs b/dapps/src/page/handler.rs index 0962f22c7..f908a69c5 100644 --- a/dapps/src/page/handler.rs +++ b/dapps/src/page/handler.rs @@ -15,6 +15,8 @@ // along with Parity. If not, see . use std::io::Write; +use time::{self, Duration}; + use hyper::header; use hyper::server; use hyper::uri::RequestUri; @@ -59,7 +61,7 @@ pub enum ServedFile { impl ServedFile { pub fn new(embeddable_at: Option) -> Self { - ServedFile::Error(ContentHandler::error_embeddable( + ServedFile::Error(ContentHandler::error( StatusCode::NotFound, "404 Not Found", "Requested dapp resource was not found.", @@ -69,6 +71,19 @@ impl ServedFile { } } +/// Defines what cache headers should be appended to returned resources. +#[derive(Debug, Copy, Clone, PartialEq)] +pub enum PageCache { + Enabled, + Disabled, +} + +impl Default for PageCache { + fn default() -> Self { + PageCache::Disabled + } +} + /// A handler for a single webapp. /// Resolves correct paths and serves as a plumbing code between /// hyper server and dapp. @@ -83,6 +98,8 @@ pub struct PageHandler { pub path: EndpointPath, /// Flag indicating if the file can be safely embeded (put in iframe). pub safe_to_embed_at_port: Option, + /// Cache settings for this page. + pub cache: PageCache, } impl PageHandler { @@ -129,9 +146,19 @@ impl server::Handler for PageHandler { ServedFile::File(ref f) => { res.set_status(StatusCode::Ok); + if let PageCache::Enabled = self.cache { + let mut headers = res.headers_mut(); + let validity = Duration::days(365); + headers.set(header::CacheControl(vec![ + header::CacheDirective::Public, + header::CacheDirective::MaxAge(validity.num_seconds() as u32), + ])); + headers.set(header::Expires(header::HttpDate(time::now() + validity))); + } + match f.content_type().parse() { Ok(mime) => res.headers_mut().set(header::ContentType(mime)), - Err(()) => debug!(target: "page_handler", "invalid MIME type: {}", f.content_type()), + Err(()) => debug!(target: "dapps", "invalid MIME type: {}", f.content_type()), } // Security headers: @@ -218,6 +245,7 @@ fn should_extract_path_with_appid() { using_dapps_domains: true, }, file: ServedFile::new(None), + cache: Default::default(), safe_to_embed_at_port: None, }; diff --git a/dapps/src/page/local.rs b/dapps/src/page/local.rs index 5390f5aac..aa98a68cd 100644 --- a/dapps/src/page/local.rs +++ b/dapps/src/page/local.rs @@ -18,7 +18,7 @@ use mime_guess; use std::io::{Seek, Read, SeekFrom}; use std::fs; use std::path::{Path, PathBuf}; -use page::handler; +use page::handler::{self, PageCache}; use endpoint::{Endpoint, EndpointInfo, EndpointPath, Handler}; #[derive(Debug, Clone)] @@ -26,24 +26,27 @@ pub struct LocalPageEndpoint { path: PathBuf, mime: Option, info: Option, + cache: PageCache, embeddable_at: Option, } impl LocalPageEndpoint { - pub fn new(path: PathBuf, info: EndpointInfo, embeddable_at: Option) -> Self { + pub fn new(path: PathBuf, info: EndpointInfo, cache: PageCache, embeddable_at: Option) -> Self { LocalPageEndpoint { path: path, mime: None, info: Some(info), + cache: cache, embeddable_at: embeddable_at, } } - pub fn single_file(path: PathBuf, mime: String) -> Self { + pub fn single_file(path: PathBuf, mime: String, cache: PageCache) -> Self { LocalPageEndpoint { path: path, mime: Some(mime), info: None, + cache: cache, embeddable_at: None, } } @@ -66,6 +69,7 @@ impl Endpoint for LocalPageEndpoint { path: path, file: handler::ServedFile::new(None), safe_to_embed_at_port: self.embeddable_at, + cache: self.cache, }) } else { Box::new(handler::PageHandler { @@ -74,6 +78,7 @@ impl Endpoint for LocalPageEndpoint { path: path, file: handler::ServedFile::new(None), safe_to_embed_at_port: self.embeddable_at, + cache: self.cache, }) } } diff --git a/dapps/src/page/mod.rs b/dapps/src/page/mod.rs index 349c979c7..92c066df3 100644 --- a/dapps/src/page/mod.rs +++ b/dapps/src/page/mod.rs @@ -21,4 +21,5 @@ mod handler; pub use self::local::LocalPageEndpoint; pub use self::builtin::PageEndpoint; +pub use self::handler::PageCache; diff --git a/dapps/src/router/auth.rs b/dapps/src/router/auth.rs index ff05420bc..a220e2ab0 100644 --- a/dapps/src/router/auth.rs +++ b/dapps/src/router/auth.rs @@ -59,7 +59,8 @@ impl Authorization for HttpBasicAuth { status::StatusCode::Unauthorized, "Unauthorized", "You need to provide valid credentials to access this page.", - None + None, + None, ))) }, Access::AuthRequired => { diff --git a/dapps/src/router/host_validation.rs b/dapps/src/router/host_validation.rs index 2b7e6c9e4..802466efd 100644 --- a/dapps/src/router/host_validation.rs +++ b/dapps/src/router/host_validation.rs @@ -41,6 +41,7 @@ pub fn host_invalid_response() -> Box + Send> { Box::new(ContentHandler::error(StatusCode::Forbidden, "Current Host Is Disallowed", "You are trying to access your node using incorrect address.", - Some("Use allowed URL or specify different hosts CLI options.") + Some("Use allowed URL or specify different hosts CLI options."), + None, )) } diff --git a/dapps/src/router/mod.rs b/dapps/src/router/mod.rs index 6ca453d6d..fe8061ef0 100644 --- a/dapps/src/router/mod.rs +++ b/dapps/src/router/mod.rs @@ -117,6 +117,7 @@ impl server::Handler for Router { "404 Not Found", "Requested content was not found.", None, + self.signer_port, )) }, // Redirect any other GET request to signer. @@ -131,6 +132,7 @@ impl server::Handler for Router { "404 Not Found", "Your homepage is not available when Trusted Signer is disabled.", Some("You can still access dapps by writing a correct address, though. Re-enabled Signer to get your homepage back."), + self.signer_port, )) } }, diff --git a/dapps/src/tests/fetch.rs b/dapps/src/tests/fetch.rs index 1cabca5cb..d50b2bdde 100644 --- a/dapps/src/tests/fetch.rs +++ b/dapps/src/tests/fetch.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use tests::helpers::{serve_with_registrar, serve_with_registrar_and_sync, request, assert_security_headers}; +use tests::helpers::{serve_with_registrar, serve_with_registrar_and_sync, request, assert_security_headers_for_embed}; #[test] fn should_resolve_dapp() { @@ -34,7 +34,7 @@ fn should_resolve_dapp() { // then assert_eq!(response.status, "HTTP/1.1 404 Not Found".to_owned()); assert_eq!(registrar.calls.lock().len(), 2); - assert_security_headers(&response.headers); + assert_security_headers_for_embed(&response.headers); } #[test] @@ -63,5 +63,5 @@ fn should_return_503_when_syncing_but_should_make_the_calls() { // then assert_eq!(response.status, "HTTP/1.1 503 Service Unavailable".to_owned()); assert_eq!(registrar.calls.lock().len(), 4); - assert_security_headers(&response.headers); + assert_security_headers_for_embed(&response.headers); } diff --git a/dapps/src/tests/redirection.rs b/dapps/src/tests/redirection.rs index 398d08774..b0a5ca9a2 100644 --- a/dapps/src/tests/redirection.rs +++ b/dapps/src/tests/redirection.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use tests::helpers::{serve, request, assert_security_headers}; +use tests::helpers::{serve, request, assert_security_headers, assert_security_headers_for_embed}; #[test] fn should_redirect_to_home() { @@ -93,7 +93,7 @@ fn should_display_404_on_invalid_dapp() { // then assert_eq!(response.status, "HTTP/1.1 404 Not Found".to_owned()); - assert_security_headers(&response.headers); + assert_security_headers_for_embed(&response.headers); } #[test] @@ -113,7 +113,7 @@ fn should_display_404_on_invalid_dapp_with_domain() { // then assert_eq!(response.status, "HTTP/1.1 404 Not Found".to_owned()); - assert_security_headers(&response.headers); + assert_security_headers_for_embed(&response.headers); } #[test] diff --git a/ethcore/Cargo.toml b/ethcore/Cargo.toml index 1f8413339..667b40ace 100644 --- a/ethcore/Cargo.toml +++ b/ethcore/Cargo.toml @@ -3,7 +3,7 @@ description = "Ethcore library" homepage = "http://ethcore.io" license = "GPL-3.0" name = "ethcore" -version = "1.4.0" +version = "1.5.0" authors = ["Ethcore "] build = "build.rs" diff --git a/ethcore/res/ethereum/classic.json b/ethcore/res/ethereum/classic.json index 5be7b1caf..7c1e9454e 100644 --- a/ethcore/res/ethereum/classic.json +++ b/ethcore/res/ethereum/classic.json @@ -11,7 +11,13 @@ "blockReward": "0x4563918244F40000", "registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b", "homesteadTransition": "0x118c30", - "eip150Transition": "0x2625a0" + "eip150Transition": "0x2625a0", + "eip155Transition": "0x7fffffffffffffff", + "eip160Transition": "0x7fffffffffffffff", + "eip161abcTransition": "0x7fffffffffffffff", + "eip161dTransition": "0x7fffffffffffffff", + "ecip1010PauseTransition": "0x2dc6c0", + "ecip1010ContinueTransition": "0x4c4b40" } } }, diff --git a/ethcore/res/ethereum/eip150_test.json b/ethcore/res/ethereum/eip150_test.json index 39d4b3fe8..34ef478dc 100644 --- a/ethcore/res/ethereum/eip150_test.json +++ b/ethcore/res/ethereum/eip150_test.json @@ -10,7 +10,11 @@ "blockReward": "0x4563918244F40000", "registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b", "homesteadTransition": "0x0", - "eip150Transition": "0x0" + "eip150Transition": "0x0", + "eip155Transition": "0x7fffffffffffffff", + "eip160Transition": "0x7fffffffffffffff", + "eip161abcTransition": "0x7fffffffffffffff", + "eip161dTransition": "0x7fffffffffffffff" } } }, diff --git a/ethcore/res/ethereum/eip161_test.json b/ethcore/res/ethereum/eip161_test.json new file mode 100644 index 000000000..884053d2a --- /dev/null +++ b/ethcore/res/ethereum/eip161_test.json @@ -0,0 +1,47 @@ +{ + "name": "Homestead (Test)", + "engine": { + "Ethash": { + "params": { + "gasLimitBoundDivisor": "0x0400", + "minimumDifficulty": "0x020000", + "difficultyBoundDivisor": "0x0800", + "durationLimit": "0x0d", + "blockReward": "0x4563918244F40000", + "registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b", + "homesteadTransition": "0x0", + "eip150Transition": "0x0", + "eip155Transition": "0x7fffffffffffffff", + "eip160Transition": "0x0", + "eip161abcTransition": "0x0", + "eip161dTransition": "0x0" + } + } + }, + "params": { + "accountStartNonce": "0x00", + "maximumExtraDataSize": "0x20", + "minGasLimit": "0x1388", + "networkID" : "0x1" + }, + "genesis": { + "seal": { + "ethereum": { + "nonce": "0x0000000000000042", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + } + }, + "difficulty": "0x400000000", + "author": "0x0000000000000000000000000000000000000000", + "timestamp": "0x00", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa", + "gasLimit": "0x1388" + }, + "accounts": { + "0000000000000000000000000000000000000001": { "balance": "1", "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } }, + "0000000000000000000000000000000000000002": { "balance": "1", "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } }, + "0000000000000000000000000000000000000003": { "balance": "1", "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } }, + "0000000000000000000000000000000000000004": { "balance": "1", "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } } + } +} diff --git a/ethcore/res/ethereum/expanse.json b/ethcore/res/ethereum/expanse.json index d2d036487..8d580b6f5 100644 --- a/ethcore/res/ethereum/expanse.json +++ b/ethcore/res/ethereum/expanse.json @@ -15,7 +15,11 @@ "difficultyHardforkTransition": "0x59d9", "difficultyHardforkBoundDivisor": "0x0200", "bombDefuseTransition": "0x30d40", - "eip150Transition": "0x7fffffffffffffff" + "eip150Transition": "0x7fffffffffffffff", + "eip155Transition": "0x7fffffffffffffff", + "eip160Transition": "0x7fffffffffffffff", + "eip161abcTransition": "0x7fffffffffffffff", + "eip161dTransition": "0x7fffffffffffffff" } } }, diff --git a/ethcore/res/ethereum/frontier.json b/ethcore/res/ethereum/frontier.json index 111dff30e..ecaefa4c3 100644 --- a/ethcore/res/ethereum/frontier.json +++ b/ethcore/res/ethereum/frontier.json @@ -130,7 +130,11 @@ "0xbb9bc244d798123fde783fcc1c72d3bb8c189413", "0x807640a13483f8ac783c557fcdf27be11ea4ac7a" ], - "eip150Transition": "0x259518" + "eip150Transition": "0x259518", + "eip155Transition": 2642462, + "eip160Transition": 2642462, + "eip161abcTransition": 2642462, + "eip161dTransition": 2642462 } } }, diff --git a/ethcore/res/ethereum/frontier_like_test.json b/ethcore/res/ethereum/frontier_like_test.json index 99a7ad712..8f41c61c8 100644 --- a/ethcore/res/ethereum/frontier_like_test.json +++ b/ethcore/res/ethereum/frontier_like_test.json @@ -130,7 +130,11 @@ "0xbb9bc244d798123fde783fcc1c72d3bb8c189413", "0x807640a13483f8ac783c557fcdf27be11ea4ac7a" ], - "eip150Transition": "0x7fffffffffffffff" + "eip150Transition": "0x7fffffffffffffff", + "eip155Transition": "0x7fffffffffffffff", + "eip160Transition": "0x7fffffffffffffff", + "eip161abcTransition": "0x7fffffffffffffff", + "eip161dTransition": "0x7fffffffffffffff" } } }, diff --git a/ethcore/res/ethereum/frontier_test.json b/ethcore/res/ethereum/frontier_test.json index 1cb3d8cfc..0fad8f37e 100644 --- a/ethcore/res/ethereum/frontier_test.json +++ b/ethcore/res/ethereum/frontier_test.json @@ -10,7 +10,11 @@ "blockReward": "0x4563918244F40000", "registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b", "homesteadTransition": "0x7fffffffffffffff", - "eip150Transition": "0x7fffffffffffffff" + "eip150Transition": "0x7fffffffffffffff", + "eip155Transition": "0x7fffffffffffffff", + "eip160Transition": "0x7fffffffffffffff", + "eip161abcTransition": "0x7fffffffffffffff", + "eip161dTransition": "0x7fffffffffffffff" } } }, diff --git a/ethcore/res/ethereum/homestead_test.json b/ethcore/res/ethereum/homestead_test.json index ad64ce2d5..a757a7bc6 100644 --- a/ethcore/res/ethereum/homestead_test.json +++ b/ethcore/res/ethereum/homestead_test.json @@ -10,7 +10,11 @@ "blockReward": "0x4563918244F40000", "registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b", "homesteadTransition": "0x0", - "eip150Transition": "0x7fffffffffffffff" + "eip150Transition": "0x7fffffffffffffff", + "eip155Transition": "0x7fffffffffffffff", + "eip160Transition": "0x7fffffffffffffff", + "eip161abcTransition": "0x7fffffffffffffff", + "eip161dTransition": "0x7fffffffffffffff" } } }, diff --git a/ethcore/res/ethereum/morden.json b/ethcore/res/ethereum/morden.json index 67d9ce044..9d54169c3 100644 --- a/ethcore/res/ethereum/morden.json +++ b/ethcore/res/ethereum/morden.json @@ -10,7 +10,11 @@ "blockReward": "0x4563918244F40000", "registrar": "0x52dff57a8a1532e6afb3dc07e2af58bb9eb05b3d", "homesteadTransition": "0x789b0", - "eip150Transition": "0x1b34d8" + "eip150Transition": "0x1b34d8", + "eip155Transition": "0x7fffffffffffffff", + "eip160Transition": "0x7fffffffffffffff", + "eip161abcTransition": "0x7fffffffffffffff", + "eip161dTransition": "0x7fffffffffffffff" } } }, diff --git a/ethcore/res/ethereum/olympic.json b/ethcore/res/ethereum/olympic.json index ebc7abd4e..655410ee1 100644 --- a/ethcore/res/ethereum/olympic.json +++ b/ethcore/res/ethereum/olympic.json @@ -10,7 +10,11 @@ "blockReward": "0x14D1120D7B160000", "registrar": "5e70c0bbcd5636e0f9f9316e9f8633feb64d4050", "homesteadTransition": "0x7fffffffffffffff", - "eip150Transition": "0x7fffffffffffffff" + "eip150Transition": "0x7fffffffffffffff", + "eip155Transition": "0x7fffffffffffffff", + "eip160Transition": "0x7fffffffffffffff", + "eip161abcTransition": "0x7fffffffffffffff", + "eip161dTransition": "0x7fffffffffffffff" } } }, diff --git a/ethcore/res/ethereum/tests b/ethcore/res/ethereum/tests index 97066e40c..853333e7d 160000 --- a/ethcore/res/ethereum/tests +++ b/ethcore/res/ethereum/tests @@ -1 +1 @@ -Subproject commit 97066e40ccd061f727deb5cd860e4d9135aa2551 +Subproject commit 853333e7da312775fb8f32f2c2771b8578cd0d79 diff --git a/ethcore/res/ethereum/transition_test.json b/ethcore/res/ethereum/transition_test.json index c004bc2ba..aebea2b4f 100644 --- a/ethcore/res/ethereum/transition_test.json +++ b/ethcore/res/ethereum/transition_test.json @@ -130,7 +130,11 @@ "0xbb9bc244d798123fde783fcc1c72d3bb8c189413", "0x807640a13483f8ac783c557fcdf27be11ea4ac7a" ], - "eip150Transition": "0xa" + "eip150Transition": "0xa", + "eip155Transition": "0x7fffffffffffffff", + "eip160Transition": "0x7fffffffffffffff", + "eip161abcTransition": "0x7fffffffffffffff", + "eip161dTransition": "0x7fffffffffffffff" } } }, diff --git a/ethcore/src/blockchain/blockchain.rs b/ethcore/src/blockchain/blockchain.rs index d95c199ed..5910d0309 100644 --- a/ethcore/src/blockchain/blockchain.rs +++ b/ethcore/src/blockchain/blockchain.rs @@ -1468,7 +1468,7 @@ mod tests { action: Action::Create, value: 100.into(), data: "601080600c6000396000f3006000355415600957005b60203560003555".from_hex().unwrap(), - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); let b1a = canon_chain @@ -1532,7 +1532,7 @@ mod tests { action: Action::Create, value: 100.into(), data: "601080600c6000396000f3006000355415600957005b60203560003555".from_hex().unwrap(), - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); let t2 = Transaction { nonce: 1.into(), @@ -1541,7 +1541,7 @@ mod tests { action: Action::Create, value: 100.into(), data: "601080600c6000396000f3006000355415600957005b60203560003555".from_hex().unwrap(), - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); let t3 = Transaction { nonce: 2.into(), @@ -1550,7 +1550,7 @@ mod tests { action: Action::Create, value: 100.into(), data: "601080600c6000396000f3006000355415600957005b60203560003555".from_hex().unwrap(), - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); let b1a = canon_chain .with_transaction(t1.clone()) @@ -1856,7 +1856,7 @@ mod tests { action: Action::Create, value: 101.into(), data: "601080600c6000396000f3006000355415600957005b60203560003555".from_hex().unwrap(), - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); let t2 = Transaction { nonce: 0.into(), gas_price: 0.into(), @@ -1864,7 +1864,7 @@ mod tests { action: Action::Create, value: 102.into(), data: "601080600c6000396000f3006000355415600957005b60203560003555".from_hex().unwrap(), - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); let t3 = Transaction { nonce: 0.into(), gas_price: 0.into(), @@ -1872,7 +1872,7 @@ mod tests { action: Action::Create, value: 103.into(), data: "601080600c6000396000f3006000355415600957005b60203560003555".from_hex().unwrap(), - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); let tx_hash1 = t1.hash(); let tx_hash2 = t2.hash(); let tx_hash3 = t3.hash(); diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index bf612852e..b1a70454d 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -33,7 +33,7 @@ use io::*; use views::{HeaderView, BodyView, BlockView}; use error::{ImportError, ExecutionError, CallError, BlockError, ImportResult, Error as EthcoreError}; use header::BlockNumber; -use state::State; +use state::{State, CleanupMode}; use spec::Spec; use basic_types::Seal; use engines::Engine; @@ -65,7 +65,7 @@ use evm::{Factory as EvmFactory, Schedule}; use miner::{Miner, MinerService}; use snapshot::{self, io as snapshot_io}; use factory::Factories; -use rlp::{View, UntrustedRlp}; +use rlp::{decode, View, UntrustedRlp}; use state_db::StateDB; use rand::OsRng; @@ -147,6 +147,7 @@ pub struct Client { factories: Factories, history: u64, rng: Mutex, + on_mode_change: Mutex>>, } impl Client { @@ -211,7 +212,7 @@ impl Client { let panic_handler = PanicHandler::new_in_arc(); panic_handler.forward_from(&block_queue); - let awake = match config.mode { Mode::Dark(..) => false, _ => true }; + let awake = match config.mode { Mode::Dark(..) | Mode::Off => false, _ => true }; let factories = Factories { vm: EvmFactory::new(config.vm_type.clone(), config.jump_table_size), @@ -243,6 +244,7 @@ impl Client { factories: factories, history: history, rng: Mutex::new(try!(OsRng::new().map_err(::util::UtilError::StdIo))), + on_mode_change: Mutex::new(None), }; Ok(Arc::new(client)) } @@ -260,6 +262,11 @@ impl Client { } } + /// Register an action to be done if a mode change happens. + pub fn on_mode_change(&self, f: F) where F: 'static + FnMut(&Mode) + Send { + *self.on_mode_change.lock() = Some(Box::new(f)); + } + /// Flush the block import queue. pub fn flush_queue(&self) { self.block_queue.flush(); @@ -268,6 +275,22 @@ impl Client { } } + /// The env info as of the best block. + fn latest_env_info(&self) -> EnvInfo { + let header_data = self.best_block_header(); + let view = HeaderView::new(&header_data); + + EnvInfo { + number: view.number(), + author: view.author(), + timestamp: view.timestamp(), + difficulty: view.difficulty(), + last_hashes: self.build_last_hashes(view.hash()), + gas_used: U256::default(), + gas_limit: view.gas_limit(), + } + } + fn build_last_hashes(&self, parent_hash: H256) -> Arc { { let hashes = self.last_hashes.read(); @@ -790,7 +813,7 @@ impl BlockChainClient for Client { let needed_balance = t.value + t.gas * t.gas_price; if balance < needed_balance { // give the sender a sufficient balance - state.add_balance(&sender, &(needed_balance - balance)); + state.add_balance(&sender, &(needed_balance - balance), CleanupMode::NoEmpty); } let options = TransactOptions { tracing: analytics.transaction_tracing, vm_tracing: analytics.vm_tracing, check_nonce: false }; let mut ret = try!(Executive::new(&mut state, &env_info, &*self.engine, &self.factories.vm).transact(t, options)); @@ -840,18 +863,37 @@ impl BlockChainClient for Client { } fn keep_alive(&self) { - let mode = self.mode.lock().clone(); - if mode != Mode::Active { + let should_wake = match &*self.mode.lock() { + &Mode::Dark(..) | &Mode::Passive(..) => true, + _ => false, + }; + if should_wake { self.wake_up(); (*self.sleep_state.lock()).last_activity = Some(Instant::now()); } } - fn mode(&self) -> IpcMode { self.mode.lock().clone().into() } + fn mode(&self) -> IpcMode { + let r = self.mode.lock().clone().into(); + trace!(target: "mode", "Asked for mode = {:?}. returning {:?}", &*self.mode.lock(), r); + r + } - fn set_mode(&self, mode: IpcMode) { - *self.mode.lock() = mode.clone().into(); - match mode { + fn set_mode(&self, new_mode: IpcMode) { + trace!(target: "mode", "Client::set_mode({:?})", new_mode); + { + let mut mode = self.mode.lock(); + *mode = new_mode.clone().into(); + trace!(target: "mode", "Mode now {:?}", &*mode); + match *self.on_mode_change.lock() { + Some(ref mut f) => { + trace!(target: "mode", "Making callback..."); + f(&*mode) + }, + _ => {} + } + } + match new_mode { IpcMode::Active => self.wake_up(), IpcMode::Off => self.sleep(), _ => {(*self.sleep_state.lock()).last_activity = Some(Instant::now()); } @@ -1008,7 +1050,9 @@ impl BlockChainClient for Client { transaction_hash: transaction_hash.clone(), transaction_index: transaction_index, log_index: i - }).collect() + }).collect(), + log_bloom: receipt.log_bloom, + state_root: receipt.state_root, }) }, _ => None @@ -1167,24 +1211,28 @@ impl BlockChainClient for Client { fn pending_transactions(&self) -> Vec { self.miner.pending_transactions(self.chain.read().best_block_number()) } + + fn signing_network_id(&self) -> Option { + self.engine.signing_network_id(&self.latest_env_info()) + } + + fn block_extra_info(&self, id: BlockID) -> Option> { + self.block_header(id) + .map(|block| decode(&block)) + .map(|header| self.engine.extra_info(&header)) + } + + fn uncle_extra_info(&self, id: UncleID) -> Option> { + self.uncle(id) + .map(|block| BlockView::new(&block).header()) + .map(|header| self.engine.extra_info(&header)) + } } impl MiningBlockChainClient for Client { fn latest_schedule(&self) -> Schedule { - let header_data = self.best_block_header(); - let view = HeaderView::new(&header_data); - - let env_info = EnvInfo { - number: view.number(), - author: view.author(), - timestamp: view.timestamp(), - difficulty: view.difficulty(), - last_hashes: self.build_last_hashes(view.hash()), - gas_used: U256::default(), - gas_limit: view.gas_limit(), - }; - self.engine.schedule(&env_info) + self.engine.schedule(&self.latest_env_info()) } fn prepare_open_block(&self, author: Address, gas_range_target: (U256, U256), extra_data: Bytes) -> OpenBlock { diff --git a/ethcore/src/client/config.rs b/ethcore/src/client/config.rs index c4aeba8a4..045b8ee05 100644 --- a/ethcore/src/client/config.rs +++ b/ethcore/src/client/config.rs @@ -16,6 +16,7 @@ use std::str::FromStr; use std::path::Path; +use std::fmt::{Display, Formatter, Error as FmtError}; pub use std::time::Duration; pub use blockchain::Config as BlockChainConfig; pub use trace::Config as TraceConfig; @@ -86,6 +87,17 @@ impl Default for Mode { } } +impl Display for Mode { + fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { + match *self { + Mode::Active => write!(f, "active"), + Mode::Passive(..) => write!(f, "passive"), + Mode::Dark(..) => write!(f, "dark"), + Mode::Off => write!(f, "offline"), + } + } +} + /// Client configuration. Includes configs for all sub-systems. #[derive(Debug, PartialEq, Default)] pub struct ClientConfig { diff --git a/ethcore/src/client/test_client.rs b/ethcore/src/client/test_client.rs index a12d94ae4..434edd3e8 100644 --- a/ethcore/src/client/test_client.rs +++ b/ethcore/src/client/test_client.rs @@ -38,6 +38,7 @@ use evm::{Factory as EvmFactory, VMType, Schedule}; use miner::{Miner, MinerService, TransactionImportResult}; use spec::Spec; use types::mode::Mode; +use views::BlockView; use verification::queue::QueueInfo; use block::{OpenBlock, SealedBlock}; @@ -227,7 +228,7 @@ impl TestBlockChainClient { gas_price: U256::one(), nonce: U256::zero() }; - let signed_tx = tx.sign(keypair.secret()); + let signed_tx = tx.sign(keypair.secret(), None); txs.append(&signed_tx); txs.out() }, @@ -293,7 +294,7 @@ impl TestBlockChainClient { gas_price: U256::one(), nonce: U256::zero() }; - let signed_tx = tx.sign(keypair.secret()); + let signed_tx = tx.sign(keypair.secret(), None); self.set_balance(signed_tx.sender().unwrap(), 10_000_000.into()); let res = self.miner.import_external_transactions(self, vec![signed_tx]); let res = res.into_iter().next().unwrap().expect("Successful import"); @@ -314,7 +315,7 @@ pub fn get_temp_state_db() -> GuardedTempResult { impl MiningBlockChainClient for TestBlockChainClient { fn latest_schedule(&self) -> Schedule { - Schedule::new_homestead_gas_fix() + Schedule::new_post_eip150(true, true, true) } fn prepare_open_block(&self, author: Address, gas_range_target: (U256, U256), extra_data: Bytes) -> OpenBlock { @@ -417,6 +418,10 @@ impl BlockChainClient for TestBlockChainClient { None // Simple default. } + fn uncle_extra_info(&self, _id: UncleID) -> Option> { + None + } + fn transaction_receipt(&self, id: TransactionID) -> Option { self.receipts.read().get(&id).cloned() } @@ -459,6 +464,13 @@ impl BlockChainClient for TestBlockChainClient { self.block_hash(id).and_then(|hash| self.blocks.read().get(&hash).cloned()) } + fn block_extra_info(&self, id: BlockID) -> Option> { + self.block(id) + .map(|block| BlockView::new(&block).header()) + .map(|header| self.spec.engine.extra_info(&header)) + } + + fn block_status(&self, id: BlockID) -> BlockStatus { match id { BlockID::Number(number) if (number as usize) < self.blocks.read().len() => BlockStatus::InChain, @@ -633,6 +645,8 @@ impl BlockChainClient for TestBlockChainClient { self.miner.pending_transactions(self.chain_info().best_block_number) } + fn signing_network_id(&self) -> Option { None } + fn mode(&self) -> Mode { Mode::Active } fn set_mode(&self, _: Mode) { unimplemented!(); } diff --git a/ethcore/src/client/traits.rs b/ethcore/src/client/traits.rs index d7844ba3d..67092e986 100644 --- a/ethcore/src/client/traits.rs +++ b/ethcore/src/client/traits.rs @@ -29,13 +29,13 @@ use error::{ImportResult, CallError}; use receipt::LocalizedReceipt; use trace::LocalizedTrace; use evm::{Factory as EvmFactory, Schedule}; -use types::ids::*; -use types::trace_filter::Filter as TraceFilter; use executive::Executed; use env_info::LastHashes; -use types::call_analytics::CallAnalytics; use block_import_error::BlockImportError; use ipc::IpcConfig; +use types::ids::*; +use types::trace_filter::Filter as TraceFilter; +use types::call_analytics::CallAnalytics; use types::blockchain_info::BlockChainInfo; use types::block_status::BlockStatus; use types::mode::Mode; @@ -215,7 +215,7 @@ pub trait BlockChainClient : Sync + Send { /// Calculate median gas price from recent blocks if they have any transactions. fn gas_price_median(&self, sample_size: usize) -> Option { let corpus = self.gas_price_corpus(sample_size); - corpus.get(corpus.len()/2).cloned() + corpus.get(corpus.len() / 2).cloned() } /// Get the gas price distribution based on recent blocks if they have any transactions. @@ -223,13 +223,24 @@ pub trait BlockChainClient : Sync + Send { let raw_corpus = self.gas_price_corpus(sample_size); let raw_len = raw_corpus.len(); // Throw out outliers. - let (corpus, _) = raw_corpus.split_at(raw_len-raw_len/40); + let (corpus, _) = raw_corpus.split_at(raw_len - raw_len / 40); Histogram::new(corpus, bucket_number) } + /// Get the preferred network ID to sign on + fn signing_network_id(&self) -> Option; + + /// Get the mode. fn mode(&self) -> Mode; + /// Set the mode. fn set_mode(&self, mode: Mode); + + /// Returns engine-related extra info for `BlockID`. + fn block_extra_info(&self, id: BlockID) -> Option>; + + /// Returns engine-related extra info for `UncleID`. + fn uncle_extra_info(&self, id: UncleID) -> Option>; } /// Extended client interface used for mining diff --git a/ethcore/src/engines/basic_authority.rs b/ethcore/src/engines/basic_authority.rs index 815d2b43a..5a55c6210 100644 --- a/ethcore/src/engines/basic_authority.rs +++ b/ethcore/src/engines/basic_authority.rs @@ -81,7 +81,7 @@ impl Engine for BasicAuthority { fn builtins(&self) -> &BTreeMap { &self.builtins } /// Additional engine-specific information for the user/developer concerning `header`. - fn extra_info(&self, _header: &Header) -> HashMap { hash_map!["signature".to_owned() => "TODO".to_owned()] } + fn extra_info(&self, _header: &Header) -> BTreeMap { map!["signature".to_owned() => "TODO".to_owned()] } fn schedule(&self, _env_info: &EnvInfo) -> Schedule { Schedule::new_homestead() diff --git a/ethcore/src/engines/mod.rs b/ethcore/src/engines/mod.rs index 250529dad..52812f45e 100644 --- a/ethcore/src/engines/mod.rs +++ b/ethcore/src/engines/mod.rs @@ -47,7 +47,7 @@ pub trait Engine : Sync + Send { fn seal_fields(&self) -> usize { 0 } /// Additional engine-specific information for the user/developer concerning `header`. - fn extra_info(&self, _header: &Header) -> HashMap { HashMap::new() } + fn extra_info(&self, _header: &Header) -> BTreeMap { BTreeMap::new() } /// Additional information. fn additional_params(&self) -> HashMap { HashMap::new() } @@ -108,6 +108,9 @@ pub trait Engine : Sync + Send { /// Verify a particular transaction is valid. fn verify_transaction(&self, _t: &SignedTransaction, _header: &Header) -> Result<(), Error> { Ok(()) } + /// The network ID that transactions should be signed with. + fn signing_network_id(&self, _env_info: &EnvInfo) -> Option { None } + /// Verify the seal of a block. This is an auxilliary method that actually just calls other `verify_` methods /// to get the job done. By default it must pass `verify_basic` and `verify_block_unordered`. If more or fewer /// methods are needed for an Engine, this may be overridden. diff --git a/ethcore/src/error.rs b/ethcore/src/error.rs index 04a0920fa..ae68aefa1 100644 --- a/ethcore/src/error.rs +++ b/ethcore/src/error.rs @@ -76,6 +76,8 @@ pub enum TransactionError { RecipientBanned, /// Contract creation code is banned. CodeBanned, + /// Invalid network ID given. + InvalidNetworkId, } impl fmt::Display for TransactionError { @@ -99,6 +101,7 @@ impl fmt::Display for TransactionError { SenderBanned => "Sender is temporarily banned.".into(), RecipientBanned => "Recipient is temporarily banned.".into(), CodeBanned => "Contract code is temporarily banned.".into(), + InvalidNetworkId => "Transaction of this network ID is not allowed on this chain.".into(), }; f.write_fmt(format_args!("Transaction error ({})", msg)) diff --git a/ethcore/src/ethereum/ethash.rs b/ethcore/src/ethereum/ethash.rs index 060a20aa2..6436e3531 100644 --- a/ethcore/src/ethereum/ethash.rs +++ b/ethcore/src/ethereum/ethash.rs @@ -14,13 +14,14 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use ethash::{quick_get_difficulty, slow_get_seedhash, EthashManager, H256 as EH256}; +use ethash::{quick_get_difficulty, slow_get_seedhash, EthashManager}; use util::*; use block::*; use builtin::Builtin; use env_info::EnvInfo; -use error::{BlockError, Error}; +use error::{BlockError, TransactionError, Error}; use header::Header; +use state::CleanupMode; use spec::CommonParams; use transaction::SignedTransaction; use engines::Engine; @@ -59,8 +60,20 @@ pub struct EthashParams { pub difficulty_hardfork_bound_divisor: U256, /// Block on which there is no additional difficulty from the exponential bomb. pub bomb_defuse_transition: u64, - /// Bad gas transition block number. + /// Number of first block where EIP-150 rules begin. pub eip150_transition: u64, + /// Number of first block where EIP-155 rules begin. + pub eip155_transition: u64, + /// Number of first block where EIP-160 rules begin. + pub eip160_transition: u64, + /// Number of first block where EIP-161.abc begin. + pub eip161abc_transition: u64, + /// Number of first block where EIP-161.d begins. + pub eip161d_transition: u64, + /// Number of first block where ECIP-1010 begins. + pub ecip1010_pause_transition: u64, + /// Number of first block where ECIP-1010 ends. + pub ecip1010_continue_transition: u64 } impl From for EthashParams { @@ -81,6 +94,12 @@ impl From for EthashParams { difficulty_hardfork_bound_divisor: p.difficulty_hardfork_bound_divisor.map_or(p.difficulty_bound_divisor.into(), Into::into), bomb_defuse_transition: p.bomb_defuse_transition.map_or(0x7fffffffffffffff, Into::into), eip150_transition: p.eip150_transition.map_or(0, Into::into), + eip155_transition: p.eip155_transition.map_or(0, Into::into), + eip160_transition: p.eip160_transition.map_or(0, Into::into), + eip161abc_transition: p.eip161abc_transition.map_or(0, Into::into), + eip161d_transition: p.eip161d_transition.map_or(0x7fffffffffffffff, Into::into), + ecip1010_pause_transition: p.ecip1010_pause_transition.map_or(0x7fffffffffffffff, Into::into), + ecip1010_continue_transition: p.ecip1010_continue_transition.map_or(0x7fffffffffffffff, Into::into), } } } @@ -120,8 +139,8 @@ impl Engine for Ethash { } /// Additional engine-specific information for the user/developer concerning `header`. - fn extra_info(&self, header: &Header) -> HashMap { - hash_map!["nonce".to_owned() => format!("0x{}", header.nonce().hex()), "mixHash".to_owned() => format!("0x{}", header.mix_hash().hex())] + fn extra_info(&self, header: &Header) -> BTreeMap { + map!["nonce".to_owned() => format!("0x{}", header.nonce().hex()), "mixHash".to_owned() => format!("0x{}", header.mix_hash().hex())] } fn schedule(&self, env_info: &EnvInfo) -> Schedule { @@ -132,7 +151,19 @@ impl Engine for Ethash { } else if env_info.number < self.ethash_params.eip150_transition { Schedule::new_homestead() } else { - Schedule::new_homestead_gas_fix() + Schedule::new_post_eip150( + env_info.number >= self.ethash_params.eip160_transition, + env_info.number >= self.ethash_params.eip161abc_transition, + env_info.number >= self.ethash_params.eip161d_transition + ) + } + } + + fn signing_network_id(&self, env_info: &EnvInfo) -> Option { + if env_info.number >= self.ethash_params.eip155_transition && self.params().network_id < 127 { + Some(self.params().network_id as u8) + } else { + None } } @@ -169,7 +200,7 @@ impl Engine for Ethash { let mut state = block.fields_mut().state; for child in &self.ethash_params.dao_hardfork_accounts { let b = state.balance(child); - state.transfer_balance(child, &self.ethash_params.dao_hardfork_beneficiary, &b); + state.transfer_balance(child, &self.ethash_params.dao_hardfork_beneficiary, &b, CleanupMode::NoEmpty); } // } } @@ -182,12 +213,12 @@ impl Engine for Ethash { let fields = block.fields_mut(); // Bestow block reward - fields.state.add_balance(fields.header.author(), &(reward + reward / U256::from(32) * U256::from(fields.uncles.len()))); + fields.state.add_balance(fields.header.author(), &(reward + reward / U256::from(32) * U256::from(fields.uncles.len())), CleanupMode::NoEmpty); // Bestow uncle rewards let current_number = fields.header.number(); for u in fields.uncles.iter() { - fields.state.add_balance(u.author(), &(reward * U256::from(8 + u.number() - current_number) / U256::from(8))); + fields.state.add_balance(u.author(), &(reward * U256::from(8 + u.number() - current_number) / U256::from(8)), CleanupMode::NoEmpty); } // Commit state so that we can actually figure out the state root. @@ -212,10 +243,10 @@ impl Engine for Ethash { return Err(From::from(BlockError::DifficultyOutOfBounds(OutOfBounds { min: Some(min_difficulty), max: None, found: header.difficulty().clone() }))) } - let difficulty = Ethash::boundary_to_difficulty(&Ethash::from_ethash(quick_get_difficulty( - &Ethash::to_ethash(header.bare_hash()), + let difficulty = Ethash::boundary_to_difficulty(&H256(quick_get_difficulty( + &header.bare_hash().0, header.nonce().low_u64(), - &Ethash::to_ethash(header.mix_hash()) + &header.mix_hash().0 ))); if &difficulty < header.difficulty() { return Err(From::from(BlockError::InvalidProofOfWork(OutOfBounds { min: Some(header.difficulty().clone()), max: None, found: difficulty }))); @@ -240,10 +271,10 @@ impl Engine for Ethash { Mismatch { expected: self.seal_fields(), found: header.seal().len() } ))); } - let result = self.pow.compute_light(header.number() as u64, &Ethash::to_ethash(header.bare_hash()), header.nonce().low_u64()); - let mix = Ethash::from_ethash(result.mix_hash); - let difficulty = Ethash::boundary_to_difficulty(&Ethash::from_ethash(result.value)); - trace!(target: "miner", "num: {}, seed: {}, h: {}, non: {}, mix: {}, res: {}" , header.number() as u64, Ethash::from_ethash(slow_get_seedhash(header.number() as u64)), header.bare_hash(), header.nonce().low_u64(), Ethash::from_ethash(result.mix_hash), Ethash::from_ethash(result.value)); + let result = self.pow.compute_light(header.number() as u64, &header.bare_hash().0, header.nonce().low_u64()); + let mix = H256(result.mix_hash); + let difficulty = Ethash::boundary_to_difficulty(&H256(result.value)); + trace!(target: "miner", "num: {}, seed: {}, h: {}, non: {}, mix: {}, res: {}" , header.number() as u64, H256(slow_get_seedhash(header.number() as u64)), header.bare_hash(), header.nonce().low_u64(), H256(result.mix_hash), H256(result.value)); if mix != header.mix_hash() { return Err(From::from(BlockError::MismatchedH256SealElement(Mismatch { expected: mix, found: header.mix_hash() }))); } @@ -277,6 +308,13 @@ impl Engine for Ethash { if header.number() >= self.ethash_params.homestead_transition { try!(t.check_low_s()); } + + if let Some(n) = t.network_id() { + if header.number() < self.ethash_params.eip155_transition || n as usize != self.params().network_id { + return Err(TransactionError::InvalidNetworkId.into()) + } + } + Ok(()) } @@ -285,7 +323,7 @@ impl Engine for Ethash { } } -#[cfg_attr(feature="dev", allow(wrong_self_convention))] // to_ethash should take self +#[cfg_attr(feature="dev", allow(wrong_self_convention))] impl Ethash { fn calculate_difficulty(&self, header: &Header, parent: &Header) -> U256 { const EXP_DIFF_PERIOD: u64 = 100000; @@ -321,9 +359,20 @@ impl Ethash { }; target = max(min_difficulty, target); if header.number() < self.ethash_params.bomb_defuse_transition { - let period = ((parent.number() + 1) / EXP_DIFF_PERIOD) as usize; - if period > 1 { - target = max(min_difficulty, target + (U256::from(1) << (period - 2))); + if header.number() < self.ethash_params.ecip1010_pause_transition { + let period = ((parent.number() + 1) / EXP_DIFF_PERIOD) as usize; + if period > 1 { + target = max(min_difficulty, target + (U256::from(1) << (period - 2))); + } + } + else if header.number() < self.ethash_params.ecip1010_continue_transition { + let fixed_difficulty = ((self.ethash_params.ecip1010_pause_transition / EXP_DIFF_PERIOD) - 2) as usize; + target = max(min_difficulty, target + (U256::from(1) << fixed_difficulty)); + } + else { + let period = ((parent.number() + 1) / EXP_DIFF_PERIOD) as usize; + let delay = ((self.ethash_params.ecip1010_continue_transition - self.ethash_params.ecip1010_pause_transition) / EXP_DIFF_PERIOD) as usize; + target = max(min_difficulty, target + (U256::from(1) << (period - delay - 2))); } } target @@ -347,14 +396,6 @@ impl Ethash { (((U256::one() << 255) / *difficulty) << 1).into() } } - - fn to_ethash(hash: H256) -> EH256 { - unsafe { mem::transmute(hash) } - } - - fn from_ethash(hash: EH256) -> H256 { - unsafe { mem::transmute(hash) } - } } impl Header { @@ -382,8 +423,8 @@ mod tests { use env_info::EnvInfo; use error::{BlockError, Error}; use header::Header; - use super::super::new_morden; - use super::Ethash; + use super::super::{new_morden, new_homestead_test}; + use super::{Ethash, EthashParams}; use rlp; #[test] @@ -605,5 +646,122 @@ mod tests { assert_eq!(Ethash::difficulty_to_boundary(&U256::from(32)), H256::from_str("0800000000000000000000000000000000000000000000000000000000000000").unwrap()); } - // TODO: difficulty test + #[test] + fn difficulty_frontier() { + let spec = new_homestead_test(); + let ethparams = get_default_ethash_params(); + let ethash = Ethash::new(spec.params, ethparams, BTreeMap::new()); + + let mut parent_header = Header::default(); + parent_header.set_number(1000000); + parent_header.set_difficulty(U256::from_str("b69de81a22b").unwrap()); + parent_header.set_timestamp(1455404053); + let mut header = Header::default(); + header.set_number(parent_header.number() + 1); + header.set_timestamp(1455404058); + + let difficulty = ethash.calculate_difficulty(&header, &parent_header); + assert_eq!(U256::from_str("b6b4bbd735f").unwrap(), difficulty); + } + + #[test] + fn difficulty_homestead() { + let spec = new_homestead_test(); + let ethparams = get_default_ethash_params(); + let ethash = Ethash::new(spec.params, ethparams, BTreeMap::new()); + + let mut parent_header = Header::default(); + parent_header.set_number(1500000); + parent_header.set_difficulty(U256::from_str("1fd0fd70792b").unwrap()); + parent_header.set_timestamp(1463003133); + let mut header = Header::default(); + header.set_number(parent_header.number() + 1); + header.set_timestamp(1463003177); + + let difficulty = ethash.calculate_difficulty(&header, &parent_header); + assert_eq!(U256::from_str("1fc50f118efe").unwrap(), difficulty); + } + + #[test] + fn difficulty_classic_bomb_delay() { + let spec = new_homestead_test(); + let ethparams = EthashParams { + ecip1010_pause_transition: 3000000, + ..get_default_ethash_params() + }; + let ethash = Ethash::new(spec.params, ethparams, BTreeMap::new()); + + let mut parent_header = Header::default(); + parent_header.set_number(3500000); + parent_header.set_difficulty(U256::from_str("6F62EAF8D3C").unwrap()); + parent_header.set_timestamp(1452838500); + let mut header = Header::default(); + header.set_number(parent_header.number() + 1); + + header.set_timestamp(parent_header.timestamp() + 20); + assert_eq!( + U256::from_str("6F55FE9B74B").unwrap(), + ethash.calculate_difficulty(&header, &parent_header) + ); + header.set_timestamp(parent_header.timestamp() + 5); + assert_eq!( + U256::from_str("6F71D75632D").unwrap(), + ethash.calculate_difficulty(&header, &parent_header) + ); + header.set_timestamp(parent_header.timestamp() + 80); + assert_eq!( + U256::from_str("6F02746B3A5").unwrap(), + ethash.calculate_difficulty(&header, &parent_header) + ); + } + + #[test] + fn test_difficulty_bomb_continue() { + let spec = new_homestead_test(); + let ethparams = EthashParams { + ecip1010_pause_transition: 3000000, + ecip1010_continue_transition: 5000000, + ..get_default_ethash_params() + }; + let ethash = Ethash::new(spec.params, ethparams, BTreeMap::new()); + + let mut parent_header = Header::default(); + parent_header.set_number(5000102); + parent_header.set_difficulty(U256::from_str("14944397EE8B").unwrap()); + parent_header.set_timestamp(1513175023); + let mut header = Header::default(); + header.set_number(parent_header.number() + 1); + header.set_timestamp(parent_header.timestamp() + 6); + assert_eq!( + U256::from_str("1496E6206188").unwrap(), + ethash.calculate_difficulty(&header, &parent_header) + ); + parent_header.set_number(5100123); + parent_header.set_difficulty(U256::from_str("14D24B39C7CF").unwrap()); + parent_header.set_timestamp(1514609324); + header.set_number(parent_header.number() + 1); + header.set_timestamp(parent_header.timestamp() + 41); + assert_eq!( + U256::from_str("14CA9C5D9227").unwrap(), + ethash.calculate_difficulty(&header, &parent_header) + ); + parent_header.set_number(6150001); + parent_header.set_difficulty(U256::from_str("305367B57227").unwrap()); + parent_header.set_timestamp(1529664575); + header.set_number(parent_header.number() + 1); + header.set_timestamp(parent_header.timestamp() + 105); + assert_eq!( + U256::from_str("309D09E0C609").unwrap(), + ethash.calculate_difficulty(&header, &parent_header) + ); + parent_header.set_number(8000000); + parent_header.set_difficulty(U256::from_str("1180B36D4CE5B6A").unwrap()); + parent_header.set_timestamp(1535431724); + header.set_number(parent_header.number() + 1); + header.set_timestamp(parent_header.timestamp() + 420); + assert_eq!( + U256::from_str("5126FFD5BCBB9E7").unwrap(), + ethash.calculate_difficulty(&header, &parent_header) + ); + } } diff --git a/ethcore/src/ethereum/mod.rs b/ethcore/src/ethereum/mod.rs index d8299324d..253a12372 100644 --- a/ethcore/src/ethereum/mod.rs +++ b/ethcore/src/ethereum/mod.rs @@ -54,6 +54,9 @@ pub fn new_homestead_test() -> Spec { load(include_bytes!("../../res/ethereum/ho /// Create a new Homestead-EIP150 chain spec as though it never changed from Homestead/Frontier. pub fn new_eip150_test() -> Spec { load(include_bytes!("../../res/ethereum/eip150_test.json")) } +/// Create a new Homestead-EIP150 chain spec as though it never changed from Homestead/Frontier. +pub fn new_eip161_test() -> Spec { load(include_bytes!("../../res/ethereum/eip161_test.json")) } + /// Create a new Frontier/Homestead/DAO chain spec with transition points at #5 and #8. pub fn new_transition_test() -> Spec { load(include_bytes!("../../res/ethereum/transition_test.json")) } diff --git a/ethcore/src/evm/ext.rs b/ethcore/src/evm/ext.rs index 6397f067e..1c340b5b1 100644 --- a/ethcore/src/evm/ext.rs +++ b/ethcore/src/evm/ext.rs @@ -52,6 +52,12 @@ pub trait Ext { /// Determine whether an account exists. fn exists(&self, address: &Address) -> bool; + /// Determine whether an account exists and is not null (zero balance/nonce, no code). + fn exists_and_not_null(&self, address: &Address) -> bool; + + /// Balance of the origin account. + fn origin_balance(&self) -> U256; + /// Returns address balance. fn balance(&self, address: &Address) -> U256; diff --git a/ethcore/src/evm/interpreter/gasometer.rs b/ethcore/src/evm/interpreter/gasometer.rs index a2b940655..beaaadac5 100644 --- a/ethcore/src/evm/interpreter/gasometer.rs +++ b/ethcore/src/evm/interpreter/gasometer.rs @@ -146,8 +146,13 @@ impl Gasometer { instructions::SUICIDE => { let mut gas = Gas::from(schedule.suicide_gas); + let is_value_transfer = !ext.origin_balance().is_zero(); let address = u256_to_address(stack.peek(0)); - if !ext.exists(&address) { + if ( + !schedule.no_empty && !ext.exists(&address) + ) || ( + schedule.no_empty && is_value_transfer && !ext.exists_and_not_null(&address) + ) { gas = overflowing!(gas.overflow_add(schedule.suicide_to_new_account_cost.into())); } @@ -190,12 +195,19 @@ impl Gasometer { ); let address = u256_to_address(stack.peek(1)); + let is_value_transfer = !stack.peek(2).is_zero(); - if instruction == instructions::CALL && !ext.exists(&address) { - gas = overflowing!(gas.overflow_add(schedule.call_new_account_gas.into())); + if instruction == instructions::CALL { + if ( + !schedule.no_empty && !ext.exists(&address) + ) || ( + schedule.no_empty && is_value_transfer && !ext.exists_and_not_null(&address) + ) { + gas = overflowing!(gas.overflow_add(schedule.call_new_account_gas.into())); + } }; - if !stack.peek(2).is_zero() { + if is_value_transfer { gas = overflowing!(gas.overflow_add(schedule.call_value_transfer_gas.into())); }; diff --git a/ethcore/src/evm/schedule.rs b/ethcore/src/evm/schedule.rs index b8de785b3..b68f6acb5 100644 --- a/ethcore/src/evm/schedule.rs +++ b/ethcore/src/evm/schedule.rs @@ -93,6 +93,10 @@ pub struct Schedule { /// If Some(x): let limit = GAS * (x - 1) / x; let CALL's gas = min(requested, limit). let CREATE's gas = limit. /// If None: let CALL's gas = (requested > GAS ? [OOG] : GAS). let CREATE's gas = GAS pub sub_gas_cap_divisor: Option, + /// Don't ever make empty accounts; contracts start with nonce=1. Also, don't charge 25k when sending/suicide zero-value. + pub no_empty: bool, + /// Kill empty accounts if touched. + pub kill_empty: bool, } impl Schedule { @@ -106,16 +110,16 @@ impl Schedule { Self::new(true, true, 53000) } - /// Schedule for the Homestead-era of the Ethereum main net. - pub fn new_homestead_gas_fix() -> Schedule { - Schedule{ + /// Schedule for the post-EIP-150-era of the Ethereum main net. + pub fn new_post_eip150(fix_exp: bool, no_empty: bool, kill_empty: bool) -> Schedule { + Schedule { exceptional_failed_code_deposit: true, have_delegate_call: true, stack_limit: 1024, max_depth: 1024, tier_step_gas: [0, 2, 3, 5, 8, 10, 20, 0], exp_gas: 10, - exp_byte_gas: 10, + exp_byte_gas: if fix_exp {50} else {10}, sha3_gas: 30, sha3_word_gas: 6, sload_gas: 200, @@ -146,11 +150,13 @@ impl Schedule { suicide_gas: 5000, suicide_to_new_account_cost: 25000, sub_gas_cap_divisor: Some(64), + no_empty: no_empty, + kill_empty: kill_empty, } } fn new(efcd: bool, hdc: bool, tcg: usize) -> Schedule { - Schedule{ + Schedule { exceptional_failed_code_deposit: efcd, have_delegate_call: hdc, stack_limit: 1024, @@ -188,6 +194,8 @@ impl Schedule { suicide_gas: 0, suicide_to_new_account_cost: 0, sub_gas_cap_divisor: None, + no_empty: false, + kill_empty: false, } } } diff --git a/ethcore/src/evm/tests.rs b/ethcore/src/evm/tests.rs index ba002d649..7e69c0771 100644 --- a/ethcore/src/evm/tests.rs +++ b/ethcore/src/evm/tests.rs @@ -94,6 +94,14 @@ impl Ext for FakeExt { self.balances.contains_key(address) } + fn exists_and_not_null(&self, address: &Address) -> bool { + self.balances.get(address).map_or(false, |b| !b.is_zero()) + } + + fn origin_balance(&self) -> U256 { + unimplemented!() + } + fn balance(&self, address: &Address) -> U256 { *self.balances.get(address).unwrap() } diff --git a/ethcore/src/executive.rs b/ethcore/src/executive.rs index f05cc4fd8..5da105e2f 100644 --- a/ethcore/src/executive.rs +++ b/ethcore/src/executive.rs @@ -17,7 +17,7 @@ //! Transaction Execution environment. use util::*; use action_params::{ActionParams, ActionValue}; -use state::{State, Substate}; +use state::{State, Substate, CleanupMode}; use engines::Engine; use types::executed::CallType; use env_info::EnvInfo; @@ -256,9 +256,11 @@ impl<'a> Executive<'a> { // backup used in case of running out of gas self.state.checkpoint(); + let schedule = self.engine.schedule(self.info); + // at first, transfer value to destination if let ActionValue::Transfer(val) = params.value { - self.state.transfer_balance(¶ms.sender, ¶ms.address, &val); + self.state.transfer_balance(¶ms.sender, ¶ms.address, &val, substate.to_cleanup_mode(&schedule)); } trace!("Executive::call(params={:?}) self.env_info={:?}", params, self.info); @@ -364,12 +366,14 @@ impl<'a> Executive<'a> { let mut unconfirmed_substate = Substate::new(); // create contract and transfer value to it if necessary + let schedule = self.engine.schedule(self.info); + let nonce_offset = if schedule.no_empty {1} else {0}.into(); let prev_bal = self.state.balance(¶ms.address); if let ActionValue::Transfer(val) = params.value { self.state.sub_balance(¶ms.sender, &val); - self.state.new_contract(¶ms.address, val + prev_bal); + self.state.new_contract(¶ms.address, val + prev_bal, nonce_offset); } else { - self.state.new_contract(¶ms.address, prev_bal); + self.state.new_contract(¶ms.address, prev_bal, nonce_offset); } let trace_info = tracer.prepare_trace_create(¶ms); @@ -405,7 +409,7 @@ impl<'a> Executive<'a> { fn finalize( &mut self, t: &SignedTransaction, - substate: Substate, + mut substate: Substate, result: evm::Result, output: Bytes, trace: Vec, @@ -440,15 +444,23 @@ impl<'a> Executive<'a> { }; trace!("exec::finalize: Refunding refund_value={}, sender={}\n", refund_value, sender); - self.state.add_balance(&sender, &refund_value); + // Below: NoEmpty is safe since the sender must already be non-null to have sent this transaction + self.state.add_balance(&sender, &refund_value, CleanupMode::NoEmpty); trace!("exec::finalize: Compensating author: fees_value={}, author={}\n", fees_value, &self.info.author); - self.state.add_balance(&self.info.author, &fees_value); + self.state.add_balance(&self.info.author, &fees_value, substate.to_cleanup_mode(&schedule)); // perform suicides for address in &substate.suicides { self.state.kill_account(address); } + // perform garbage-collection + for address in &substate.garbage { + if self.state.exists(address) && !self.state.exists_and_not_null(address) { + self.state.kill_account(address); + } + } + match result { Err(evm::Error::Internal) => Err(ExecutionError::Internal), Err(_) => { @@ -509,7 +521,7 @@ mod tests { use env_info::EnvInfo; use evm::{Factory, VMType}; use error::ExecutionError; - use state::Substate; + use state::{Substate, CleanupMode}; use tests::helpers::*; use trace::trace; use trace::{FlatTrace, Tracer, NoopTracer, ExecutiveTracer}; @@ -538,7 +550,7 @@ mod tests { params.value = ActionValue::Transfer(U256::from(0x7)); let mut state_result = get_temp_state(); let mut state = state_result.reference_mut(); - state.add_balance(&sender, &U256::from(0x100u64)); + state.add_balance(&sender, &U256::from(0x100u64), CleanupMode::NoEmpty); let info = EnvInfo::default(); let engine = TestEngine::new(0); let mut substate = Substate::new(); @@ -597,7 +609,7 @@ mod tests { params.value = ActionValue::Transfer(U256::from(100)); let mut state_result = get_temp_state(); let mut state = state_result.reference_mut(); - state.add_balance(&sender, &U256::from(100)); + state.add_balance(&sender, &U256::from(100), CleanupMode::NoEmpty); let info = EnvInfo::default(); let engine = TestEngine::new(0); let mut substate = Substate::new(); @@ -656,7 +668,7 @@ mod tests { params.call_type = CallType::Call; let mut state_result = get_temp_state(); let mut state = state_result.reference_mut(); - state.add_balance(&sender, &U256::from(100)); + state.add_balance(&sender, &U256::from(100), CleanupMode::NoEmpty); let info = EnvInfo::default(); let engine = TestEngine::new(5); let mut substate = Substate::new(); @@ -767,7 +779,7 @@ mod tests { params.value = ActionValue::Transfer(100.into()); let mut state_result = get_temp_state(); let mut state = state_result.reference_mut(); - state.add_balance(&sender, &U256::from(100)); + state.add_balance(&sender, &U256::from(100), CleanupMode::NoEmpty); let info = EnvInfo::default(); let engine = TestEngine::new(5); let mut substate = Substate::new(); @@ -855,7 +867,7 @@ mod tests { params.value = ActionValue::Transfer(U256::from(100)); let mut state_result = get_temp_state(); let mut state = state_result.reference_mut(); - state.add_balance(&sender, &U256::from(100)); + state.add_balance(&sender, &U256::from(100), CleanupMode::NoEmpty); let info = EnvInfo::default(); let engine = TestEngine::new(0); let mut substate = Substate::new(); @@ -907,7 +919,7 @@ mod tests { params.value = ActionValue::Transfer(U256::from(100)); let mut state_result = get_temp_state(); let mut state = state_result.reference_mut(); - state.add_balance(&sender, &U256::from(100)); + state.add_balance(&sender, &U256::from(100), CleanupMode::NoEmpty); let info = EnvInfo::default(); let engine = TestEngine::new(1024); let mut substate = Substate::new(); @@ -967,7 +979,7 @@ mod tests { let mut state = state_result.reference_mut(); state.init_code(&address_a, code_a.clone()); state.init_code(&address_b, code_b.clone()); - state.add_balance(&sender, &U256::from(100_000)); + state.add_balance(&sender, &U256::from(100_000), CleanupMode::NoEmpty); let info = EnvInfo::default(); let engine = TestEngine::new(0); @@ -1040,13 +1052,13 @@ mod tests { gas: U256::from(100_000), gas_price: U256::zero(), nonce: U256::zero() - }.sign(keypair.secret()); + }.sign(keypair.secret(), None); let sender = t.sender().unwrap(); let contract = contract_address(&sender, &U256::zero()); let mut state_result = get_temp_state(); let mut state = state_result.reference_mut(); - state.add_balance(&sender, &U256::from(18)); + state.add_balance(&sender, &U256::from(18), CleanupMode::NoEmpty); let mut info = EnvInfo::default(); info.gas_limit = U256::from(100_000); let engine = TestEngine::new(0); @@ -1107,12 +1119,12 @@ mod tests { gas: U256::from(100_000), gas_price: U256::zero(), nonce: U256::one() - }.sign(keypair.secret()); + }.sign(keypair.secret(), None); let sender = t.sender().unwrap(); let mut state_result = get_temp_state(); let mut state = state_result.reference_mut(); - state.add_balance(&sender, &U256::from(17)); + state.add_balance(&sender, &U256::from(17), CleanupMode::NoEmpty); let mut info = EnvInfo::default(); info.gas_limit = U256::from(100_000); let engine = TestEngine::new(0); @@ -1140,12 +1152,12 @@ mod tests { gas: U256::from(80_001), gas_price: U256::zero(), nonce: U256::zero() - }.sign(keypair.secret()); + }.sign(keypair.secret(), None); let sender = t.sender().unwrap(); let mut state_result = get_temp_state(); let mut state = state_result.reference_mut(); - state.add_balance(&sender, &U256::from(17)); + state.add_balance(&sender, &U256::from(17), CleanupMode::NoEmpty); let mut info = EnvInfo::default(); info.gas_used = U256::from(20_000); info.gas_limit = U256::from(100_000); @@ -1175,12 +1187,12 @@ mod tests { gas: U256::from(100_000), gas_price: U256::one(), nonce: U256::zero() - }.sign(keypair.secret()); + }.sign(keypair.secret(), None); let sender = t.sender().unwrap(); let mut state_result = get_temp_state(); let mut state = state_result.reference_mut(); - state.add_balance(&sender, &U256::from(100_017)); + state.add_balance(&sender, &U256::from(100_017), CleanupMode::NoEmpty); let mut info = EnvInfo::default(); info.gas_limit = U256::from(100_000); let engine = TestEngine::new(0); @@ -1215,7 +1227,7 @@ mod tests { params.value = ActionValue::Transfer(U256::from_str("0de0b6b3a7640000").unwrap()); let mut state_result = get_temp_state(); let mut state = state_result.reference_mut(); - state.add_balance(&sender, &U256::from_str("152d02c7e14af6800000").unwrap()); + state.add_balance(&sender, &U256::from_str("152d02c7e14af6800000").unwrap(), CleanupMode::NoEmpty); let info = EnvInfo::default(); let engine = TestEngine::new(0); let mut substate = Substate::new(); diff --git a/ethcore/src/externalities.rs b/ethcore/src/externalities.rs index bbe81a511..df1b64e67 100644 --- a/ethcore/src/externalities.rs +++ b/ethcore/src/externalities.rs @@ -114,6 +114,12 @@ impl<'a, T, V> Ext for Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMT self.state.exists(address) } + fn exists_and_not_null(&self, address: &Address) -> bool { + self.state.exists_and_not_null(address) + } + + fn origin_balance(&self) -> U256 { self.balance(&self.origin_info.address) } + fn balance(&self, address: &Address) -> U256 { self.state.balance(address) } @@ -269,11 +275,11 @@ impl<'a, T, V> Ext for Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMT let address = self.origin_info.address.clone(); let balance = self.balance(&address); if &address == refund_address { - // TODO [todr] To be consisted with CPP client we set balance to 0 in that case. + // TODO [todr] To be consistent with CPP client we set balance to 0 in that case. self.state.sub_balance(&address, &balance); } else { - trace!("Suiciding {} -> {} (xfer: {})", address, refund_address, balance); - self.state.transfer_balance(&address, refund_address, &balance); + trace!(target: "ext", "Suiciding {} -> {} (xfer: {})", address, refund_address, balance); + self.state.transfer_balance(&address, refund_address, &balance, self.substate.to_cleanup_mode(&self.schedule)); } self.tracer.trace_suicide(address, balance, refund_address.clone()); diff --git a/ethcore/src/json_tests/chain.rs b/ethcore/src/json_tests/chain.rs index bf32db133..b50241199 100644 --- a/ethcore/src/json_tests/chain.rs +++ b/ethcore/src/json_tests/chain.rs @@ -49,6 +49,7 @@ pub fn json_chain_test(json_data: &[u8], era: ChainEra) -> Vec { ChainEra::Frontier => ethereum::new_frontier_test(), ChainEra::Homestead => ethereum::new_homestead_test(), ChainEra::Eip150 => ethereum::new_eip150_test(), + ChainEra::Eip161 => ethereum::new_eip161_test(), ChainEra::TransitionTest => ethereum::new_transition_test(), }; spec.set_genesis_state(state); diff --git a/ethcore/src/json_tests/eip161_state.rs b/ethcore/src/json_tests/eip161_state.rs new file mode 100644 index 000000000..da7997fa1 --- /dev/null +++ b/ethcore/src/json_tests/eip161_state.rs @@ -0,0 +1,51 @@ +// 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 . + +use super::test_common::*; +use tests::helpers::*; +use super::state::json_chain_test; + +fn do_json_test(json_data: &[u8]) -> Vec { + json_chain_test(json_data, ChainEra::Eip161) +} + +declare_test!{StateTests_EIP158_stEIP158SpecificTest, "StateTests/EIP158/stEIP158SpecificTest"} +declare_test!{StateTests_EIP158_stNonZeroCallsTest, "StateTests/EIP158/stNonZeroCallsTest"} +declare_test!{StateTests_EIP158_stZeroCallsTest, "StateTests/EIP158/stZeroCallsTest"} + +declare_test!{StateTests_EIP158_EIP150_stMemExpandingEIPCalls, "StateTests/EIP158/EIP150/stMemExpandingEIPCalls"} +declare_test!{StateTests_EIP158_EIP150_stEIPSpecificTest, "StateTests/EIP158/EIP150/stEIPSpecificTest"} +declare_test!{StateTests_EIP158_EIP150_stEIPsingleCodeGasPrices, "StateTests/EIP158/EIP150/stEIPsingleCodeGasPrices"} +declare_test!{StateTests_EIP158_EIP150_stChangedTests, "StateTests/EIP158/EIP150/stChangedTests"} + +declare_test!{StateTests_EIP158_Homestead_stBoundsTest, "StateTests/EIP158/Homestead/stBoundsTest"} +declare_test!{StateTests_EIP158_Homestead_stCallCodes, "StateTests/EIP158/Homestead/stCallCodes"} +declare_test!{StateTests_EIP158_Homestead_stCallCreateCallCodeTest, "StateTests/EIP158/Homestead/stCallCreateCallCodeTest"} +declare_test!{StateTests_EIP158_Homestead_stCallDelegateCodes, "StateTests/EIP158/Homestead/stCallDelegateCodes"} +declare_test!{StateTests_EIP158_Homestead_stCallDelegateCodesCallCode, "StateTests/EIP158/Homestead/stCallDelegateCodesCallCode"} +declare_test!{StateTests_EIP158_Homestead_stDelegatecallTest, "StateTests/EIP158/Homestead/stDelegatecallTest"} +declare_test!{StateTests_EIP158_Homestead_stHomeSteadSpecific, "StateTests/EIP158/Homestead/stHomeSteadSpecific"} +declare_test!{StateTests_EIP158_Homestead_stInitCodeTest, "StateTests/EIP158/Homestead/stInitCodeTest"} +declare_test!{StateTests_EIP158_Homestead_stLogTests, "StateTests/EIP158/Homestead/stLogTests"} +declare_test!{heavy => StateTests_EIP158_Homestead_stMemoryTest, "StateTests/EIP158/Homestead/stMemoryTest"} +declare_test!{StateTests_EIP158_Homestead_stPreCompiledContracts, "StateTests/EIP158/Homestead/stPreCompiledContracts"} +declare_test!{heavy => StateTests_EIP158_Homestead_stQuadraticComplexityTest, "StateTests/EIP158/Homestead/stQuadraticComplexityTest"} +declare_test!{StateTests_EIP158_Homestead_stRecursiveCreate, "StateTests/EIP158/Homestead/stRecursiveCreate"} +declare_test!{StateTests_EIP158_Homestead_stRefundTest, "StateTests/EIP158/Homestead/stRefundTest"} +declare_test!{StateTests_EIP158_Homestead_stSpecialTest, "StateTests/EIP158/Homestead/stSpecialTest"} +declare_test!{StateTests_EIP158_Homestead_stSystemOperationsTest, "StateTests/EIP158/Homestead/stSystemOperationsTest"} +declare_test!{StateTests_EIP158_Homestead_stTransactionTest, "StateTests/EIP158/Homestead/stTransactionTest"} +declare_test!{StateTests_EIP158_Homestead_stWalletTest, "StateTests/EIP158/Homestead/stWalletTest"} \ No newline at end of file diff --git a/ethcore/src/json_tests/executive.rs b/ethcore/src/json_tests/executive.rs index 1d4faec62..60321f971 100644 --- a/ethcore/src/json_tests/executive.rs +++ b/ethcore/src/json_tests/executive.rs @@ -92,10 +92,18 @@ impl<'a, T, V> Ext for TestExt<'a, T, V> where T: Tracer, V: VMTracer { self.ext.exists(address) } + fn exists_and_not_null(&self, address: &Address) -> bool { + self.ext.exists_and_not_null(address) + } + fn balance(&self, address: &Address) -> U256 { self.ext.balance(address) } + fn origin_balance(&self) -> U256 { + self.ext.origin_balance() + } + fn blockhash(&self, number: &U256) -> H256 { self.ext.blockhash(number) } diff --git a/ethcore/src/json_tests/mod.rs b/ethcore/src/json_tests/mod.rs index 7a5dd30d2..13d3fb5bb 100644 --- a/ethcore/src/json_tests/mod.rs +++ b/ethcore/src/json_tests/mod.rs @@ -24,4 +24,5 @@ mod chain; mod homestead_state; mod homestead_chain; mod eip150_state; +mod eip161_state; mod trie; diff --git a/ethcore/src/json_tests/state.rs b/ethcore/src/json_tests/state.rs index c3e74af5d..bf84d50ee 100644 --- a/ethcore/src/json_tests/state.rs +++ b/ethcore/src/json_tests/state.rs @@ -29,6 +29,7 @@ pub fn json_chain_test(json_data: &[u8], era: ChainEra) -> Vec { ChainEra::Frontier => ethereum::new_mainnet_like().engine, ChainEra::Homestead => ethereum::new_homestead_test().engine, ChainEra::Eip150 => ethereum::new_eip150_test().engine, + ChainEra::Eip161 => ethereum::new_eip161_test().engine, ChainEra::TransitionTest => ethereum::new_transition_test().engine, }; diff --git a/ethcore/src/json_tests/transaction.rs b/ethcore/src/json_tests/transaction.rs index 50061cbfd..dd5a4ef14 100644 --- a/ethcore/src/json_tests/transaction.rs +++ b/ethcore/src/json_tests/transaction.rs @@ -35,17 +35,24 @@ fn do_json_test(json_data: &[u8]) -> Vec { Some(x) if x < 1_150_000 => &old_schedule, Some(_) => &new_schedule }; + let allow_network_id_of_one = number.map_or(false, |n| n > 2600000); let rlp: Vec = test.rlp.into(); let res = UntrustedRlp::new(&rlp) .as_val() .map_err(From::from) - .and_then(|t: SignedTransaction| t.validate(schedule, schedule.have_delegate_call)); + .and_then(|t: SignedTransaction| t.validate(schedule, schedule.have_delegate_call, allow_network_id_of_one)); fail_unless(test.transaction.is_none() == res.is_err()); if let (Some(tx), Some(sender)) = (test.transaction, test.sender) { let t = res.unwrap(); fail_unless(t.sender().unwrap() == sender.into()); + let is_acceptable_network_id = match t.network_id() { + None => true, + Some(1) if allow_network_id_of_one => true, + _ => false, + }; + fail_unless(is_acceptable_network_id); let data: Vec = tx.data.into(); fail_unless(t.data == data); fail_unless(t.gas_price == tx.gas_price.into()); diff --git a/ethcore/src/miner/banning_queue.rs b/ethcore/src/miner/banning_queue.rs index f127dc7e8..0fdea2ac3 100644 --- a/ethcore/src/miner/banning_queue.rs +++ b/ethcore/src/miner/banning_queue.rs @@ -245,7 +245,7 @@ mod tests { gas: U256::from(100_000), gas_price: U256::from(10), nonce: U256::from(0), - }.sign(keypair.secret()) + }.sign(keypair.secret(), None) } fn unwrap_err(res: Result) -> TransactionError { diff --git a/ethcore/src/miner/miner.rs b/ethcore/src/miner/miner.rs index d36869a74..19a2b9a10 100644 --- a/ethcore/src/miner/miner.rs +++ b/ethcore/src/miner/miner.rs @@ -21,7 +21,7 @@ use util::*; use util::using_queue::{UsingQueue, GetAction}; use account_provider::AccountProvider; use views::{BlockView, HeaderView}; -use state::State; +use state::{State, CleanupMode}; use client::{MiningBlockChainClient, Executive, Executed, EnvInfo, TransactOptions, BlockID, CallAnalytics}; use executive::contract_address; use block::{ClosedBlock, SealedBlock, IsBlock, Block}; @@ -650,7 +650,7 @@ impl MinerService for Miner { let needed_balance = t.value + t.gas * t.gas_price; if balance < needed_balance { // give the sender a sufficient balance - state.add_balance(&sender, &(needed_balance - balance)); + state.add_balance(&sender, &(needed_balance - balance), CleanupMode::NoEmpty); } let options = TransactOptions { tracing: analytics.transaction_tracing, vm_tracing: analytics.vm_tracing, check_nonce: false }; let mut ret = try!(Executive::new(&mut state, &env_info, &*self.engine, chain.vm_factory()).transact(t, options)); @@ -935,6 +935,8 @@ impl MinerService for Miner { } }, logs: receipt.logs.clone(), + log_bloom: receipt.log_bloom, + state_root: receipt.state_root, } }) } @@ -1173,7 +1175,7 @@ mod tests { gas: U256::from(100_000), gas_price: U256::zero(), nonce: U256::zero(), - }.sign(keypair.secret()) + }.sign(keypair.secret(), None) } #[test] diff --git a/ethcore/src/miner/transaction_queue.rs b/ethcore/src/miner/transaction_queue.rs index 51c1863f6..cc10bbe98 100644 --- a/ethcore/src/miner/transaction_queue.rs +++ b/ethcore/src/miner/transaction_queue.rs @@ -42,8 +42,8 @@ //! let t2 = Transaction { action: Action::Create, value: U256::from(100), data: "3331600055".from_hex().unwrap(), //! gas: U256::from(100_000), gas_price: U256::one(), nonce: U256::from(11) }; //! -//! let st1 = t1.sign(&key.secret()); -//! let st2 = t2.sign(&key.secret()); +//! let st1 = t1.sign(&key.secret(), None); +//! let st2 = t2.sign(&key.secret(), None); //! let default_account_details = |_a: &Address| AccountDetails { //! nonce: U256::from(10), //! balance: U256::from(1_000_000), @@ -1104,12 +1104,12 @@ mod test { fn new_tx(nonce: U256, gas_price: U256) -> SignedTransaction { let keypair = Random.generate().unwrap(); - new_unsigned_tx(nonce, default_gas_val(), gas_price).sign(keypair.secret()) + new_unsigned_tx(nonce, default_gas_val(), gas_price).sign(keypair.secret(), None) } fn new_tx_with_gas(gas: U256, gas_price: U256) -> SignedTransaction { let keypair = Random.generate().unwrap(); - new_unsigned_tx(default_nonce(), gas, gas_price).sign(keypair.secret()) + new_unsigned_tx(default_nonce(), gas, gas_price).sign(keypair.secret(), None) } fn new_tx_default() -> SignedTransaction { @@ -1133,7 +1133,7 @@ mod test { let keypair = Random.generate().unwrap(); let secret = &keypair.secret(); - (tx1.sign(secret), tx2.sign(secret)) + (tx1.sign(secret, None), tx2.sign(secret, None)) } /// Returns two consecutive transactions, both with increased gas price @@ -1144,7 +1144,7 @@ mod test { let keypair = Random.generate().unwrap(); let secret = &keypair.secret(); - (tx1.sign(secret), tx2.sign(secret)) + (tx1.sign(secret, None), tx2.sign(secret, None)) } fn new_tx_pair_default(nonce_increment: U256, gas_price_increment: U256) -> (SignedTransaction, SignedTransaction) { @@ -1798,9 +1798,9 @@ mod test { let mut txq = TransactionQueue::default(); let kp = Random.generate().unwrap(); let secret = kp.secret(); - let tx = new_unsigned_tx(123.into(), default_gas_val(), 1.into()).sign(secret); - let tx1 = new_unsigned_tx(124.into(), default_gas_val(), 1.into()).sign(secret); - let tx2 = new_unsigned_tx(125.into(), default_gas_val(), 1.into()).sign(secret); + let tx = new_unsigned_tx(123.into(), default_gas_val(), 1.into()).sign(secret, None); + let tx1 = new_unsigned_tx(124.into(), default_gas_val(), 1.into()).sign(secret, None); + let tx2 = new_unsigned_tx(125.into(), default_gas_val(), 1.into()).sign(secret, None); txq.add(tx, TransactionOrigin::External, &default_account_details, &gas_estimator).unwrap(); assert_eq!(txq.status().pending, 1); @@ -2038,11 +2038,11 @@ mod test { // given let mut txq = TransactionQueue::default(); let keypair = Random.generate().unwrap(); - let tx = new_unsigned_tx(123.into(), default_gas_val(), 1.into()).sign(keypair.secret()); + let tx = new_unsigned_tx(123.into(), default_gas_val(), 1.into()).sign(keypair.secret(), None); let tx2 = { let mut tx2 = (*tx).clone(); tx2.gas_price = U256::from(200); - tx2.sign(keypair.secret()) + tx2.sign(keypair.secret(), None) }; // when @@ -2061,16 +2061,16 @@ mod test { // given let mut txq = TransactionQueue::default(); let keypair = Random.generate().unwrap(); - let tx0 = new_unsigned_tx(123.into(), default_gas_val(), 1.into()).sign(keypair.secret()); + let tx0 = new_unsigned_tx(123.into(), default_gas_val(), 1.into()).sign(keypair.secret(), None); let tx1 = { let mut tx1 = (*tx0).clone(); tx1.nonce = U256::from(124); - tx1.sign(keypair.secret()) + tx1.sign(keypair.secret(), None) }; let tx2 = { let mut tx2 = (*tx1).clone(); tx2.gas_price = U256::from(200); - tx2.sign(keypair.secret()) + tx2.sign(keypair.secret(), None) }; // when @@ -2223,7 +2223,7 @@ mod test { let tx3 = new_unsigned_tx(nonce + 2.into(), gas, 1.into()); - (tx.sign(secret), tx2.sign(secret), tx2_2.sign(secret), tx3.sign(secret)) + (tx.sign(secret, None), tx2.sign(secret, None), tx2_2.sign(secret, None), tx3.sign(secret, None)) }; let sender = tx1.sender().unwrap(); txq.add(tx1, TransactionOrigin::Local, &default_account_details, &gas_estimator).unwrap(); diff --git a/ethcore/src/spec/spec.rs b/ethcore/src/spec/spec.rs index 46e99c12e..2babfb708 100644 --- a/ethcore/src/spec/spec.rs +++ b/ethcore/src/spec/spec.rs @@ -38,7 +38,7 @@ pub struct CommonParams { /// Maximum size of extra data. pub maximum_extra_data_size: usize, /// Network id. - pub network_id: U256, + pub network_id: usize, /// Main subprotocol name. pub subprotocol_name: String, /// Minimum gas limit. @@ -160,7 +160,7 @@ impl Spec { pub fn nodes(&self) -> &[String] { &self.nodes } /// Get the configured Network ID. - pub fn network_id(&self) -> U256 { self.params.network_id } + pub fn network_id(&self) -> usize { self.params.network_id } /// Get the configured Network ID. pub fn subprotocol_name(&self) -> String { self.params.subprotocol_name.clone() } @@ -250,7 +250,7 @@ impl Spec { } trace!(target: "spec", "ensure_db_good: Populated sec trie; root is {}", root); for (address, account) in self.genesis_state.get().iter() { - db.note_account_bloom(address); + db.note_non_null_account(address); account.insert_additional(&mut AccountDBMut::new(db.as_hashdb_mut(), address)); } assert!(db.as_hashdb().contains(&self.state_root())); diff --git a/ethcore/src/state/account.rs b/ethcore/src/state/account.rs index d8d281b17..76061f6a0 100644 --- a/ethcore/src/state/account.rs +++ b/ethcore/src/state/account.rs @@ -300,11 +300,17 @@ impl Account { pub fn storage_is_clean(&self) -> bool { self.storage_changes.is_empty() } /// Check if account has zero nonce, balance, no code and no storage. + /// + /// NOTE: Will panic if `!self.storage_is_clean()` pub fn is_empty(&self) -> bool { - self.storage_changes.is_empty() && + assert!(self.storage_is_clean(), "Account::is_empty() may only legally be called when storage is clean."); + self.is_null() && self.storage_root == SHA3_NULL_RLP + } + + /// Check if account has zero nonce, balance, no code. + pub fn is_null(&self) -> bool { self.balance.is_zero() && self.nonce.is_zero() && - self.storage_root == SHA3_NULL_RLP && self.code_hash == SHA3_EMPTY } diff --git a/ethcore/src/state/mod.rs b/ethcore/src/state/mod.rs index 7c0f43d97..01a7e3b15 100644 --- a/ethcore/src/state/mod.rs +++ b/ethcore/src/state/mod.rs @@ -199,6 +199,13 @@ enum RequireCache { Code, } +#[derive(PartialEq)] +pub enum CleanupMode<'a> { + ForceCreate, + NoEmpty, + KillEmpty(&'a mut HashSet
), +} + const SEC_TRIE_DB_UNWRAP_STR: &'static str = "A state can only be created with valid root. Creating a SecTrieDB with a valid root will not fail. \ Therefore creating a SecTrieDB with this state's root will not fail."; @@ -329,8 +336,8 @@ impl State { /// Create a new contract at address `contract`. If there is already an account at the address /// it will have its code reset, ready for `init_code()`. - pub fn new_contract(&mut self, contract: &Address, balance: U256) { - self.insert_cache(contract, AccountEntry::new_dirty(Some(Account::new_contract(balance, self.account_start_nonce)))); + pub fn new_contract(&mut self, contract: &Address, balance: U256, nonce_offset: U256) { + self.insert_cache(contract, AccountEntry::new_dirty(Some(Account::new_contract(balance, self.account_start_nonce + nonce_offset)))); } /// Remove an existing account. @@ -341,10 +348,15 @@ impl State { /// Determine whether an account exists. pub fn exists(&self, a: &Address) -> bool { // Bloom filter does not contain empty accounts, so it is important here to - // check if account exists in the database directly before EIP-158 is in effect. + // check if account exists in the database directly before EIP-161 is in effect. self.ensure_cached(a, RequireCache::None, false, |a| a.is_some()) } + /// Determine whether an account exists and if not empty. + pub fn exists_and_not_null(&self, a: &Address) -> bool { + self.ensure_cached(a, RequireCache::None, false, |a| a.map_or(false, |a| !a.is_null())) + } + /// Get the balance of account `a`. pub fn balance(&self, a: &Address) -> U256 { self.ensure_cached(a, RequireCache::None, true, @@ -399,7 +411,7 @@ impl State { } // check bloom before any requests to trie - if !self.db.check_account_bloom(address) { return H256::zero() } + if !self.db.check_non_null_bloom(address) { return H256::zero() } // account is not found in the global cache, get from the DB and insert into local let db = self.factories.trie.readonly(self.db.as_hashdb(), &self.root).expect(SEC_TRIE_DB_UNWRAP_STR); @@ -433,10 +445,18 @@ impl State { } /// Add `incr` to the balance of account `a`. - pub fn add_balance(&mut self, a: &Address, incr: &U256) { + pub fn add_balance(&mut self, a: &Address, incr: &U256, cleanup_mode: CleanupMode) { trace!(target: "state", "add_balance({}, {}): {}", a, incr, self.balance(a)); - if !incr.is_zero() || !self.exists(a) { + let is_value_transfer = !incr.is_zero(); + if is_value_transfer || (cleanup_mode == CleanupMode::ForceCreate && !self.exists(a)) { self.require(a, false).add_balance(incr); + } else { + match cleanup_mode { + CleanupMode::KillEmpty(set) => if !is_value_transfer && self.exists(a) && !self.exists_and_not_null(a) { + set.insert(a.clone()); + }, + _ => {} + } } } @@ -449,9 +469,9 @@ impl State { } /// Subtracts `by` from the balance of `from` and adds it to that of `to`. - pub fn transfer_balance(&mut self, from: &Address, to: &Address, by: &U256) { + pub fn transfer_balance(&mut self, from: &Address, to: &Address, by: &U256, cleanup_mode: CleanupMode) { self.sub_balance(from, by); - self.add_balance(to, by); + self.add_balance(to, by, cleanup_mode); } /// Increment the nonce of account `a` by 1. @@ -507,13 +527,15 @@ impl State { // first, commit the sub trees. for (address, ref mut a) in accounts.iter_mut().filter(|&(_, ref a)| a.is_dirty()) { if let Some(ref mut account) = a.account { - if !account.is_empty() { - db.note_account_bloom(address); - } let addr_hash = account.address_hash(address); - let mut account_db = factories.accountdb.create(db.as_hashdb_mut(), addr_hash); - account.commit_storage(&factories.trie, account_db.as_hashdb_mut()); - account.commit_code(account_db.as_hashdb_mut()); + { + let mut account_db = factories.accountdb.create(db.as_hashdb_mut(), addr_hash); + account.commit_storage(&factories.trie, account_db.as_hashdb_mut()); + account.commit_code(account_db.as_hashdb_mut()); + } + if !account.is_empty() { + db.note_non_null_account(address); + } } } @@ -653,7 +675,7 @@ impl State { Some(r) => r, None => { // first check bloom if it is not in database for sure - if check_bloom && !self.db.check_account_bloom(a) { return f(None); } + if check_bloom && !self.db.check_non_null_bloom(a) { return f(None); } // not found in the global cache, get from the DB and insert into local let db = self.factories.trie.readonly(self.db.as_hashdb(), &self.root).expect(SEC_TRIE_DB_UNWRAP_STR); @@ -687,7 +709,7 @@ impl State { match self.db.get_cached_account(a) { Some(acc) => self.insert_cache(a, AccountEntry::new_clean_cached(acc)), None => { - let maybe_acc = if self.db.check_account_bloom(a) { + let maybe_acc = if self.db.check_non_null_bloom(a) { let db = self.factories.trie.readonly(self.db.as_hashdb(), &self.root).expect(SEC_TRIE_DB_UNWRAP_STR); match db.get(a) { Ok(Some(acc)) => AccountEntry::new_clean(Some(Account::from_rlp(&acc))), @@ -793,9 +815,9 @@ fn should_apply_create_transaction() { action: Action::Create, value: 100.into(), data: FromHex::from_hex("601080600c6000396000f3006000355415600957005b60203560003555").unwrap(), - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); - state.add_balance(t.sender().as_ref().unwrap(), &(100.into())); + state.add_balance(t.sender().as_ref().unwrap(), &(100.into()), CleanupMode::NoEmpty); let result = state.apply(&info, &engine, &t, true).unwrap(); let expected_trace = vec![FlatTrace { trace_address: Default::default(), @@ -853,9 +875,9 @@ fn should_trace_failed_create_transaction() { action: Action::Create, value: 100.into(), data: FromHex::from_hex("5b600056").unwrap(), - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); - state.add_balance(t.sender().as_ref().unwrap(), &(100.into())); + state.add_balance(t.sender().as_ref().unwrap(), &(100.into()), CleanupMode::NoEmpty); let result = state.apply(&info, &engine, &t, true).unwrap(); let expected_trace = vec![FlatTrace { trace_address: Default::default(), @@ -890,10 +912,10 @@ fn should_trace_call_transaction() { action: Action::Call(0xa.into()), value: 100.into(), data: vec![], - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); state.init_code(&0xa.into(), FromHex::from_hex("6000").unwrap()); - state.add_balance(t.sender().as_ref().unwrap(), &(100.into())); + state.add_balance(t.sender().as_ref().unwrap(), &(100.into()), CleanupMode::NoEmpty); let result = state.apply(&info, &engine, &t, true).unwrap(); let expected_trace = vec![FlatTrace { trace_address: Default::default(), @@ -933,9 +955,9 @@ fn should_trace_basic_call_transaction() { action: Action::Call(0xa.into()), value: 100.into(), data: vec![], - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); - state.add_balance(t.sender().as_ref().unwrap(), &(100.into())); + state.add_balance(t.sender().as_ref().unwrap(), &(100.into()), CleanupMode::NoEmpty); let result = state.apply(&info, &engine, &t, true).unwrap(); let expected_trace = vec![FlatTrace { trace_address: Default::default(), @@ -975,7 +997,7 @@ fn should_trace_call_transaction_to_builtin() { action: Action::Call(0x1.into()), value: 0.into(), data: vec![], - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); let result = state.apply(&info, engine, &t, true).unwrap(); @@ -1017,7 +1039,7 @@ fn should_not_trace_subcall_transaction_to_builtin() { action: Action::Call(0xa.into()), value: 0.into(), data: vec![], - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); state.init_code(&0xa.into(), FromHex::from_hex("600060006000600060006001610be0f1").unwrap()); let result = state.apply(&info, engine, &t, true).unwrap(); @@ -1060,7 +1082,7 @@ fn should_not_trace_callcode() { action: Action::Call(0xa.into()), value: 0.into(), data: vec![], - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); state.init_code(&0xa.into(), FromHex::from_hex("60006000600060006000600b611000f2").unwrap()); state.init_code(&0xb.into(), FromHex::from_hex("6000").unwrap()); @@ -1122,7 +1144,7 @@ fn should_not_trace_delegatecall() { action: Action::Call(0xa.into()), value: 0.into(), data: vec![], - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); state.init_code(&0xa.into(), FromHex::from_hex("6000600060006000600b618000f4").unwrap()); state.init_code(&0xb.into(), FromHex::from_hex("6000").unwrap()); @@ -1181,10 +1203,10 @@ fn should_trace_failed_call_transaction() { action: Action::Call(0xa.into()), value: 100.into(), data: vec![], - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); state.init_code(&0xa.into(), FromHex::from_hex("5b600056").unwrap()); - state.add_balance(t.sender().as_ref().unwrap(), &(100.into())); + state.add_balance(t.sender().as_ref().unwrap(), &(100.into()), CleanupMode::NoEmpty); let result = state.apply(&info, &engine, &t, true).unwrap(); let expected_trace = vec![FlatTrace { trace_address: Default::default(), @@ -1221,11 +1243,11 @@ fn should_trace_call_with_subcall_transaction() { action: Action::Call(0xa.into()), value: 100.into(), data: vec![], - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); state.init_code(&0xa.into(), FromHex::from_hex("60006000600060006000600b602b5a03f1").unwrap()); state.init_code(&0xb.into(), FromHex::from_hex("6000").unwrap()); - state.add_balance(t.sender().as_ref().unwrap(), &(100.into())); + state.add_balance(t.sender().as_ref().unwrap(), &(100.into()), CleanupMode::NoEmpty); let result = state.apply(&info, &engine, &t, true).unwrap(); let expected_trace = vec![FlatTrace { @@ -1281,10 +1303,10 @@ fn should_trace_call_with_basic_subcall_transaction() { action: Action::Call(0xa.into()), value: 100.into(), data: vec![], - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); state.init_code(&0xa.into(), FromHex::from_hex("60006000600060006045600b6000f1").unwrap()); - state.add_balance(t.sender().as_ref().unwrap(), &(100.into())); + state.add_balance(t.sender().as_ref().unwrap(), &(100.into()), CleanupMode::NoEmpty); let result = state.apply(&info, &engine, &t, true).unwrap(); let expected_trace = vec![FlatTrace { trace_address: Default::default(), @@ -1336,10 +1358,10 @@ fn should_not_trace_call_with_invalid_basic_subcall_transaction() { action: Action::Call(0xa.into()), value: 100.into(), data: vec![], - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); state.init_code(&0xa.into(), FromHex::from_hex("600060006000600060ff600b6000f1").unwrap()); // not enough funds. - state.add_balance(t.sender().as_ref().unwrap(), &(100.into())); + state.add_balance(t.sender().as_ref().unwrap(), &(100.into()), CleanupMode::NoEmpty); let result = state.apply(&info, &engine, &t, true).unwrap(); let expected_trace = vec![FlatTrace { trace_address: Default::default(), @@ -1379,11 +1401,11 @@ fn should_trace_failed_subcall_transaction() { action: Action::Call(0xa.into()), value: 100.into(), data: vec![],//600480600b6000396000f35b600056 - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); state.init_code(&0xa.into(), FromHex::from_hex("60006000600060006000600b602b5a03f1").unwrap()); state.init_code(&0xb.into(), FromHex::from_hex("5b600056").unwrap()); - state.add_balance(t.sender().as_ref().unwrap(), &(100.into())); + state.add_balance(t.sender().as_ref().unwrap(), &(100.into()), CleanupMode::NoEmpty); let result = state.apply(&info, &engine, &t, true).unwrap(); let expected_trace = vec![FlatTrace { trace_address: Default::default(), @@ -1435,12 +1457,12 @@ fn should_trace_call_with_subcall_with_subcall_transaction() { action: Action::Call(0xa.into()), value: 100.into(), data: vec![], - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); state.init_code(&0xa.into(), FromHex::from_hex("60006000600060006000600b602b5a03f1").unwrap()); state.init_code(&0xb.into(), FromHex::from_hex("60006000600060006000600c602b5a03f1").unwrap()); state.init_code(&0xc.into(), FromHex::from_hex("6000").unwrap()); - state.add_balance(t.sender().as_ref().unwrap(), &(100.into())); + state.add_balance(t.sender().as_ref().unwrap(), &(100.into()), CleanupMode::NoEmpty); let result = state.apply(&info, &engine, &t, true).unwrap(); let expected_trace = vec![FlatTrace { trace_address: Default::default(), @@ -1510,12 +1532,12 @@ fn should_trace_failed_subcall_with_subcall_transaction() { action: Action::Call(0xa.into()), value: 100.into(), data: vec![],//600480600b6000396000f35b600056 - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); state.init_code(&0xa.into(), FromHex::from_hex("60006000600060006000600b602b5a03f1").unwrap()); state.init_code(&0xb.into(), FromHex::from_hex("60006000600060006000600c602b5a03f1505b601256").unwrap()); state.init_code(&0xc.into(), FromHex::from_hex("6000").unwrap()); - state.add_balance(t.sender().as_ref().unwrap(), &(100.into())); + state.add_balance(t.sender().as_ref().unwrap(), &(100.into()), CleanupMode::NoEmpty); let result = state.apply(&info, &engine, &t, true).unwrap(); let expected_trace = vec![FlatTrace { @@ -1583,11 +1605,11 @@ fn should_trace_suicide() { action: Action::Call(0xa.into()), value: 100.into(), data: vec![], - }.sign(&"".sha3()); + }.sign(&"".sha3(), None); state.init_code(&0xa.into(), FromHex::from_hex("73000000000000000000000000000000000000000bff").unwrap()); - state.add_balance(&0xa.into(), &50.into()); - state.add_balance(t.sender().as_ref().unwrap(), &100.into()); + state.add_balance(&0xa.into(), &50.into(), CleanupMode::NoEmpty); + state.add_balance(t.sender().as_ref().unwrap(), &100.into(), CleanupMode::NoEmpty); let result = state.apply(&info, &engine, &t, true).unwrap(); let expected_trace = vec![FlatTrace { trace_address: Default::default(), @@ -1658,7 +1680,7 @@ fn get_from_database() { let (root, db) = { let mut state = get_temp_state_in(temp.as_path()); state.inc_nonce(&a); - state.add_balance(&a, &U256::from(69u64)); + state.add_balance(&a, &U256::from(69u64), CleanupMode::NoEmpty); state.commit().unwrap(); assert_eq!(state.balance(&a), U256::from(69u64)); state.drop() @@ -1675,27 +1697,47 @@ fn remove() { let mut state_result = get_temp_state(); let mut state = state_result.reference_mut(); assert_eq!(state.exists(&a), false); + assert_eq!(state.exists_and_not_null(&a), false); state.inc_nonce(&a); assert_eq!(state.exists(&a), true); + assert_eq!(state.exists_and_not_null(&a), true); assert_eq!(state.nonce(&a), U256::from(1u64)); state.kill_account(&a); assert_eq!(state.exists(&a), false); + assert_eq!(state.exists_and_not_null(&a), false); assert_eq!(state.nonce(&a), U256::from(0u64)); } #[test] -fn empty_account_exists() { +fn empty_account_is_not_created() { let a = Address::zero(); let path = RandomTempPath::new(); let db = get_temp_state_db_in(path.as_path()); let (root, db) = { let mut state = State::new(db, U256::from(0), Default::default()); - state.add_balance(&a, &U256::default()); // create an empty account + state.add_balance(&a, &U256::default(), CleanupMode::NoEmpty); // create an empty account + state.commit().unwrap(); + state.drop() + }; + let state = State::from_existing(db, root, U256::from(0u8), Default::default()).unwrap(); + assert!(!state.exists(&a)); + assert!(!state.exists_and_not_null(&a)); +} + +#[test] +fn empty_account_exists_when_creation_forced() { + let a = Address::zero(); + let path = RandomTempPath::new(); + let db = get_temp_state_db_in(path.as_path()); + let (root, db) = { + let mut state = State::new(db, U256::from(0), Default::default()); + state.add_balance(&a, &U256::default(), CleanupMode::ForceCreate); // create an empty account state.commit().unwrap(); state.drop() }; let state = State::from_existing(db, root, U256::from(0u8), Default::default()).unwrap(); assert!(state.exists(&a)); + assert!(!state.exists_and_not_null(&a)); } #[test] @@ -1733,7 +1775,7 @@ fn alter_balance() { let mut state = state_result.reference_mut(); let a = Address::zero(); let b = 1u64.into(); - state.add_balance(&a, &U256::from(69u64)); + state.add_balance(&a, &U256::from(69u64), CleanupMode::NoEmpty); assert_eq!(state.balance(&a), U256::from(69u64)); state.commit().unwrap(); assert_eq!(state.balance(&a), U256::from(69u64)); @@ -1741,7 +1783,7 @@ fn alter_balance() { assert_eq!(state.balance(&a), U256::from(27u64)); state.commit().unwrap(); assert_eq!(state.balance(&a), U256::from(27u64)); - state.transfer_balance(&a, &b, &U256::from(18u64)); + state.transfer_balance(&a, &b, &U256::from(18u64), CleanupMode::NoEmpty); assert_eq!(state.balance(&a), U256::from(9u64)); assert_eq!(state.balance(&b), U256::from(18u64)); state.commit().unwrap(); @@ -1794,12 +1836,12 @@ fn checkpoint_basic() { let mut state = state_result.reference_mut(); let a = Address::zero(); state.checkpoint(); - state.add_balance(&a, &U256::from(69u64)); + state.add_balance(&a, &U256::from(69u64), CleanupMode::NoEmpty); assert_eq!(state.balance(&a), U256::from(69u64)); state.discard_checkpoint(); assert_eq!(state.balance(&a), U256::from(69u64)); state.checkpoint(); - state.add_balance(&a, &U256::from(1u64)); + state.add_balance(&a, &U256::from(1u64), CleanupMode::NoEmpty); assert_eq!(state.balance(&a), U256::from(70u64)); state.revert_to_checkpoint(); assert_eq!(state.balance(&a), U256::from(69u64)); @@ -1812,7 +1854,7 @@ fn checkpoint_nested() { let a = Address::zero(); state.checkpoint(); state.checkpoint(); - state.add_balance(&a, &U256::from(69u64)); + state.add_balance(&a, &U256::from(69u64), CleanupMode::NoEmpty); assert_eq!(state.balance(&a), U256::from(69u64)); state.discard_checkpoint(); assert_eq!(state.balance(&a), U256::from(69u64)); @@ -1835,7 +1877,7 @@ fn should_not_panic_on_state_diff_with_storage() { let a: Address = 0xa.into(); state.init_code(&a, b"abcdefg".to_vec()); - state.add_balance(&a, &256.into()); + state.add_balance(&a, &256.into(), CleanupMode::NoEmpty); state.set_storage(&a, 0xb.into(), 0xc.into()); let mut new_state = state.clone(); diff --git a/ethcore/src/state/substate.rs b/ethcore/src/state/substate.rs index de703f369..853b0e422 100644 --- a/ethcore/src/state/substate.rs +++ b/ethcore/src/state/substate.rs @@ -18,6 +18,8 @@ use std::collections::HashSet; use util::{Address, U256}; use log_entry::LogEntry; +use evm::Schedule; +use super::CleanupMode; /// State changes which should be applied in finalize, /// after transaction is fully executed. @@ -26,6 +28,9 @@ pub struct Substate { /// Any accounts that have suicided. pub suicides: HashSet
, + /// Any accounts that are tagged for garbage collection. + pub garbage: HashSet
, + /// Any logs. pub logs: Vec, @@ -45,10 +50,20 @@ impl Substate { /// Merge secondary substate `s` into self, accruing each element correspondingly. pub fn accrue(&mut self, s: Substate) { self.suicides.extend(s.suicides.into_iter()); + self.garbage.extend(s.garbage.into_iter()); self.logs.extend(s.logs.into_iter()); self.sstore_clears_count = self.sstore_clears_count + s.sstore_clears_count; self.contracts_created.extend(s.contracts_created.into_iter()); } + + /// Get the cleanup mode object from this. + pub fn to_cleanup_mode(&mut self, schedule: &Schedule) -> CleanupMode { + match (schedule.no_empty, schedule.kill_empty) { + (false, _) => CleanupMode::ForceCreate, + (true, false) => CleanupMode::NoEmpty, + (true, true) => CleanupMode::KillEmpty(&mut self.garbage), + } + } } #[cfg(test)] diff --git a/ethcore/src/state_db.rs b/ethcore/src/state_db.rs index 3506b8951..3a3595a35 100644 --- a/ethcore/src/state_db.rs +++ b/ethcore/src/state_db.rs @@ -165,13 +165,13 @@ impl StateDB { bloom } - pub fn check_account_bloom(&self, address: &Address) -> bool { + pub fn check_non_null_bloom(&self, address: &Address) -> bool { trace!(target: "account_bloom", "Check account bloom: {:?}", address); let bloom = self.account_bloom.lock(); bloom.check(&*address.sha3()) } - pub fn note_account_bloom(&self, address: &Address) { + pub fn note_non_null_account(&self, address: &Address) { trace!(target: "account_bloom", "Note account bloom: {:?}", address); let mut bloom = self.account_bloom.lock(); bloom.set(&*address.sha3()); diff --git a/ethcore/src/tests/client.rs b/ethcore/src/tests/client.rs index 3a24ccf21..99b251d66 100644 --- a/ethcore/src/tests/client.rs +++ b/ethcore/src/tests/client.rs @@ -16,6 +16,7 @@ use io::IoChannel; use client::{BlockChainClient, MiningBlockChainClient, Client, ClientConfig, BlockID}; +use state::CleanupMode; use ethereum; use block::IsBlock; use tests::helpers::*; @@ -217,7 +218,7 @@ fn can_generate_gas_price_histogram() { let client = client_result.reference(); let hist = client.gas_price_histogram(20, 5).unwrap(); - let correct_hist = Histogram { bucket_bounds: vec_into![643,2293,3943,5593,7243,8893], counts: vec![4,2,4,6,3] }; + let correct_hist = Histogram { bucket_bounds: vec_into![643, 2294, 3945, 5596, 7247, 8898], counts: vec![4,2,4,6,4] }; assert_eq!(hist, correct_hist); } @@ -272,7 +273,7 @@ fn change_history_size() { let client = Client::new(ClientConfig::default(), &test_spec, dir.as_path(), Arc::new(Miner::with_spec(&test_spec)), IoChannel::disconnected(), &db_config).unwrap(); for _ in 0..20 { let mut b = client.prepare_open_block(Address::default(), (3141562.into(), 31415620.into()), vec![]); - b.block_mut().fields_mut().state.add_balance(&address, &5.into()); + b.block_mut().fields_mut().state.add_balance(&address, &5.into(), CleanupMode::NoEmpty); b.block_mut().fields_mut().state.commit().unwrap(); let b = b.close_and_lock().seal(&*test_spec.engine, vec![]).unwrap(); client.import_sealed_block(b).unwrap(); // account change is in the journal overlay diff --git a/ethcore/src/tests/helpers.rs b/ethcore/src/tests/helpers.rs index 7b952b30c..96d5f8366 100644 --- a/ethcore/src/tests/helpers.rs +++ b/ethcore/src/tests/helpers.rs @@ -28,6 +28,7 @@ use evm::Schedule; use engines::Engine; use env_info::EnvInfo; use ethereum; +use ethereum::ethash::EthashParams; use devtools::*; use miner::Miner; use header::Header; @@ -40,6 +41,7 @@ pub enum ChainEra { Frontier, Homestead, Eip150, + Eip161, TransitionTest, } @@ -194,7 +196,7 @@ pub fn generate_dummy_client_with_spec_and_data(get_test_spec: F, block_numbe action: Action::Create, data: vec![], value: U256::zero(), - }.sign(kp.secret()), None).unwrap(); + }.sign(kp.secret(), None), None).unwrap(); n += 1; } @@ -420,3 +422,29 @@ pub fn get_bad_state_dummy_block() -> Bytes { create_test_block(&block_header) } + +pub fn get_default_ethash_params() -> EthashParams{ + EthashParams { + gas_limit_bound_divisor: U256::from(1024), + minimum_difficulty: U256::from(131072), + difficulty_bound_divisor: U256::from(2048), + difficulty_increment_divisor: 10, + duration_limit: 13, + block_reward: U256::from(0), + registrar: "0000000000000000000000000000000000000001".into(), + homestead_transition: 1150000, + dao_hardfork_transition: 0x7fffffffffffffff, + dao_hardfork_beneficiary: "0000000000000000000000000000000000000001".into(), + dao_hardfork_accounts: vec![], + difficulty_hardfork_transition: 0x7fffffffffffffff, + difficulty_hardfork_bound_divisor: U256::from(0), + bomb_defuse_transition: 0x7fffffffffffffff, + eip150_transition: 0x7fffffffffffffff, + eip155_transition: 0x7fffffffffffffff, + eip160_transition: 0x7fffffffffffffff, + eip161abc_transition: 0x7fffffffffffffff, + eip161d_transition: 0x7fffffffffffffff, + ecip1010_pause_transition: 0x7fffffffffffffff, + ecip1010_continue_transition: 0x7fffffffffffffff + } +} diff --git a/ethcore/src/types/ids.rs b/ethcore/src/types/ids.rs index d248a45bc..1fe81f392 100644 --- a/ethcore/src/types/ids.rs +++ b/ethcore/src/types/ids.rs @@ -55,7 +55,7 @@ pub struct TraceId { } /// Uniquely identifies Uncle. -#[derive(Debug, Binary)] +#[derive(Debug, PartialEq, Eq, Copy, Clone, Binary)] pub struct UncleID { /// Block id. pub block: BlockID, diff --git a/ethcore/src/types/mode.rs b/ethcore/src/types/mode.rs index b48a92a89..58f652c6c 100644 --- a/ethcore/src/types/mode.rs +++ b/ethcore/src/types/mode.rs @@ -20,7 +20,7 @@ pub use std::time::Duration; use client::Mode as ClientMode; /// IPC-capable shadow-type for client::config::Mode -#[derive(Clone, Binary)] +#[derive(Clone, Binary, Debug)] pub enum Mode { /// Same as ClientMode::Off. Off, diff --git a/ethcore/src/types/receipt.rs b/ethcore/src/types/receipt.rs index 52e6747e8..deefeb383 100644 --- a/ethcore/src/types/receipt.rs +++ b/ethcore/src/types/receipt.rs @@ -93,6 +93,10 @@ pub struct RichReceipt { pub contract_address: Option
, /// Logs pub logs: Vec, + /// Logs bloom + pub log_bloom: LogBloom, + /// State root + pub state_root: H256, } /// Receipt with additional info. @@ -114,6 +118,10 @@ pub struct LocalizedReceipt { pub contract_address: Option
, /// Logs pub logs: Vec, + /// Logs bloom + pub log_bloom: LogBloom, + /// State root + pub state_root: H256, } #[test] diff --git a/ethcore/src/types/transaction.rs b/ethcore/src/types/transaction.rs index 247a1b301..8289c5864 100644 --- a/ethcore/src/types/transaction.rs +++ b/ethcore/src/types/transaction.rs @@ -72,8 +72,8 @@ pub struct Transaction { impl Transaction { /// Append object with a without signature into RLP stream - pub fn rlp_append_unsigned_transaction(&self, s: &mut RlpStream) { - s.begin_list(6); + pub fn rlp_append_unsigned_transaction(&self, s: &mut RlpStream, network_id: Option) { + s.begin_list(if let None = network_id { 6 } else { 9 }); s.append(&self.nonce); s.append(&self.gas_price); s.append(&self.gas); @@ -83,6 +83,11 @@ impl Transaction { }; s.append(&self.value); s.append(&self.data); + if let Some(n) = network_id { + s.append(&n); + s.append(&0u8); + s.append(&0u8); + } } } @@ -105,7 +110,7 @@ impl From for SignedTransaction { }, value: t.value.into(), data: t.data.into(), - }.sign(&t.secret.into()) + }.sign(&t.secret.into(), None) } } @@ -135,26 +140,26 @@ impl From for SignedTransaction { impl Transaction { /// The message hash of the transaction. - pub fn hash(&self) -> H256 { + pub fn hash(&self, network_id: Option) -> H256 { let mut stream = RlpStream::new(); - self.rlp_append_unsigned_transaction(&mut stream); + self.rlp_append_unsigned_transaction(&mut stream, network_id); stream.out().sha3() } /// Signs the transaction as coming from `sender`. - pub fn sign(self, secret: &Secret) -> SignedTransaction { - let sig = ::ethkey::sign(secret, &self.hash()) + pub fn sign(self, secret: &Secret, network_id: Option) -> SignedTransaction { + let sig = ::ethkey::sign(secret, &self.hash(network_id)) .expect("data is valid and context has signing capabilities; qed"); - self.with_signature(sig) + self.with_signature(sig, network_id) } /// Signs the transaction with signature. - pub fn with_signature(self, sig: Signature) -> SignedTransaction { + pub fn with_signature(self, sig: Signature, network_id: Option) -> SignedTransaction { SignedTransaction { unsigned: self, r: sig.r().into(), s: sig.s().into(), - v: sig.v() + 27, + v: sig.v() + if let Some(n) = network_id { 35 + n * 2 } else { 27 }, hash: Cell::new(None), sender: Cell::new(None), } @@ -204,7 +209,8 @@ impl Transaction { pub struct SignedTransaction { /// Plain Transaction. unsigned: Transaction, - /// The V field of the signature, either 27 or 28; helps describe the point on the curve. + /// The V field of the signature; the LS bit described which half of the curve our point falls + /// in. The MS bits describe which network this transaction is for. If 27/28, its for all networks. v: u8, /// The R field of the signature; helps describe the point on the curve. r: U256, @@ -266,7 +272,7 @@ impl HeapSizeOf for SignedTransaction { impl SignedTransaction { /// Append object with a signature into RLP stream - pub fn rlp_append_sealed_transaction(&self, s: &mut RlpStream) { + fn rlp_append_sealed_transaction(&self, s: &mut RlpStream) { s.begin_list(9); s.append(&self.nonce); s.append(&self.gas_price); @@ -295,8 +301,16 @@ impl SignedTransaction { } } - /// 0 is `v` is 27, 1 if 28, and 4 otherwise. - pub fn standard_v(&self) -> u8 { match self.v { 27 => 0, 28 => 1, _ => 4 } } + /// 0 if `v` would have been 27 under "Electrum" notation, 1 if 28 or 4 if invalid. + pub fn standard_v(&self) -> u8 { match self.v { v if v == 27 || v == 28 || v > 36 => (v - 1) % 2, _ => 4 } } + + /// The network ID, or `None` if this is a global transaction. + pub fn network_id(&self) -> Option { + match self.v { + v if v > 36 => Some((v - 35) / 2), + _ => None, + } + } /// Construct a signature object from the sig. pub fn signature(&self) -> Signature { @@ -327,20 +341,25 @@ impl SignedTransaction { /// Returns the public key of the sender. pub fn public_key(&self) -> Result { - Ok(try!(recover(&self.signature(), &self.unsigned.hash()))) + Ok(try!(recover(&self.signature(), &self.unsigned.hash(self.network_id())))) } /// Do basic validation, checking for valid signature and minimum gas, // TODO: consider use in block validation. #[cfg(test)] #[cfg(feature = "json-tests")] - pub fn validate(self, schedule: &Schedule, require_low: bool) -> Result { + pub fn validate(self, schedule: &Schedule, require_low: bool, allow_network_id_of_one: bool) -> Result { if require_low && !self.signature().is_low_s() { return Err(EthkeyError::InvalidSignature.into()) } + match self.network_id() { + None => {}, + Some(1) if allow_network_id_of_one => {}, + _ => return Err(TransactionError::InvalidNetworkId.into()), + } try!(self.sender()); if self.gas < U256::from(self.gas_required(&schedule)) { - Err(From::from(TransactionError::InvalidGasLimit(::util::OutOfBounds{min: Some(U256::from(self.gas_required(&schedule))), max: None, found: self.gas}))) + Err(TransactionError::InvalidGasLimit(::util::OutOfBounds{min: Some(U256::from(self.gas_required(&schedule))), max: None, found: self.gas}).into()) } else { Ok(self) } @@ -380,6 +399,7 @@ fn sender_test() { } else { panic!(); } assert_eq!(t.value, U256::from(0x0au64)); assert_eq!(t.sender().unwrap(), "0f65fe9276bc9a24ae7083ae28e2660ef72df99e".into()); + assert_eq!(t.network_id(), None); } #[test] @@ -394,8 +414,9 @@ fn signing() { gas: U256::from(50_000), value: U256::from(1), data: b"Hello!".to_vec() - }.sign(&key.secret()); + }.sign(&key.secret(), None); assert_eq!(Address::from(key.public().sha3()), t.sender().unwrap()); + assert_eq!(t.network_id(), None); } #[test] @@ -409,7 +430,48 @@ fn fake_signing() { data: b"Hello!".to_vec() }.fake_sign(Address::from(0x69)); assert_eq!(Address::from(0x69), t.sender().unwrap()); + assert_eq!(t.network_id(), None); let t = t.clone(); assert_eq!(Address::from(0x69), t.sender().unwrap()); + assert_eq!(t.network_id(), None); } + +#[test] +fn should_recover_from_network_specific_signing() { + use ethkey::{Random, Generator}; + let key = Random.generate().unwrap(); + let t = Transaction { + action: Action::Create, + nonce: U256::from(42), + gas_price: U256::from(3000), + gas: U256::from(50_000), + value: U256::from(1), + data: b"Hello!".to_vec() + }.sign(&key.secret(), Some(69)); + assert_eq!(Address::from(key.public().sha3()), t.sender().unwrap()); + assert_eq!(t.network_id(), Some(69)); +} + +#[test] +fn should_agree_with_vitalik() { + use rustc_serialize::hex::FromHex; + + let test_vector = |tx_data: &str, address: &'static str| { + let signed: SignedTransaction = decode(&FromHex::from_hex(tx_data).unwrap()); + signed.check_low_s().unwrap(); + assert_eq!(signed.sender().unwrap(), address.into()); + flushln!("networkid: {:?}", signed.network_id()); + }; + + test_vector("f864808504a817c800825208943535353535353535353535353535353535353535808025a0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116da0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116d", "0xf0f6f18bca1b28cd68e4357452947e021241e9ce") + test_vector("f864018504a817c80182a410943535353535353535353535353535353535353535018025a0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bcaa0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6", "0x23ef145a395ea3fa3deb533b8a9e1b4c6c25d112") + test_vector("f864028504a817c80282f618943535353535353535353535353535353535353535088025a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5", "0x2e485e0c23b4c3c542628a5f672eeab0ad4888be") + test_vector("f865038504a817c803830148209435353535353535353535353535353535353535351b8025a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4e0a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4de", "0x82a88539669a3fd524d669e858935de5e5410cf0") + test_vector("f865048504a817c80483019a28943535353535353535353535353535353535353535408025a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c063a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c060", "0xf9358f2538fd5ccfeb848b64a96b743fcc930554") + test_vector("f865058504a817c8058301ec309435353535353535353535353535353535353535357d8025a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", "0xa8f7aba377317440bc5b26198a363ad22af1f3a4") + test_vector("f866068504a817c80683023e3894353535353535353535353535353535353535353581d88025a06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2fa06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2d", "0xf1f571dc362a0e5b2696b8e775f8491d3e50de35") + test_vector("f867078504a817c807830290409435353535353535353535353535353535353535358201578025a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021", "0xd37922162ab7cea97c97a87551ed02c9a38b7332") + test_vector("f867088504a817c8088302e2489435353535353535353535353535353535353535358202008025a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", "0x9bddad43f934d313c2b79ca28a432dd2b7281029") + test_vector("f867098504a817c809830334509435353535353535353535353535353535353535358202d98025a052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afba052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", "0x3c24d7329e92f84f08556ceb6df1cdb0104ca49f") +} \ No newline at end of file diff --git a/ethcore/src/verification/verification.rs b/ethcore/src/verification/verification.rs index 4ebd8aebd..47b2e16de 100644 --- a/ethcore/src/verification/verification.rs +++ b/ethcore/src/verification/verification.rs @@ -395,7 +395,7 @@ mod tests { gas: U256::from(30_000), gas_price: U256::from(40_000), nonce: U256::one() - }.sign(keypair.secret()); + }.sign(keypair.secret(), None); let tr2 = Transaction { action: Action::Create, @@ -404,7 +404,7 @@ mod tests { gas: U256::from(30_000), gas_price: U256::from(40_000), nonce: U256::from(2) - }.sign(keypair.secret()); + }.sign(keypair.secret(), None); let good_transactions = [ tr1.clone(), tr2.clone() ]; diff --git a/evmbin/src/ext.rs b/evmbin/src/ext.rs index 11fb3a876..cac89d76c 100644 --- a/evmbin/src/ext.rs +++ b/evmbin/src/ext.rs @@ -51,6 +51,14 @@ impl Ext for FakeExt { unimplemented!(); } + fn exists_and_not_null(&self, address: &Address) -> bool { + unimplemented!(); + } + + fn origin_balance(&self) -> U256 { + unimplemented!(); + } + fn balance(&self, _address: &Address) -> U256 { unimplemented!(); } diff --git a/js/assets/images/dapps/coins-64x64.jpg b/js/assets/images/dapps/coins-64x64.jpg deleted file mode 100644 index 987d7400e..000000000 Binary files a/js/assets/images/dapps/coins-64x64.jpg and /dev/null differ diff --git a/js/assets/images/dapps/coins.jpg b/js/assets/images/dapps/coins.jpg deleted file mode 100644 index 8fba5e65c..000000000 Binary files a/js/assets/images/dapps/coins.jpg and /dev/null differ diff --git a/js/assets/images/dapps/hex-64x64.jpg b/js/assets/images/dapps/hex-64x64.jpg deleted file mode 100644 index 8c6a1d5cc..000000000 Binary files a/js/assets/images/dapps/hex-64x64.jpg and /dev/null differ diff --git a/js/assets/images/dapps/hex.jpg b/js/assets/images/dapps/hex.jpg deleted file mode 100644 index 8e09f49aa..000000000 Binary files a/js/assets/images/dapps/hex.jpg and /dev/null differ diff --git a/js/assets/images/dapps/interlock-64x64.png b/js/assets/images/dapps/interlock-64x64.png deleted file mode 100644 index f4b342489..000000000 Binary files a/js/assets/images/dapps/interlock-64x64.png and /dev/null differ diff --git a/js/assets/images/dapps/interlock.png b/js/assets/images/dapps/interlock.png deleted file mode 100644 index e8aeb275d..000000000 Binary files a/js/assets/images/dapps/interlock.png and /dev/null differ diff --git a/js/assets/images/dapps/link-64x64.jpg b/js/assets/images/dapps/link-64x64.jpg deleted file mode 100644 index 14f9c1190..000000000 Binary files a/js/assets/images/dapps/link-64x64.jpg and /dev/null differ diff --git a/js/assets/images/dapps/link.jpg b/js/assets/images/dapps/link.jpg deleted file mode 100644 index 546c67e20..000000000 Binary files a/js/assets/images/dapps/link.jpg and /dev/null differ diff --git a/js/assets/images/dapps/register-64x64.jpg b/js/assets/images/dapps/register-64x64.jpg deleted file mode 100644 index ff8fc6c2f..000000000 Binary files a/js/assets/images/dapps/register-64x64.jpg and /dev/null differ diff --git a/js/assets/images/dapps/register.jpg b/js/assets/images/dapps/register.jpg deleted file mode 100644 index cd47bd81e..000000000 Binary files a/js/assets/images/dapps/register.jpg and /dev/null differ diff --git a/js/build-server.js b/js/build-server.js index 9153f5ed2..f8c0eb828 100644 --- a/js/build-server.js +++ b/js/build-server.js @@ -13,6 +13,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . +// test only /** * Run `PARITY_URL="127.0.0.1:8180" NODE_ENV="production" npm run build` diff --git a/js/package.json b/js/package.json index 0ff75b720..f2a004140 100644 --- a/js/package.json +++ b/js/package.json @@ -1,11 +1,13 @@ { "name": "parity.js", - "version": "0.1.35", + "version": "0.2.19", "main": "release/index.js", "jsnext:main": "src/index.js", "author": "Parity Team ", "maintainers": [ - "Jaco Greeff" + "Jaco Greeff", + "Nicolas Gotchac", + "Jannis Redmann" ], "contributors": [], "license": "GPL-3.0", @@ -23,16 +25,16 @@ "Promise" ], "scripts": { - "build": "npm run build:dll && npm run build:app && npm run build:lib", + "build": "npm run build:lib && npm run build:dll && npm run build:app", "build:app": "webpack --progress", "build:lib": "webpack --config webpack.libraries --progress", "build:dll": "webpack --config webpack.vendor --progress", - "ci:build": "npm run ci:build:dll && npm run ci:build:app && npm run ci:build:lib", + "ci:build": "npm run ci:build:lib && npm run ci:build:dll && npm run ci:build:app", "ci:build:app": "NODE_ENV=production webpack", "ci:build:lib": "NODE_ENV=production webpack --config webpack.libraries", "ci:build:dll": "NODE_ENV=production webpack --config webpack.vendor", "ci:build:npm": "NODE_ENV=production webpack --config webpack.npm", - "start": "npm install && npm run build:dll && npm run start:app", + "start": "npm install && npm run build:lib && npm run build:dll && npm run start:app", "start:app": "webpack-dev-server -d --history-api-fallback --open --hot --inline --progress --colors --port 3000", "clean": "rm -rf ./build ./coverage", "coveralls": "npm run testCoverage && coveralls < coverage/lcov.info", @@ -44,7 +46,7 @@ "devDependencies": { "babel-cli": "^6.10.1", "babel-core": "^6.10.4", - "babel-eslint": "^6.1.2", + "babel-eslint": "^7.1.0", "babel-loader": "^6.2.3", "babel-plugin-lodash": "^3.2.2", "babel-plugin-transform-class-properties": "^6.11.5", @@ -126,6 +128,9 @@ "marked": "^0.3.6", "material-ui": "^0.16.1", "material-ui-chip-input": "^0.8.0", + "mobx": "^2.6.1", + "mobx-react": "^3.5.8", + "mobx-react-devtools": "^4.2.9", "moment": "^2.14.1", "qs": "^6.3.0", "react": "^15.2.1", diff --git a/js/scripts/release.sh b/js/scripts/release.sh index 22fd91ab6..fd95e00b8 100755 --- a/js/scripts/release.sh +++ b/js/scripts/release.sh @@ -50,32 +50,32 @@ setup_git_user git remote set-url origin $GIT_PARITY git reset --hard origin/$BRANCH 2>$GITLOG -echo "*** Bumping package.json patch version" -cd js -npm --no-git-tag-version version -npm version patch -cd .. +if [ "$BRANCH" == "master" ]; then + cd js + echo "*** Bumping package.json patch version" + npm --no-git-tag-version version + npm version patch + + echo "*** Building packages for npmjs" + # echo -e "$NPM_USERNAME\n$NPM_PASSWORD\n$NPM_EMAIL" | npm login + echo "$NPM_TOKEN" >> ~/.npmrc + npm run ci:build:npm + + echo "*** Publishing $PACKAGE to npmjs" + cd .npmjs + npm publish --access public + cd ../.. +fi echo "*** Updating cargo parity-ui-precompiled#$PRECOMPILED_HASH" cargo update -p parity-ui-precompiled # --precise "$PRECOMPILED_HASH" echo "*** Committing updated files" -git add Cargo.lock js/package.json +git add . git commit -m "[ci skip] js-precompiled $UTCDATE" git push origin HEAD:refs/heads/$BRANCH 2>$GITLOG -echo "*** Building packages for npmjs" -cd js -# echo -e "$NPM_USERNAME\n$NPM_PASSWORD\n$NPM_EMAIL" | npm login -echo "$NPM_TOKEN" >> ~/.npmrc -npm run ci:build:npm - -echo "*** Publishing $PACKAGE to npmjs" -cd .npmjs -npm publish --access public -cd .. - # back to root echo "*** Release completed" popd diff --git a/js/src/api/README.md b/js/src/api/README.md index 691a24cca..e28c6c2a1 100644 --- a/js/src/api/README.md +++ b/js/src/api/README.md @@ -135,10 +135,11 @@ APIs implement the calls as exposed in the [Ethcore JSON Ethereum RPC](https://g - [ethapi.db](https://github.com/ethcore/ethereum-rpc-json/blob/master/interfaces.md#db) - [ethapi.eth](https://github.com/ethcore/ethereum-rpc-json/blob/master/interfaces.md#eth) -- [ethapi.ethcore](https://github.com/ethcore/ethereum-rpc-json/blob/master/interfaces.md#ethcore) +- [ethapi.parity](https://github.com/ethcore/ethereum-rpc-json/blob/master/interfaces.md#parity) - [ethapi.net](https://github.com/ethcore/ethereum-rpc-json/blob/master/interfaces.md#net) - [ethapi.personal](https://github.com/ethcore/ethereum-rpc-json/blob/master/interfaces.md#personal) - [ethapi.shh](https://github.com/ethcore/ethereum-rpc-json/blob/master/interfaces.md#shh) +- [ethapi.signer](https://github.com/ethcore/ethereum-rpc-json/blob/master/interfaces.md#signer) - [ethapi.trace](https://github.com/ethcore/ethereum-rpc-json/blob/master/interfaces.md#trace) - [ethapi.web3](https://github.com/ethcore/ethereum-rpc-json/blob/master/interfaces.md#web3) diff --git a/js/src/api/api.js b/js/src/api/api.js index 9768b9acb..75d4392d0 100644 --- a/js/src/api/api.js +++ b/js/src/api/api.js @@ -17,7 +17,7 @@ import { Http, Ws } from './transport'; import Contract from './contract'; -import { Db, Eth, Ethcore, Net, Personal, Shh, Trace, Web3 } from './rpc'; +import { Db, Eth, Parity, Net, Personal, Shh, Signer, Trace, Web3 } from './rpc'; import Subscriptions from './subscriptions'; import util from './util'; import { isFunction } from './util/types'; @@ -32,10 +32,11 @@ export default class Api { this._db = new Db(transport); this._eth = new Eth(transport); - this._ethcore = new Ethcore(transport); this._net = new Net(transport); + this._parity = new Parity(transport); this._personal = new Personal(transport); this._shh = new Shh(transport); + this._signer = new Signer(transport); this._trace = new Trace(transport); this._web3 = new Web3(transport); @@ -50,8 +51,8 @@ export default class Api { return this._eth; } - get ethcore () { - return this._ethcore; + get parity () { + return this._parity; } get net () { @@ -66,6 +67,10 @@ export default class Api { return this._shh; } + get signer () { + return this._signer; + } + get trace () { return this._trace; } diff --git a/js/src/api/contract/contract.js b/js/src/api/contract/contract.js index cef75eda7..bb6c15d8d 100644 --- a/js/src/api/contract/contract.js +++ b/js/src/api/contract/contract.js @@ -102,7 +102,7 @@ export default class Contract { options.gas = gas.toFixed(0); setState({ state: 'postTransaction', gas }); - return this._api.eth.postTransaction(this._encodeOptions(this.constructors[0], options, values)); + return this._api.parity.postTransaction(this._encodeOptions(this.constructors[0], options, values)); }) .then((requestId) => { setState({ state: 'checkRequest', requestId }); @@ -166,7 +166,7 @@ export default class Contract { } _pollCheckRequest = (requestId) => { - return this._api.pollMethod('eth_checkRequest', requestId); + return this._api.pollMethod('parity_checkRequest', requestId); } _pollTransactionReceipt = (txhash, gas) => { @@ -208,7 +208,7 @@ export default class Contract { if (!func.constant) { func.postTransaction = (options, values = []) => { - return this._api.eth + return this._api.parity .postTransaction(this._encodeOptions(func, this._addOptionsTo(options), values)); }; diff --git a/js/src/api/contract/contract.spec.js b/js/src/api/contract/contract.spec.js index 0d6169e26..9065b4fad 100644 --- a/js/src/api/contract/contract.spec.js +++ b/js/src/api/contract/contract.spec.js @@ -249,9 +249,9 @@ describe('api/contract/Contract', () => { before(() => { scope = mockHttp([ { method: 'eth_estimateGas', reply: { result: 1000 } }, - { method: 'eth_postTransaction', reply: { result: '0x678' } }, - { method: 'eth_checkRequest', reply: { result: null } }, - { method: 'eth_checkRequest', reply: { result: '0x890' } }, + { method: 'parity_postTransaction', reply: { result: '0x678' } }, + { method: 'parity_checkRequest', reply: { result: null } }, + { method: 'parity_checkRequest', reply: { result: '0x890' } }, { method: 'eth_getTransactionReceipt', reply: { result: null } }, { method: 'eth_getTransactionReceipt', reply: { result: RECEIPT_PEND } }, { method: 'eth_getTransactionReceipt', reply: { result: RECEIPT_DONE } }, @@ -266,7 +266,7 @@ describe('api/contract/Contract', () => { }); it('passes the options through to postTransaction (incl. gas calculation)', () => { - expect(scope.body.eth_postTransaction.params).to.deep.equal([ + expect(scope.body.parity_postTransaction.params).to.deep.equal([ { data: '0x123', gas: '0x4b0' } ]); }); @@ -280,8 +280,8 @@ describe('api/contract/Contract', () => { it('fails when gasUsed == gas', () => { mockHttp([ { method: 'eth_estimateGas', reply: { result: 1000 } }, - { method: 'eth_postTransaction', reply: { result: '0x678' } }, - { method: 'eth_checkRequest', reply: { result: '0x789' } }, + { method: 'parity_postTransaction', reply: { result: '0x678' } }, + { method: 'parity_checkRequest', reply: { result: '0x789' } }, { method: 'eth_getTransactionReceipt', reply: { result: RECEIPT_EXCP } } ]); @@ -295,8 +295,8 @@ describe('api/contract/Contract', () => { it('fails when no code was deployed', () => { mockHttp([ { method: 'eth_estimateGas', reply: { result: 1000 } }, - { method: 'eth_postTransaction', reply: { result: '0x678' } }, - { method: 'eth_checkRequest', reply: { result: '0x789' } }, + { method: 'parity_postTransaction', reply: { result: '0x678' } }, + { method: 'parity_checkRequest', reply: { result: '0x789' } }, { method: 'eth_getTransactionReceipt', reply: { result: RECEIPT_DONE } }, { method: 'eth_getCode', reply: { result: '0x' } } ]); @@ -360,15 +360,15 @@ describe('api/contract/Contract', () => { describe('postTransaction', () => { beforeEach(() => { - scope = mockHttp([{ method: 'eth_postTransaction', reply: { result: ['hashId'] } }]); + scope = mockHttp([{ method: 'parity_postTransaction', reply: { result: ['hashId'] } }]); }); - it('encodes options and mades an eth_postTransaction call', () => { + it('encodes options and mades an parity_postTransaction call', () => { return func .postTransaction({ someExtras: 'foo' }, VALUES) .then(() => { expect(scope.isDone()).to.be.true; - expect(scope.body.eth_postTransaction.params[0]).to.deep.equal({ + expect(scope.body.parity_postTransaction.params[0]).to.deep.equal({ someExtras: 'foo', to: ADDR, data: ENCODED diff --git a/js/src/api/rpc/eth/eth.js b/js/src/api/rpc/eth/eth.js index 703f3ed11..43f8025e1 100644 --- a/js/src/api/rpc/eth/eth.js +++ b/js/src/api/rpc/eth/eth.js @@ -39,11 +39,6 @@ export default class Eth { .execute('eth_call', inOptions(options), inBlockNumber(blockNumber)); } - checkRequest (requestId) { - return this._transport - .execute('eth_checkRequest', inNumber16(requestId)); - } - coinbase () { return this._transport .execute('eth_coinbase') @@ -267,11 +262,6 @@ export default class Eth { .execute('eth_pendingTransactions'); } - postTransaction (options) { - return this._transport - .execute('eth_postTransaction', inOptions(options)); - } - protocolVersion () { return this._transport .execute('eth_protocolVersion'); diff --git a/js/src/api/rpc/ethcore/ethcore.js b/js/src/api/rpc/ethcore/ethcore.js deleted file mode 100644 index 663143f0d..000000000 --- a/js/src/api/rpc/ethcore/ethcore.js +++ /dev/null @@ -1,196 +0,0 @@ -// 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 { inAddress, inData, inNumber16 } from '../../format/input'; -import { outAddress, outHistogram, outNumber, outPeers } from '../../format/output'; - -export default class Ethcore { - constructor (transport) { - this._transport = transport; - } - - acceptNonReservedPeers () { - return this._transport - .execute('ethcore_acceptNonReservedPeers'); - } - - addReservedPeer (encode) { - return this._transport - .execute('ethcore_addReservedPeer', encode); - } - - dappsPort () { - return this._transport - .execute('ethcore_dappsPort') - .then(outNumber); - } - - defaultExtraData () { - return this._transport - .execute('ethcore_defaultExtraData'); - } - - devLogs () { - return this._transport - .execute('ethcore_devLogs'); - } - - devLogsLevels () { - return this._transport - .execute('ethcore_devLogsLevels'); - } - - dropNonReservedPeers () { - return this._transport - .execute('ethcore_dropNonReservedPeers'); - } - - extraData () { - return this._transport - .execute('ethcore_extraData'); - } - - gasFloorTarget () { - return this._transport - .execute('ethcore_gasFloorTarget') - .then(outNumber); - } - - gasPriceHistogram () { - return this._transport - .execute('ethcore_gasPriceHistogram') - .then(outHistogram); - } - - generateSecretPhrase () { - return this._transport - .execute('ethcore_generateSecretPhrase'); - } - - hashContent (url) { - return this._transport - .execute('ethcore_hashContent', url); - } - - minGasPrice () { - return this._transport - .execute('ethcore_minGasPrice') - .then(outNumber); - } - - mode () { - return this._transport - .execute('ethcore_mode'); - } - - netChain () { - return this._transport - .execute('ethcore_netChain'); - } - - netPeers () { - return this._transport - .execute('ethcore_netPeers') - .then(outPeers); - } - - netMaxPeers () { - return this._transport - .execute('ethcore_netMaxPeers') - .then(outNumber); - } - - netPort () { - return this._transport - .execute('ethcore_netPort') - .then(outNumber); - } - - nodeName () { - return this._transport - .execute('ethcore_nodeName'); - } - - phraseToAddress (phrase) { - return this._transport - .execute('ethcore_phraseToAddress', phrase) - .then(outAddress); - } - - registryAddress () { - return this._transport - .execute('ethcore_registryAddress') - .then(outAddress); - } - - removeReservedPeer (encode) { - return this._transport - .execute('ethcore_removeReservedPeer', encode); - } - - rpcSettings () { - return this._transport - .execute('ethcore_rpcSettings'); - } - - setAuthor (address) { - return this._transport - .execute('ethcore_setAuthor', inAddress(address)); - } - - setExtraData (data) { - return this._transport - .execute('ethcore_setExtraData', inData(data)); - } - - setGasFloorTarget (quantity) { - return this._transport - .execute('ethcore_setGasFloorTarget', inNumber16(quantity)); - } - - setMinGasPrice (quantity) { - return this._transport - .execute('ethcore_setMinGasPrice', inNumber16(quantity)); - } - - setMode (mode) { - return this._transport - .execute('ethcore_setMode', mode); - } - - setTransactionsLimit (quantity) { - return this._transport - .execute('ethcore_setTransactionsLimit', inNumber16(quantity)); - } - - signerPort () { - return this._transport - .execute('ethcore_signerPort') - .then(outNumber); - } - - transactionsLimit () { - return this._transport - .execute('ethcore_transactionsLimit') - .then(outNumber); - } - - unsignedTransactionsCount () { - return this._transport - .execute('ethcore_unsignedTransactionsCount') - .then(outNumber); - } -} diff --git a/js/src/api/rpc/index.js b/js/src/api/rpc/index.js index e7e94b9ed..7961da81c 100644 --- a/js/src/api/rpc/index.js +++ b/js/src/api/rpc/index.js @@ -16,9 +16,10 @@ export Db from './db'; export Eth from './eth'; -export Ethcore from './ethcore'; +export Parity from './parity'; export Net from './net'; export Personal from './personal'; export Shh from './shh'; +export Signer from './signer'; export Trace from './trace'; export Web3 from './web3'; diff --git a/js/src/api/rpc/ethcore/index.js b/js/src/api/rpc/parity/index.js similarity index 95% rename from js/src/api/rpc/ethcore/index.js rename to js/src/api/rpc/parity/index.js index 2372a2171..38f08f725 100644 --- a/js/src/api/rpc/ethcore/index.js +++ b/js/src/api/rpc/parity/index.js @@ -14,4 +14,4 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -export default from './ethcore'; +export default from './parity'; diff --git a/js/src/api/rpc/ethcore/ethcore.e2e.js b/js/src/api/rpc/parity/parity.e2e.js similarity index 82% rename from js/src/api/rpc/ethcore/ethcore.e2e.js rename to js/src/api/rpc/parity/parity.e2e.js index aae7108e7..91e01ab6a 100644 --- a/js/src/api/rpc/ethcore/ethcore.e2e.js +++ b/js/src/api/rpc/parity/parity.e2e.js @@ -16,12 +16,12 @@ import { createHttpApi } from '../../../../test/e2e/ethapi'; -describe('ethapi.ethcore', () => { +describe('ethapi.parity', () => { const ethapi = createHttpApi(); describe('gasFloorTarget', () => { it('returns and translates the target', () => { - return ethapi.ethcore.gasFloorTarget().then((value) => { + return ethapi.parity.gasFloorTarget().then((value) => { expect(value.gt(0)).to.be.true; }); }); @@ -29,7 +29,7 @@ describe('ethapi.ethcore', () => { describe('gasPriceHistogram', () => { it('returns and translates the target', () => { - return ethapi.ethcore.gasPriceHistogram().then((result) => { + return ethapi.parity.gasPriceHistogram().then((result) => { expect(Object.keys(result)).to.deep.equal(['bucketBounds', 'counts']); expect(result.bucketBounds.length > 0).to.be.true; expect(result.counts.length > 0).to.be.true; @@ -39,7 +39,7 @@ describe('ethapi.ethcore', () => { describe('netChain', () => { it('returns and the chain', () => { - return ethapi.ethcore.netChain().then((value) => { + return ethapi.parity.netChain().then((value) => { expect(value).to.equal('morden'); }); }); @@ -47,7 +47,7 @@ describe('ethapi.ethcore', () => { describe('netPort', () => { it('returns and translates the port', () => { - return ethapi.ethcore.netPort().then((value) => { + return ethapi.parity.netPort().then((value) => { expect(value.gt(0)).to.be.true; }); }); @@ -55,7 +55,7 @@ describe('ethapi.ethcore', () => { describe('transactionsLimit', () => { it('returns and translates the limit', () => { - return ethapi.ethcore.transactionsLimit().then((value) => { + return ethapi.parity.transactionsLimit().then((value) => { expect(value.gt(0)).to.be.true; }); }); @@ -63,7 +63,7 @@ describe('ethapi.ethcore', () => { describe('rpcSettings', () => { it('returns and translates the settings', () => { - return ethapi.ethcore.rpcSettings().then((value) => { + return ethapi.parity.rpcSettings().then((value) => { expect(value).to.be.ok; }); }); diff --git a/js/src/api/rpc/parity/parity.js b/js/src/api/rpc/parity/parity.js new file mode 100644 index 000000000..f1739f848 --- /dev/null +++ b/js/src/api/rpc/parity/parity.js @@ -0,0 +1,273 @@ +// 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 { inAddress, inData, inHex, inNumber16, inOptions } from '../../format/input'; +import { outAccountInfo, outAddress, outHistogram, outNumber, outPeers } from '../../format/output'; + +export default class Parity { + constructor (transport) { + this._transport = transport; + } + + acceptNonReservedPeers () { + return this._transport + .execute('parity_acceptNonReservedPeers'); + } + + accounts () { + return this._transport + .execute('parity_accounts') + .then(outAccountInfo); + } + + accountsInfo () { + return this._transport + .execute('parity_accountsInfo') + .then(outAccountInfo); + } + + addReservedPeer (encode) { + return this._transport + .execute('parity_addReservedPeer', encode); + } + + changePassword (account, password, newPassword) { + return this._transport + .execute('parity_changePassword', inAddress(account), password, newPassword); + } + + checkRequest (requestId) { + return this._transport + .execute('parity_checkRequest', inNumber16(requestId)); + } + + dappsPort () { + return this._transport + .execute('parity_dappsPort') + .then(outNumber); + } + + defaultExtraData () { + return this._transport + .execute('parity_defaultExtraData'); + } + + devLogs () { + return this._transport + .execute('parity_devLogs'); + } + + devLogsLevels () { + return this._transport + .execute('parity_devLogsLevels'); + } + + dropNonReservedPeers () { + return this._transport + .execute('parity_dropNonReservedPeers'); + } + + enode () { + return this._transport + .execute('parity_enode'); + } + + extraData () { + return this._transport + .execute('parity_extraData'); + } + + gasFloorTarget () { + return this._transport + .execute('parity_gasFloorTarget') + .then(outNumber); + } + + gasPriceHistogram () { + return this._transport + .execute('parity_gasPriceHistogram') + .then(outHistogram); + } + + generateSecretPhrase () { + return this._transport + .execute('parity_generateSecretPhrase'); + } + + hashContent (url) { + return this._transport + .execute('parity_hashContent', url); + } + + listGethAccounts () { + return this._transport + .execute('parity_listGethAccounts') + .then((accounts) => (accounts || []).map(outAddress)); + } + + importGethAccounts (accounts) { + return this._transport + .execute('parity_importGethAccounts', (accounts || []).map(inAddress)) + .then((accounts) => (accounts || []).map(outAddress)); + } + + minGasPrice () { + return this._transport + .execute('parity_minGasPrice') + .then(outNumber); + } + + mode () { + return this._transport + .execute('parity_mode'); + } + + netChain () { + return this._transport + .execute('parity_netChain'); + } + + netPeers () { + return this._transport + .execute('parity_netPeers') + .then(outPeers); + } + + netMaxPeers () { + return this._transport + .execute('parity_netMaxPeers') + .then(outNumber); + } + + netPort () { + return this._transport + .execute('parity_netPort') + .then(outNumber); + } + + newAccountFromPhrase (phrase, password) { + return this._transport + .execute('parity_newAccountFromPhrase', phrase, password) + .then(outAddress); + } + + newAccountFromSecret (secret, password) { + return this._transport + .execute('parity_newAccountFromSecret', inHex(secret), password) + .then(outAddress); + } + + newAccountFromWallet (json, password) { + return this._transport + .execute('parity_newAccountFromWallet', json, password) + .then(outAddress); + } + + nodeName () { + return this._transport + .execute('parity_nodeName'); + } + + phraseToAddress (phrase) { + return this._transport + .execute('parity_phraseToAddress', phrase) + .then(outAddress); + } + + postTransaction (options) { + return this._transport + .execute('parity_postTransaction', inOptions(options)); + } + + registryAddress () { + return this._transport + .execute('parity_registryAddress') + .then(outAddress); + } + + removeReservedPeer (encode) { + return this._transport + .execute('parity_removeReservedPeer', encode); + } + + rpcSettings () { + return this._transport + .execute('parity_rpcSettings'); + } + + setAccountName (address, name) { + return this._transport + .execute('parity_setAccountName', inAddress(address), name); + } + + setAccountMeta (address, meta) { + return this._transport + .execute('parity_setAccountMeta', inAddress(address), JSON.stringify(meta)); + } + + setAuthor (address) { + return this._transport + .execute('parity_setAuthor', inAddress(address)); + } + + setExtraData (data) { + return this._transport + .execute('parity_setExtraData', inData(data)); + } + + setGasFloorTarget (quantity) { + return this._transport + .execute('parity_setGasFloorTarget', inNumber16(quantity)); + } + + setMinGasPrice (quantity) { + return this._transport + .execute('parity_setMinGasPrice', inNumber16(quantity)); + } + + setMode (mode) { + return this._transport + .execute('parity_setMode', mode); + } + + setTransactionsLimit (quantity) { + return this._transport + .execute('parity_setTransactionsLimit', inNumber16(quantity)); + } + + signerPort () { + return this._transport + .execute('parity_signerPort') + .then(outNumber); + } + + testPassword (account, password) { + return this._transport + .execute('parity_testPassword', inAddress(account), password); + } + + transactionsLimit () { + return this._transport + .execute('parity_transactionsLimit') + .then(outNumber); + } + + unsignedTransactionsCount () { + return this._transport + .execute('parity_unsignedTransactionsCount') + .then(outNumber); + } +} diff --git a/js/src/api/rpc/ethcore/ethcore.spec.js b/js/src/api/rpc/parity/parity.spec.js similarity index 66% rename from js/src/api/rpc/ethcore/ethcore.spec.js rename to js/src/api/rpc/parity/parity.spec.js index fd34550a7..ea0dd8d8c 100644 --- a/js/src/api/rpc/ethcore/ethcore.spec.js +++ b/js/src/api/rpc/parity/parity.spec.js @@ -18,14 +18,36 @@ import { TEST_HTTP_URL, mockHttp } from '../../../../test/mockRpc'; import { isBigNumber } from '../../../../test/types'; import Http from '../../transport/http'; -import Ethcore from './ethcore'; +import Parity from './parity'; -const instance = new Ethcore(new Http(TEST_HTTP_URL)); +const instance = new Parity(new Http(TEST_HTTP_URL)); + +describe('api/rpc/parity', () => { + describe('accountsInfo', () => { + it('retrieves the available account info', () => { + mockHttp([{ method: 'parity_accountsInfo', reply: { + result: { + '0x63cf90d3f0410092fc0fca41846f596223979195': { + name: 'name', uuid: 'uuid', meta: '{"data":"data"}' + } + } + } }]); + + return instance.accountsInfo().then((result) => { + expect(result).to.deep.equal({ + '0x63Cf90D3f0410092FC0fca41846f596223979195': { + name: 'name', uuid: 'uuid', meta: { + data: 'data' + } + } + }); + }); + }); + }); -describe('api/rpc/Ethcore', () => { describe('gasFloorTarget', () => { it('returns the gasfloor, formatted', () => { - mockHttp([{ method: 'ethcore_gasFloorTarget', reply: { result: '0x123456' } }]); + mockHttp([{ method: 'parity_gasFloorTarget', reply: { result: '0x123456' } }]); return instance.gasFloorTarget().then((count) => { expect(isBigNumber(count)).to.be.true; @@ -36,7 +58,7 @@ describe('api/rpc/Ethcore', () => { describe('minGasPrice', () => { it('returns the min gasprice, formatted', () => { - mockHttp([{ method: 'ethcore_minGasPrice', reply: { result: '0x123456' } }]); + mockHttp([{ method: 'parity_minGasPrice', reply: { result: '0x123456' } }]); return instance.minGasPrice().then((count) => { expect(isBigNumber(count)).to.be.true; @@ -47,7 +69,7 @@ describe('api/rpc/Ethcore', () => { describe('netMaxPeers', () => { it('returns the max peers, formatted', () => { - mockHttp([{ method: 'ethcore_netMaxPeers', reply: { result: 25 } }]); + mockHttp([{ method: 'parity_netMaxPeers', reply: { result: 25 } }]); return instance.netMaxPeers().then((count) => { expect(isBigNumber(count)).to.be.true; @@ -58,7 +80,7 @@ describe('api/rpc/Ethcore', () => { describe('newPeers', () => { it('returns the peer structure, formatted', () => { - mockHttp([{ method: 'ethcore_netPeers', reply: { result: { active: 123, connected: 456, max: 789 } } }]); + mockHttp([{ method: 'parity_netPeers', reply: { result: { active: 123, connected: 456, max: 789 } } }]); return instance.netPeers().then((peers) => { expect(peers.active.eq(123)).to.be.true; @@ -70,7 +92,7 @@ describe('api/rpc/Ethcore', () => { describe('netPort', () => { it('returns the connected port, formatted', () => { - mockHttp([{ method: 'ethcore_netPort', reply: { result: 33030 } }]); + mockHttp([{ method: 'parity_netPort', reply: { result: 33030 } }]); return instance.netPort().then((count) => { expect(isBigNumber(count)).to.be.true; @@ -81,7 +103,7 @@ describe('api/rpc/Ethcore', () => { describe('transactionsLimit', () => { it('returns the tx limit, formatted', () => { - mockHttp([{ method: 'ethcore_transactionsLimit', reply: { result: 1024 } }]); + mockHttp([{ method: 'parity_transactionsLimit', reply: { result: 1024 } }]); return instance.transactionsLimit().then((count) => { expect(isBigNumber(count)).to.be.true; diff --git a/js/src/api/rpc/personal/personal.js b/js/src/api/rpc/personal/personal.js index ca7dbce9b..db9a71d23 100644 --- a/js/src/api/rpc/personal/personal.js +++ b/js/src/api/rpc/personal/personal.js @@ -14,113 +14,31 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -import { inAddress, inHex, inNumber10, inNumber16, inOptions } from '../../format/input'; -import { outAccountInfo, outAddress, outSignerRequest } from '../../format/output'; +import { inAddress, inNumber10, inOptions } from '../../format/input'; +import { outAddress } from '../../format/output'; export default class Personal { constructor (transport) { this._transport = transport; } - accountsInfo () { - return this._transport - .execute('personal_accountsInfo') - .then(outAccountInfo); - } - - confirmRequest (requestId, options, password) { - return this._transport - .execute('personal_confirmRequest', inNumber16(requestId), options, password); - } - - changePassword (account, password, newPassword) { - return this._transport - .execute('personal_changePassword', inAddress(account), password, newPassword); - } - - generateAuthorizationToken () { - return this._transport - .execute('personal_generateAuthorizationToken'); - } - listAccounts () { return this._transport .execute('personal_listAccounts') .then((accounts) => (accounts || []).map(outAddress)); } - listGethAccounts () { - return this._transport - .execute('personal_listGethAccounts') - .then((accounts) => (accounts || []).map(outAddress)); - } - - importGethAccounts (accounts) { - return this._transport - .execute('personal_importGethAccounts', (accounts || []).map(inAddress)) - .then((accounts) => (accounts || []).map(outAddress)); - } - newAccount (password) { return this._transport .execute('personal_newAccount', password) .then(outAddress); } - newAccountFromPhrase (phrase, password) { - return this._transport - .execute('personal_newAccountFromPhrase', phrase, password) - .then(outAddress); - } - - newAccountFromSecret (secret, password) { - return this._transport - .execute('personal_newAccountFromSecret', inHex(secret), password) - .then(outAddress); - } - - newAccountFromWallet (json, password) { - return this._transport - .execute('personal_newAccountFromWallet', json, password) - .then(outAddress); - } - - rejectRequest (requestId) { - return this._transport - .execute('personal_rejectRequest', inNumber16(requestId)); - } - - requestsToConfirm () { - return this._transport - .execute('personal_requestsToConfirm') - .then((requests) => (requests || []).map(outSignerRequest)); - } - - setAccountName (address, name) { - return this._transport - .execute('personal_setAccountName', inAddress(address), name); - } - - setAccountMeta (address, meta) { - return this._transport - .execute('personal_setAccountMeta', inAddress(address), JSON.stringify(meta)); - } - signAndSendTransaction (options, password) { return this._transport .execute('personal_signAndSendTransaction', inOptions(options), password); } - signerEnabled () { - return this._transport - .execute('personal_signerEnabled'); - } - - testPassword (account, password) { - return this._transport - .execute('personal_testPassword', inAddress(account), password); - } - unlockAccount (account, password, duration = 1) { return this._transport .execute('personal_unlockAccount', inAddress(account), password, inNumber10(duration)); diff --git a/js/src/api/rpc/personal/personal.spec.js b/js/src/api/rpc/personal/personal.spec.js index 70734c7ee..a9bf4f644 100644 --- a/js/src/api/rpc/personal/personal.spec.js +++ b/js/src/api/rpc/personal/personal.spec.js @@ -26,28 +26,6 @@ describe('rpc/Personal', () => { const checksum = '0x63Cf90D3f0410092FC0fca41846f596223979195'; let scope; - describe('accountsInfo', () => { - it('retrieves the available account info', () => { - scope = mockHttp([{ method: 'personal_accountsInfo', reply: { - result: { - '0x63cf90d3f0410092fc0fca41846f596223979195': { - name: 'name', uuid: 'uuid', meta: '{"data":"data"}' - } - } - } }]); - - return instance.accountsInfo().then((result) => { - expect(result).to.deep.equal({ - '0x63Cf90D3f0410092FC0fca41846f596223979195': { - name: 'name', uuid: 'uuid', meta: { - data: 'data' - } - } - }); - }); - }); - }); - describe('listAccounts', () => { it('retrieves a list of available accounts', () => { scope = mockHttp([{ method: 'personal_listAccounts', reply: { result: [account] } }]); diff --git a/js/src/views/Dapps/hidden.js b/js/src/api/rpc/signer/index.js similarity index 58% rename from js/src/views/Dapps/hidden.js rename to js/src/api/rpc/signer/index.js index fa5458bac..6426bdc06 100644 --- a/js/src/views/Dapps/hidden.js +++ b/js/src/api/rpc/signer/index.js @@ -12,24 +12,6 @@ // 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 . +// along with Parity. If not, see . -const defaultHidden = []; - -export function readHiddenApps () { - const stored = localStorage.getItem('hiddenApps'); - - if (stored) { - try { - return JSON.parse(stored); - } catch (error) { - console.warn('readHiddenApps', error); - } - } - - return defaultHidden; -} - -export function writeHiddenApps (hidden) { - localStorage.setItem('hiddenApps', JSON.stringify(hidden)); -} +export default from './signer'; diff --git a/js/src/api/rpc/signer/signer.js b/js/src/api/rpc/signer/signer.js new file mode 100644 index 000000000..7f905cf50 --- /dev/null +++ b/js/src/api/rpc/signer/signer.js @@ -0,0 +1,50 @@ +// 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 { inNumber16 } from '../../format/input'; +import { outSignerRequest } from '../../format/output'; + +export default class Signer { + constructor (transport) { + this._transport = transport; + } + + confirmRequest (requestId, options, password) { + return this._transport + .execute('signer_confirmRequest', inNumber16(requestId), options, password); + } + + generateAuthorizationToken () { + return this._transport + .execute('signer_generateAuthorizationToken'); + } + + rejectRequest (requestId) { + return this._transport + .execute('signer_rejectRequest', inNumber16(requestId)); + } + + requestsToConfirm () { + return this._transport + .execute('signer_requestsToConfirm') + .then((requests) => (requests || []).map(outSignerRequest)); + } + + signerEnabled () { + return this._transport + .execute('signer_signerEnabled'); + } +} diff --git a/js/src/api/subscriptions/manager.js b/js/src/api/subscriptions/manager.js index 61e06499e..08f1a9e53 100644 --- a/js/src/api/subscriptions/manager.js +++ b/js/src/api/subscriptions/manager.js @@ -24,9 +24,9 @@ import Signer from './signer'; const events = { 'logging': { module: 'logging' }, 'eth_blockNumber': { module: 'eth' }, - 'personal_accountsInfo': { module: 'personal' }, - 'personal_listAccounts': { module: 'personal' }, - 'personal_requestsToConfirm': { module: 'signer' } + 'parity_accountsInfo': { module: 'personal' }, + 'eth_accounts': { module: 'personal' }, + 'signer_requestsToConfirm': { module: 'signer' } }; export default class Manager { diff --git a/js/src/api/subscriptions/personal.js b/js/src/api/subscriptions/personal.js index d65419962..58428895b 100644 --- a/js/src/api/subscriptions/personal.js +++ b/js/src/api/subscriptions/personal.js @@ -37,18 +37,18 @@ export default class Personal { } _listAccounts = () => { - return this._api.personal - .listAccounts() + return this._api.eth + .accounts() .then((accounts) => { - this._updateSubscriptions('personal_listAccounts', null, accounts); + this._updateSubscriptions('eth_accounts', null, accounts); }); } _accountsInfo = () => { - return this._api.personal + return this._api.parity .accountsInfo() .then((info) => { - this._updateSubscriptions('personal_accountsInfo', null, info); + this._updateSubscriptions('parity_accountsInfo', null, info); }); } @@ -59,16 +59,16 @@ export default class Personal { } switch (data.method) { - case 'personal_importGethAccounts': + case 'parity_importGethAccounts': case 'personal_newAccount': - case 'personal_newAccountFromPhrase': - case 'personal_newAccountFromWallet': + case 'parity_newAccountFromPhrase': + case 'parity_newAccountFromWallet': this._listAccounts(); this._accountsInfo(); return; - case 'personal_setAccountName': - case 'personal_setAccountMeta': + case 'parity_setAccountName': + case 'parity_setAccountMeta': this._accountsInfo(); return; } diff --git a/js/src/api/subscriptions/personal.spec.js b/js/src/api/subscriptions/personal.spec.js index 1a77b5f61..d6fd2b203 100644 --- a/js/src/api/subscriptions/personal.spec.js +++ b/js/src/api/subscriptions/personal.spec.js @@ -34,14 +34,15 @@ function stubApi (accounts, info) { return { _calls, - personal: { + parity: { accountsInfo: () => { const stub = sinon.stub().resolves(info || TEST_INFO)(); _calls.accountsInfo.push(stub); return stub; - }, - - listAccounts: () => { + } + }, + eth: { + accounts: () => { const stub = sinon.stub().resolves(accounts || TEST_LIST)(); _calls.listAccounts.push(stub); return stub; @@ -85,17 +86,17 @@ describe('api/subscriptions/personal', () => { expect(personal.isStarted).to.be.true; }); - it('calls personal_accountsInfo', () => { + it('calls parity_accountsInfo', () => { expect(api._calls.accountsInfo.length).to.be.ok; }); - it('calls personal_listAccounts', () => { + it('calls eth_accounts', () => { expect(api._calls.listAccounts.length).to.be.ok; }); it('updates subscribers', () => { - expect(cb.firstCall).to.have.been.calledWith('personal_listAccounts', null, TEST_LIST); - expect(cb.secondCall).to.have.been.calledWith('personal_accountsInfo', null, TEST_INFO); + expect(cb.firstCall).to.have.been.calledWith('eth_accounts', null, TEST_LIST); + expect(cb.secondCall).to.have.been.calledWith('parity_accountsInfo', null, TEST_INFO); }); }); diff --git a/js/src/api/subscriptions/signer.js b/js/src/api/subscriptions/signer.js index af745261b..4413fe432 100644 --- a/js/src/api/subscriptions/signer.js +++ b/js/src/api/subscriptions/signer.js @@ -49,10 +49,10 @@ export default class Signer { return; } - return this._api.personal + return this._api.signer .requestsToConfirm() .then((requests) => { - this._updateSubscriptions('personal_requestsToConfirm', null, requests); + this._updateSubscriptions('signer_requestsToConfirm', null, requests); nextTimeout(); }) .catch(nextTimeout); @@ -65,7 +65,7 @@ export default class Signer { } switch (data.method) { - case 'eth_postTransaction': + case 'parity_postTransaction': case 'eth_sendTranasction': case 'eth_sendRawTransaction': this._listRequests(false); diff --git a/js/src/api/transport/http/http.js b/js/src/api/transport/http/http.js index 65ba089cc..08d9422f8 100644 --- a/js/src/api/transport/http/http.js +++ b/js/src/api/transport/http/http.js @@ -56,6 +56,8 @@ export default class Http extends JsonRpcBase { if (response.status !== 200) { this._connected = false; this.error(JSON.stringify({ status: response.status, statusText: response.statusText })); + console.error(`${method}(${JSON.stringify(params)}): ${response.status}: ${response.statusText}`); + throw new Error(`${response.status}: ${response.statusText}`); } @@ -66,7 +68,9 @@ export default class Http extends JsonRpcBase { if (response.error) { this.error(JSON.stringify(response)); - throw new Error(`${response.error.code}: ${response.error.message}`); + console.error(`${method}(${JSON.stringify(params)}): ${response.error.code}: ${response.error.message}`); + + throw new Error(`${method}: ${response.error.code}: ${response.error.message}`); } this.log(JSON.stringify(response)); diff --git a/js/src/api/transport/ws/ws.js b/js/src/api/transport/ws/ws.js index 119f4ba76..d608426b0 100644 --- a/js/src/api/transport/ws/ws.js +++ b/js/src/api/transport/ws/ws.js @@ -107,7 +107,9 @@ export default class Ws extends JsonRpcBase { if (result.error) { this.error(event.data); - reject(new Error(`${result.error.code}: ${result.error.message}`)); + console.error(`${method}(${JSON.stringify(params)}): ${result.error.code}: ${result.error.message}`); + + reject(new Error(`${method}: ${result.error.code}: ${result.error.message}`)); delete this._messages[result.id]; return; } diff --git a/js/src/contracts/dappreg.js b/js/src/contracts/dappreg.js index 5272f6561..ae982af56 100644 --- a/js/src/contracts/dappreg.js +++ b/js/src/contracts/dappreg.js @@ -57,4 +57,8 @@ export default class DappReg { getContent (id) { return this.meta(id, 'CONTENT'); } + + getManifest (id) { + return this.meta(id, 'MANIFEST'); + } } diff --git a/js/src/contracts/registry.js b/js/src/contracts/registry.js index 85b9d6bb5..9853c0df9 100644 --- a/js/src/contracts/registry.js +++ b/js/src/contracts/registry.js @@ -32,7 +32,7 @@ export default class Registry { return; } - this._api.ethcore + this._api.parity .registryAddress() .then((address) => { this._instance = this._api.newContract(abis.registry, address).instance; diff --git a/js/src/dapps/basiccoin/Application/application.js b/js/src/dapps/basiccoin/Application/application.js index 4ab97ab6c..abe0c90c5 100644 --- a/js/src/dapps/basiccoin/Application/application.js +++ b/js/src/dapps/basiccoin/Application/application.js @@ -83,7 +83,7 @@ export default class Application extends Component { Promise .all([ attachInstances(), - api.personal.accountsInfo() + api.parity.accounts() ]) .then(([{ managerInstance, registryInstance, tokenregInstance }, accountsInfo]) => { accountsInfo = accountsInfo || {}; diff --git a/js/src/dapps/basiccoin/Deploy/Deployment/deployment.js b/js/src/dapps/basiccoin/Deploy/Deployment/deployment.js index f9232789b..0fa7dc863 100644 --- a/js/src/dapps/basiccoin/Deploy/Deployment/deployment.js +++ b/js/src/dapps/basiccoin/Deploy/Deployment/deployment.js @@ -296,7 +296,7 @@ export default class Deployment extends Component { .then((signerRequestId) => { this.setState({ signerRequestId, deployState: 'Transaction posted, Waiting for transaction authorization' }); - return api.pollMethod('eth_checkRequest', signerRequestId); + return api.pollMethod('parity_checkRequest', signerRequestId); }) .then((txHash) => { this.setState({ txHash, deployState: 'Transaction authorized, Waiting for network confirmations' }); diff --git a/js/src/dapps/basiccoin/Transfer/Send/send.js b/js/src/dapps/basiccoin/Transfer/Send/send.js index aee860fe2..a9c05a228 100644 --- a/js/src/dapps/basiccoin/Transfer/Send/send.js +++ b/js/src/dapps/basiccoin/Transfer/Send/send.js @@ -279,7 +279,7 @@ export default class Send extends Component { .then((signerRequestId) => { this.setState({ signerRequestId, sendState: 'Transaction posted, Waiting for transaction authorization' }); - return api.pollMethod('eth_checkRequest', signerRequestId); + return api.pollMethod('parity_checkRequest', signerRequestId); }) .then((txHash) => { this.setState({ txHash, sendState: 'Transaction authorized, Waiting for network confirmations' }); diff --git a/js/src/dapps/basiccoin/services.js b/js/src/dapps/basiccoin/services.js index 28cc662a7..4aed4199f 100644 --- a/js/src/dapps/basiccoin/services.js +++ b/js/src/dapps/basiccoin/services.js @@ -100,8 +100,8 @@ export function attachInstances () { return Promise .all([ - api.ethcore.registryAddress(), - api.ethcore.netChain() + api.parity.registryAddress(), + api.parity.netChain() ]) .then(([registryAddress, netChain]) => { const registry = api.newContract(abis.registry, registryAddress).instance; diff --git a/js/src/dapps/githubhint.html b/js/src/dapps/githubhint.html index 631182fcb..746c7f466 100644 --- a/js/src/dapps/githubhint.html +++ b/js/src/dapps/githubhint.html @@ -11,7 +11,6 @@
- diff --git a/js/src/dapps/githubhint/Application/application.css b/js/src/dapps/githubhint/Application/application.css index d149d883d..be04ecf34 100644 --- a/js/src/dapps/githubhint/Application/application.css +++ b/js/src/dapps/githubhint/Application/application.css @@ -82,6 +82,10 @@ .capture { } +.capture+.capture { + margin-top: 0.5em; +} + .capture * { display: inline-block; padding: 0.75em; @@ -124,3 +128,20 @@ .hashOk { opacity: 0.5; } + +.typeButtons { + text-align: center; + padding: 0 0 1em 0; +} + +.typeButtons>div { + border-radius: 0 !important; + + &:first-child { + border-radius: 5px 0 0 5px !important; + } + + &:last-child { + border-radius: 0 5px 5px 0 !important; + } +} diff --git a/js/src/dapps/githubhint/Application/application.js b/js/src/dapps/githubhint/Application/application.js index 3c4ecfda8..5a7494928 100644 --- a/js/src/dapps/githubhint/Application/application.js +++ b/js/src/dapps/githubhint/Application/application.js @@ -33,12 +33,17 @@ export default class Application extends Component { loading: true, url: '', urlError: null, + commit: '', + commitError: null, contentHash: '', contentHashError: null, contentHashOwner: null, registerBusy: false, registerError: null, - registerState: '' + registerState: '', + registerType: 'file', + repo: '', + repoError: null } componentDidMount () { @@ -65,7 +70,7 @@ export default class Application extends Component { } renderPage () { - const { fromAddress, registerBusy, url, urlError, contentHash, contentHashError, contentHashOwner } = this.state; + const { fromAddress, registerBusy, url, urlError, contentHash, contentHashError, contentHashOwner, commit, commitError, registerType, repo, repoError } = this.state; let hashClass = null; if (contentHashError) { @@ -74,22 +79,60 @@ export default class Application extends Component { hashClass = styles.hashOk; } + let valueInputs = null; + if (registerType === 'content') { + valueInputs = [ +
+ +
, +
+ +
+ ]; + } else { + valueInputs = ( +
+ +
+ ); + } + return (
+
+ + +
Provide a valid URL to register. The content information can be used in other contracts that allows for reverse lookups, e.g. image registries, dapp registries, etc.
-
- -
+ { valueInputs }
{ contentHashError || contentHash }
@@ -101,7 +144,7 @@ export default class Application extends Component { } renderButtons () { - const { accounts, fromAddress, url, urlError, contentHashError, contentHashOwner } = this.state; + const { accounts, fromAddress, urlError, repoError, commitError, contentHashError, contentHashOwner } = this.state; const account = accounts[fromAddress]; return ( @@ -114,7 +157,7 @@ export default class Application extends Component {
+ disabled={ (contentHashError && contentHashOwner !== fromAddress) || urlError || repoError || commitError }>register url
); } @@ -147,57 +190,107 @@ export default class Application extends Component { ); } - onClickContentHash = () => { - this.setState({ fileHash: false, commit: '' }); + onClickTypeNormal = () => { + const { url } = this.state; + + this.setState({ registerType: 'file', commitError: null, repoError: null }, () => { + this.onChangeUrl({ target: { value: url } }); + }); } - onClickFileHash = () => { - this.setState({ fileHash: true, commit: 0 }); + onClickTypeContent = () => { + const { repo, commit } = this.state; + + this.setState({ registerType: 'content', urlError: null }, () => { + this.onChangeRepo({ target: { value: repo } }); + this.onChangeCommit({ target: { value: commit } }); + }); + } + + onChangeCommit = (event) => { + let commit = event.target.value; + const commitError = null; + let hasContent = false; + + this.setState({ commit, commitError, contentHashError: null }, () => { + const { repo } = this.state || ''; + const parts = repo.split('/'); + + hasContent = commit.length !== 0 && parts.length === 2 && parts[0].length !== 0 && parts[1].length !== 0; + if (!commitError && hasContent) { + this.setState({ contentHashError: 'hash lookup in progress' }); + this.lookupHash(`https://codeload.github.com/${repo}/zip/${commit}`); + } + }); + } + + onChangeRepo = (event) => { + let repo = event.target.value; + const repoError = null; + let hasContent = false; + + // TODO: field validation + if (!repoError) { + repo = repo.replace('https://github.com/', ''); + } + + this.setState({ repo, repoError, contentHashError: null }, () => { + const { commit } = this.state || ''; + const parts = repo.split('/'); + + hasContent = commit.length !== 0 && parts.length === 2 && parts[0].length !== 0 && parts[1].length !== 0; + if (!repoError && hasContent) { + this.setState({ contentHashError: 'hash lookup in progress' }); + this.lookupHash(`https://codeload.github.com/${repo}/zip/${commit}`); + } + }); } onChangeUrl = (event) => { - const url = event.target.value; - let urlError = null; + let url = event.target.value; + const urlError = null; + let hasContent = false; - if (url && url.length) { - const re = /^https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}/g; // eslint-disable-line - urlError = re.test(url) - ? null - : 'not matching rexex'; + // TODO: field validation + if (!urlError) { + const parts = url.split('/'); + hasContent = parts.length !== 0; + + if (parts[2] === 'github.com' || parts[2] === 'raw.githubusercontent.com') { + url = `https://raw.githubusercontent.com/${parts.slice(3).join('/')}`.replace('/blob/', '/'); + } } - this.setState({ url, urlError, contentHashError: 'hash lookup in progress' }, () => { - this.lookupHash(); + this.setState({ url, urlError, contentHashError: null }, () => { + if (!urlError && hasContent) { + this.setState({ contentHashError: 'hash lookup in progress' }); + this.lookupHash(url); + } }); } onClickRegister = () => { - const { url, urlError, contentHash, contentHashError, contentHashOwner, fromAddress, instance } = this.state; + const { commit, commitError, contentHashError, contentHashOwner, fromAddress, url, urlError, registerType, repo, repoError } = this.state; - if ((!!contentHashError && contentHashOwner !== fromAddress) || !!urlError || url.length === 0) { + // TODO: No errors are currently set, validation to be expanded and added for each + // field (query is fast to pick up the issues, so not burning atm) + if ((contentHashError && contentHashOwner !== fromAddress) || repoError || urlError || commitError) { return; } - this.setState({ registerBusy: true, registerState: 'Estimating gas for the transaction' }); + if (registerType === 'file') { + this.registerUrl(url); + } else { + this.registerContent(repo, commit); + } + } - const values = [contentHash, url]; - const options = { from: fromAddress }; - - instance - .hintURL.estimateGas(options, values) - .then((gas) => { - this.setState({ registerState: 'Gas estimated, Posting transaction to the network' }); - - const gasPassed = gas.mul(1.2); - options.gas = gasPassed.toFixed(0); - console.log(`gas estimated at ${gas.toFormat(0)}, passing ${gasPassed.toFormat(0)}`); - - return instance.hintURL.postTransaction(options, values); - }) + trackRequest (promise) { + return promise .then((signerRequestId) => { this.setState({ signerRequestId, registerState: 'Transaction posted, Waiting for transaction authorization' }); - return api.pollMethod('eth_checkRequest', signerRequestId); + return api.pollMethod('parity_checkRequest', signerRequestId); }) .then((txHash) => { this.setState({ txHash, registerState: 'Transaction authorized, Waiting for network confirmations' }); @@ -211,7 +304,7 @@ export default class Application extends Component { }); }) .then((txReceipt) => { - this.setState({ txReceipt, registerBusy: false, registerState: 'Network confirmed, Received transaction receipt', url: '', contentHash: '' }); + this.setState({ txReceipt, registerBusy: false, registerState: 'Network confirmed, Received transaction receipt', url: '', commit: '', repo: '', commitError: null, contentHash: '', contentHashOwner: null, contentHashError: null }); }) .catch((error) => { console.error('onSend', error); @@ -219,6 +312,52 @@ export default class Application extends Component { }); } + registerContent (repo, commit) { + const { contentHash, fromAddress, instance } = this.state; + + this.setState({ registerBusy: true, registerState: 'Estimating gas for the transaction' }); + + const values = [contentHash, repo, commit.substr(0, 2) === '0x' ? commit : `0x${commit}`]; + const options = { from: fromAddress }; + + this.trackRequest( + instance + .hint.estimateGas(options, values) + .then((gas) => { + this.setState({ registerState: 'Gas estimated, Posting transaction to the network' }); + + const gasPassed = gas.mul(1.2); + options.gas = gasPassed.toFixed(0); + console.log(`gas estimated at ${gas.toFormat(0)}, passing ${gasPassed.toFormat(0)}`); + + return instance.hint.postTransaction(options, values); + }) + ); + } + + registerUrl (url) { + const { contentHash, fromAddress, instance } = this.state; + + this.setState({ registerBusy: true, registerState: 'Estimating gas for the transaction' }); + + const values = [contentHash, url]; + const options = { from: fromAddress }; + + this.trackRequest( + instance + .hintURL.estimateGas(options, values) + .then((gas) => { + this.setState({ registerState: 'Gas estimated, Posting transaction to the network' }); + + const gasPassed = gas.mul(1.2); + options.gas = gasPassed.toFixed(0); + console.log(`gas estimated at ${gas.toFormat(0)}, passing ${gasPassed.toFormat(0)}`); + + return instance.hintURL.postTransaction(options, values); + }) + ); + } + onSelectFromAddress = () => { const { accounts, fromAddress } = this.state; const addresses = Object.keys(accounts); @@ -238,10 +377,16 @@ export default class Application extends Component { this.setState({ fromAddress: addresses[index] }); } - lookupHash () { - const { url, instance } = this.state; + lookupHash (url) { + const { instance } = this.state; - api.ethcore + if (!url || !url.length) { + return; + } + + console.log(`lookupHash ${url}`); + + api.parity .hashContent(url) .then((contentHash) => { console.log('lookupHash', contentHash); diff --git a/js/src/dapps/githubhint/parity.js b/js/src/dapps/githubhint/parity.js index f6d59f44d..acee4dee0 100644 --- a/js/src/dapps/githubhint/parity.js +++ b/js/src/dapps/githubhint/parity.js @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -const { api } = window.parity; +const api = window.parent.secureApi; export { api diff --git a/js/src/dapps/githubhint/services.js b/js/src/dapps/githubhint/services.js index b7676d5f5..c9d260b73 100644 --- a/js/src/dapps/githubhint/services.js +++ b/js/src/dapps/githubhint/services.js @@ -18,7 +18,7 @@ import * as abis from '../../contracts/abi'; import { api } from './parity'; export function attachInterface () { - return api.ethcore + return api.parity .registryAddress() .then((registryAddress) => { console.log(`the registry was found at ${registryAddress}`); @@ -29,7 +29,7 @@ export function attachInterface () { .all([ registry.getAddress.call({}, [api.util.sha3('githubhint'), 'A']), api.eth.accounts(), - api.personal.accountsInfo() + api.parity.accounts() ]); }) .then(([address, addresses, accountsInfo]) => { diff --git a/js/src/dapps/registry/actions.js b/js/src/dapps/registry/actions.js index 882af0360..b1390926b 100644 --- a/js/src/dapps/registry/actions.js +++ b/js/src/dapps/registry/actions.js @@ -29,7 +29,7 @@ export { addresses, accounts, lookup, events, names, records }; export const setContract = (contract) => ({ type: 'set contract', contract }); export const fetchContract = () => (dispatch) => - api.ethcore.registryAddress() + api.parity.registryAddress() .then((address) => { const contract = api.newContract(registryAbi, address); dispatch(setContract(contract)); diff --git a/js/src/dapps/registry/addresses/actions.js b/js/src/dapps/registry/addresses/actions.js index 17975f9e6..2341d716c 100644 --- a/js/src/dapps/registry/addresses/actions.js +++ b/js/src/dapps/registry/addresses/actions.js @@ -22,7 +22,7 @@ export const fetch = () => (dispatch) => { return Promise .all([ api.eth.accounts(), - api.personal.accountsInfo() + api.parity.accounts() ]) .then(([ accounts, data ]) => { data = data || {}; diff --git a/js/src/dapps/signaturereg/services.js b/js/src/dapps/signaturereg/services.js index cab324f7e..54394c4b8 100644 --- a/js/src/dapps/signaturereg/services.js +++ b/js/src/dapps/signaturereg/services.js @@ -39,7 +39,7 @@ const logToEvent = (log) => { }; export function attachInterface (callback) { - return api.ethcore + return api.parity .registryAddress() .then((registryAddress) => { console.log(`the registry was found at ${registryAddress}`); @@ -50,7 +50,7 @@ export function attachInterface (callback) { .all([ registry.getAddress.call({}, [api.util.sha3('signaturereg'), 'A']), api.eth.accounts(), - api.personal.accountsInfo() + api.parity.accounts() ]); }) .then(([address, addresses, accountsInfo]) => { diff --git a/js/src/dapps/tokenreg/Accounts/actions.js b/js/src/dapps/tokenreg/Accounts/actions.js index f501399c2..58a74dfd8 100644 --- a/js/src/dapps/tokenreg/Accounts/actions.js +++ b/js/src/dapps/tokenreg/Accounts/actions.js @@ -38,7 +38,7 @@ export const loadAccounts = () => (dispatch) => { Promise .all([ api.eth.accounts(), - api.personal.accountsInfo() + api.parity.accounts() ]) .then(([ accounts, accountsInfo ]) => { accountsInfo = accountsInfo || {}; diff --git a/js/src/dapps/tokenreg/Actions/Register/register.js b/js/src/dapps/tokenreg/Actions/Register/register.js index 78d823326..5eb2d9e1b 100644 --- a/js/src/dapps/tokenreg/Actions/Register/register.js +++ b/js/src/dapps/tokenreg/Actions/Register/register.js @@ -80,7 +80,9 @@ export default class RegisterAction extends Component { modal={ sending || complete } className={ styles.dialog } onRequestClose={ this.onClose } - actions={ this.renderActions() } > + actions={ this.renderActions() } + autoScrollBodyContent + > { this.renderContent() } ); diff --git a/js/src/dapps/tokenreg/Status/actions.js b/js/src/dapps/tokenreg/Status/actions.js index b7de9c108..e9e217d6a 100644 --- a/js/src/dapps/tokenreg/Status/actions.js +++ b/js/src/dapps/tokenreg/Status/actions.js @@ -34,7 +34,7 @@ export const FIND_CONTRACT = 'FIND_CONTRACT'; export const loadContract = () => (dispatch) => { dispatch(setLoading(true)); - api.ethcore + api.parity .registryAddress() .then((registryAddress) => { console.log(`registry found at ${registryAddress}`); diff --git a/js/src/dev.parity.html b/js/src/dev.parity.html index 9cfe5ac18..504dfbb70 100644 --- a/js/src/dev.parity.html +++ b/js/src/dev.parity.html @@ -6,8 +6,31 @@ dev::Parity.js + + - +
+ best block #unknown +
+ diff --git a/js/src/dev.web3.html b/js/src/dev.web3.html index 93faba8e5..f4006160a 100644 --- a/js/src/dev.web3.html +++ b/js/src/dev.web3.html @@ -6,8 +6,33 @@ dev::Web3 + + - +
+ best block #unknown +
+ diff --git a/js/src/index.js b/js/src/index.js index 2321b5cf6..966e2708e 100644 --- a/js/src/index.js +++ b/js/src/index.js @@ -31,7 +31,7 @@ import ContractInstances from './contracts'; import { initStore } from './redux'; import { ContextProvider, muiTheme } from './ui'; -import { Accounts, Account, Addresses, Address, Application, Contract, Contracts, Dapp, Dapps, Settings, SettingsBackground, SettingsProxy, SettingsViews, Signer, Status } from './views'; +import { Accounts, Account, Addresses, Address, Application, Contract, Contracts, Dapp, Dapps, Settings, SettingsBackground, SettingsParity, SettingsProxy, SettingsViews, Signer, Status } from './views'; import { setApi } from './redux/providers/apiActions'; @@ -59,6 +59,8 @@ const store = initStore(api); store.dispatch({ type: 'initAll', api }); store.dispatch(setApi(api)); +window.secureApi = api; + const routerHistory = useRouterHistory(createHashHistory)({}); ReactDOM.render( @@ -72,13 +74,14 @@ ReactDOM.render( - + + diff --git a/js/src/jsonrpc/index.js b/js/src/jsonrpc/index.js index 18bd4302d..9e9692279 100644 --- a/js/src/jsonrpc/index.js +++ b/js/src/jsonrpc/index.js @@ -16,20 +16,22 @@ import db from './interfaces/db'; import eth from './interfaces/eth'; -import ethcore from './interfaces/ethcore'; import net from './interfaces/net'; +import parity from './interfaces/parity'; import personal from './interfaces/personal'; import shh from './interfaces/shh'; +import signer from './interfaces/signer'; import trace from './interfaces/trace'; import web3 from './interfaces/web3'; export default { - db: db, - eth: eth, - ethcore: ethcore, - net: net, - personal: personal, - shh: shh, - trace: trace, - web3: web3 + db, + eth, + parity, + net, + personal, + shh, + signer, + trace, + web3 }; diff --git a/js/src/jsonrpc/interfaces/eth.js b/js/src/jsonrpc/interfaces/eth.js index f1c8fb86f..d5ff471fb 100644 --- a/js/src/jsonrpc/interfaces/eth.js +++ b/js/src/jsonrpc/interfaces/eth.js @@ -86,20 +86,6 @@ export default { } }, - checkRequest: { - desc: 'Returns the transactionhash of the requestId (received from eth_postTransaction) if the request was confirmed', - params: [ - { - type: Quantity, - desc: 'The requestId to check for' - } - ], - returns: { - type: Hash, - desc: '32 Bytes - the transaction hash, or the zero hash if the transaction is not yet available' - } - }, - coinbase: { desc: 'Returns the client coinbase address.', params: [], @@ -823,22 +809,6 @@ export default { } }, - postTransaction: { - desc: 'Posts a transaction to the Signer.', - params: [ - { - type: Object, - desc: 'see [eth_sendTransaction](#eth_sendTransaction)', - format: 'inputCallFormatter' - } - ], - returns: { - type: Quantity, - desc: 'The id of the actual transaction', - format: 'utils.toDecimal' - } - }, - protocolVersion: { desc: 'Returns the current ethereum protocol version.', params: [], diff --git a/js/src/jsonrpc/interfaces/ethcore.js b/js/src/jsonrpc/interfaces/parity.js similarity index 64% rename from js/src/jsonrpc/interfaces/ethcore.js rename to js/src/jsonrpc/interfaces/parity.js index c81a82f76..66a8ea962 100644 --- a/js/src/jsonrpc/interfaces/ethcore.js +++ b/js/src/jsonrpc/interfaces/parity.js @@ -26,6 +26,52 @@ export default { } }, + accounts: { + desc: 'returns a map of accounts as an object', + params: [], + returns: { + type: Array, + desc: 'Account metadata', + details: { + name: { + type: String, + desc: 'Account name' + }, + meta: { + type: String, + desc: 'Encoded JSON string the defines additional account metadata' + }, + uuid: { + type: String, + desc: 'The account UUID, or null if not available/unknown/not applicable.' + } + } + } + }, + + accountsInfo: { + desc: 'returns a map of accounts as an object', + params: [], + returns: { + type: Array, + desc: 'Account metadata', + details: { + name: { + type: String, + desc: 'Account name' + }, + meta: { + type: String, + desc: 'Encoded JSON string the defines additional account metadata' + }, + uuid: { + type: String, + desc: 'The account UUID, or null if not available/unknown/not applicable.' + } + } + } + }, + addReservedPeer: { desc: '?', params: [ @@ -40,6 +86,20 @@ export default { } }, + checkRequest: { + desc: 'Returns the transactionhash of the requestId (received from parity_postTransaction) if the request was confirmed', + params: [ + { + type: Quantity, + desc: 'The requestId to check for' + } + ], + returns: { + type: Hash, + desc: '32 Bytes - the transaction hash, or the zero hash if the transaction is not yet available' + } + }, + dappsPort: { desc: 'Returns the port the dapps are running on, error if not enabled', params: [], @@ -85,6 +145,15 @@ export default { } }, + enode: { + desc: 'Returns the node enode URI', + params: [], + returns: { + type: String, + desc: 'Enode URI' + } + }, + extraData: { desc: 'Returns currently set extra data', params: [], @@ -146,6 +215,29 @@ export default { } }, + listGethAccounts: { + desc: 'Returns a list of the accounts available from Geth', + params: [], + returns: { + type: Array, + desc: '20 Bytes addresses owned by the client.' + } + }, + + importGethAccounts: { + desc: 'Imports a list of accounts from geth', + params: [ + { + type: Array, + desc: 'List of the geth addresses to import' + } + ], + returns: { + type: Array, + desc: 'Array of the imported addresses' + } + }, + minGasPrice: { desc: 'Returns currently set minimal gas price', params: [], @@ -157,7 +249,7 @@ export default { }, mode: { - desc: 'Get the mode. Results one of: "active", "passive", "dark", "off".', + desc: 'Get the mode. Results one of: "active", "passive", "dark", "offline".', params: [], returns: { type: String, @@ -201,6 +293,60 @@ export default { } }, + newAccountFromPhrase: { + desc: 'Creates a new account from a recovery passphrase', + params: [ + { + type: String, + desc: 'Phrase' + }, + { + type: String, + desc: 'Password' + } + ], + returns: { + type: Address, + desc: 'The created address' + } + }, + + newAccountFromSecret: { + desc: 'Creates a new account from a private ethstore secret key', + params: [ + { + type: Data, + desc: 'Secret, 32-byte hex' + }, + { + type: String, + desc: 'Password' + } + ], + returns: { + type: Address, + desc: 'The created address' + } + }, + + newAccountFromWallet: { + desc: 'Creates a new account from a JSON import', + params: [ + { + type: String, + desc: 'JSON' + }, + { + type: String, + desc: 'Password' + } + ], + returns: { + type: Address, + desc: 'The created address' + } + }, + nodeName: { desc: 'Returns node name (identity)', params: [], @@ -224,6 +370,22 @@ export default { } }, + postTransaction: { + desc: 'Posts a transaction to the Signer.', + params: [ + { + type: Object, + desc: 'see [eth_sendTransaction](#eth_sendTransaction)', + format: 'inputCallFormatter' + } + ], + returns: { + type: Quantity, + desc: 'The id of the actual transaction', + format: 'utils.toDecimal' + } + }, + removeReservedPeer: { desc: '?', params: [ @@ -256,6 +418,42 @@ export default { } }, + setAccountName: { + desc: 'Sets a name for the account', + params: [ + { + type: Address, + desc: 'Address' + }, + { + type: String, + desc: 'Name' + } + ], + returns: { + type: Object, + desc: 'Returns null in all cases' + } + }, + + setAccountMeta: { + desc: 'Sets metadata for the account', + params: [ + { + type: Address, + desc: 'Address' + }, + { + type: String, + desc: 'Metadata (JSON encoded)' + } + ], + returns: { + type: Object, + desc: 'Returns null in all cases' + } + }, + setAuthor: { desc: 'Changes author (coinbase) for mined blocks.', params: [ @@ -321,7 +519,7 @@ export default { params: [ { type: String, - desc: 'The mode to set, one of "active", "passive", "dark", "off"' + desc: 'The mode to set, one of "active", "passive", "dark", "offline"' } ], returns: { diff --git a/js/src/jsonrpc/interfaces/personal.js b/js/src/jsonrpc/interfaces/personal.js index 2a9ce7c19..eb7e5fc0f 100644 --- a/js/src/jsonrpc/interfaces/personal.js +++ b/js/src/jsonrpc/interfaces/personal.js @@ -17,83 +17,6 @@ import { Address, Data, Quantity } from '../types'; export default { - accountsInfo: { - desc: 'returns a map of accounts as an object', - params: [], - returns: { - type: Array, - desc: 'Account metadata', - details: { - name: { - type: String, - desc: 'Account name' - }, - meta: { - type: String, - desc: 'Encoded JSON string the defines additional account metadata' - }, - uuid: { - type: String, - desc: 'The account UUID, or null if not available/unknown/not applicable.' - } - } - } - }, - - generateAuthorizationToken: { - desc: 'Generates a new authorization token', - params: [], - returns: { - type: String, - desc: 'The new authorization token' - } - }, - - requestsToConfirm: { - desc: 'Returns a list of the transactions requiring authorization', - params: [], - returns: { - type: Array, - desc: 'A list of the outstanding transactions' - } - }, - - confirmRequest: { - desc: 'Confirm a request in the signer queue', - params: [ - { - type: Quantity, - desc: 'The request id' - }, - { - type: Object, - desc: 'The request options' - }, - { - type: String, - desc: 'The account password' - } - ], - returns: { - type: Boolean, - desc: 'The status of the confirmation' - } - }, - - rejectRequest: { - desc: 'Rejects a request in the signer queue', - params: [ - { - type: Quantity, - desc: 'The request id' - } - ], - returns: { - type: Boolean, - desc: 'The status of the rejection' - } - }, - listAccounts: { desc: 'Returns a list of addresses owned by client.', params: [], @@ -103,29 +26,6 @@ export default { } }, - listGethAccounts: { - desc: 'Returns a list of the accounts available from Geth', - params: [], - returns: { - type: Array, - desc: '20 Bytes addresses owned by the client.' - } - }, - - importGethAccounts: { - desc: 'Imports a list of accounts from geth', - params: [ - { - type: Array, - desc: 'List of the geth addresses to import' - } - ], - returns: { - type: Array, - desc: 'Array of the imported addresses' - } - }, - newAccount: { desc: 'Creates new account', params: [ @@ -140,96 +40,6 @@ export default { } }, - newAccountFromPhrase: { - desc: 'Creates a new account from a recovery passphrase', - params: [ - { - type: String, - desc: 'Phrase' - }, - { - type: String, - desc: 'Password' - } - ], - returns: { - type: Address, - desc: 'The created address' - } - }, - - newAccountFromSecret: { - desc: 'Creates a new account from a private ethstore secret key', - params: [ - { - type: Data, - desc: 'Secret, 32-byte hex' - }, - { - type: String, - desc: 'Password' - } - ], - returns: { - type: Address, - desc: 'The created address' - } - }, - - newAccountFromWallet: { - desc: 'Creates a new account from a JSON import', - params: [ - { - type: String, - desc: 'JSON' - }, - { - type: String, - desc: 'Password' - } - ], - returns: { - type: Address, - desc: 'The created address' - } - }, - - setAccountName: { - desc: 'Sets a name for the account', - params: [ - { - type: Address, - desc: 'Address' - }, - { - type: String, - desc: 'Name' - } - ], - returns: { - type: Object, - desc: 'Returns null in all cases' - } - }, - - setAccountMeta: { - desc: 'Sets metadata for the account', - params: [ - { - type: Address, - desc: 'Address' - }, - { - type: String, - desc: 'Metadata (JSON encoded)' - } - ], - returns: { - type: Object, - desc: 'Returns null in all cases' - } - }, - signAndSendTransaction: { desc: 'Sends and signs a transaction given account passphrase. Does not require the account to be unlocked nor unlocks the account for future transactions. ', params: [ @@ -284,15 +94,6 @@ export default { } }, - signerEnabled: { - desc: 'Returns whether signer is enabled/disabled.', - params: [], - returns: { - type: Boolean, - desc: 'true when enabled, false when disabled' - } - }, - unlockAccount: { desc: '?', params: [ diff --git a/js/src/jsonrpc/interfaces/signer.js b/js/src/jsonrpc/interfaces/signer.js new file mode 100644 index 000000000..f394dbb61 --- /dev/null +++ b/js/src/jsonrpc/interfaces/signer.js @@ -0,0 +1,82 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import { Quantity } from '../types'; + +export default { + generateAuthorizationToken: { + desc: 'Generates a new authorization token', + params: [], + returns: { + type: String, + desc: 'The new authorization token' + } + }, + + requestsToConfirm: { + desc: 'Returns a list of the transactions requiring authorization', + params: [], + returns: { + type: Array, + desc: 'A list of the outstanding transactions' + } + }, + + confirmRequest: { + desc: 'Confirm a request in the signer queue', + params: [ + { + type: Quantity, + desc: 'The request id' + }, + { + type: Object, + desc: 'The request options' + }, + { + type: String, + desc: 'The account password' + } + ], + returns: { + type: Boolean, + desc: 'The status of the confirmation' + } + }, + + rejectRequest: { + desc: 'Rejects a request in the signer queue', + params: [ + { + type: Quantity, + desc: 'The request id' + } + ], + returns: { + type: Boolean, + desc: 'The status of the rejection' + } + }, + + signerEnabled: { + desc: 'Returns whether signer is enabled/disabled.', + params: [], + returns: { + type: Boolean, + desc: 'true when enabled, false when disabled' + } + } +}; diff --git a/js/src/modals/AddAddress/addAddress.js b/js/src/modals/AddAddress/addAddress.js index 5ab8bbe80..c8845aa13 100644 --- a/js/src/modals/AddAddress/addAddress.js +++ b/js/src/modals/AddAddress/addAddress.js @@ -133,9 +133,10 @@ export default class AddAddress extends Component { const { address, name, description } = this.state; Promise.all([ - api.personal.setAccountName(address, name), - api.personal.setAccountMeta(address, { + api.parity.setAccountName(address, name), + api.parity.setAccountMeta(address, { description, + timestamp: Date.now(), deleted: false }) ]).catch((error) => { diff --git a/js/src/modals/AddContract/addContract.js b/js/src/modals/AddContract/addContract.js index ebad86807..418378136 100644 --- a/js/src/modals/AddContract/addContract.js +++ b/js/src/modals/AddContract/addContract.js @@ -141,10 +141,11 @@ export default class AddContract extends Component { const { abiParsed, address, name, description } = this.state; Promise.all([ - api.personal.setAccountName(address, name), - api.personal.setAccountMeta(address, { + api.parity.setAccountName(address, name), + api.parity.setAccountMeta(address, { contract: true, deleted: false, + timestamp: Date.now(), abi: abiParsed, description }) diff --git a/js/src/modals/CreateAccount/AccountDetails/accountDetails.js b/js/src/modals/CreateAccount/AccountDetails/accountDetails.js index 079d3cac9..646c7c180 100644 --- a/js/src/modals/CreateAccount/AccountDetails/accountDetails.js +++ b/js/src/modals/CreateAccount/AccountDetails/accountDetails.js @@ -31,7 +31,8 @@ export default class AccountDetails extends Component { return (
@@ -54,7 +55,8 @@ export default class AccountDetails extends Component { return ( diff --git a/js/src/modals/CreateAccount/NewAccount/newAccount.js b/js/src/modals/CreateAccount/NewAccount/newAccount.js index 323152213..8c476634f 100644 --- a/js/src/modals/CreateAccount/NewAccount/newAccount.js +++ b/js/src/modals/CreateAccount/NewAccount/newAccount.js @@ -27,7 +27,7 @@ const ERRORS = { noName: 'you need to specify a valid name for the account', noPhrase: 'you need to specify the recovery phrase', noKey: 'you need to provide the raw private key', - invalidKey: 'the raw key needs to be hex, 64 characters in length', + invalidKey: 'the raw key needs to be hex, 64 characters in length and contain the prefix "0x"', invalidPassword: 'you need to specify a password >= 8 characters', noMatchPassword: 'the supplied passwords does not match' }; @@ -84,7 +84,6 @@ export default class CreateAccount extends Component {
{ return Promise - .all(phrases.map((phrase) => api.ethcore.phraseToAddress(phrase))) + .all(phrases.map((phrase) => api.parity.phraseToAddress(phrase))) .then((addresses) => { const accounts = {}; diff --git a/js/src/modals/CreateAccount/NewGeth/newGeth.js b/js/src/modals/CreateAccount/NewGeth/newGeth.js index 8853a671b..4b6cc2c96 100644 --- a/js/src/modals/CreateAccount/NewGeth/newGeth.js +++ b/js/src/modals/CreateAccount/NewGeth/newGeth.js @@ -102,7 +102,7 @@ export default class NewGeth extends Component { const { api } = this.context; const { accounts } = this.props; - api.personal + api.parity .listGethAccounts() .then((_addresses) => { const addresses = (addresses || []).filter((address) => !accounts[address]); diff --git a/js/src/modals/CreateAccount/NewImport/newImport.js b/js/src/modals/CreateAccount/NewImport/newImport.js index 793a8ab1b..60c80fd00 100644 --- a/js/src/modals/CreateAccount/NewImport/newImport.js +++ b/js/src/modals/CreateAccount/NewImport/newImport.js @@ -72,7 +72,6 @@ export default class NewImport extends Component {
{ this.setState({ address }); - return api.personal + return api.parity .setAccountName(address, this.state.name) - .then(() => api.personal.setAccountMeta(address, { passwordHint: this.state.passwordHint })); + .then(() => api.parity.setAccountMeta(address, { + timestamp: Date.now(), + passwordHint: this.state.passwordHint + })); }) .then(() => { this.onNext(); @@ -230,13 +233,16 @@ export default class CreateAccount extends Component { this.newError(error); }); } else if (createType === 'fromRaw') { - return api.personal + return api.parity .newAccountFromSecret(this.state.rawKey, this.state.password) .then((address) => { this.setState({ address }); - return api.personal + return api.parity .setAccountName(address, this.state.name) - .then(() => api.personal.setAccountMeta(address, { passwordHint: this.state.passwordHint })); + .then(() => api.parity.setAccountMeta(address, { + timestamp: Date.now(), + passwordHint: this.state.passwordHint + })); }) .then(() => { this.onNext(); @@ -252,13 +258,13 @@ export default class CreateAccount extends Component { this.newError(error); }); } else if (createType === 'fromGeth') { - return api.personal + return api.parity .importGethAccounts(this.state.gethAddresses) .then((result) => { console.log('result', result); return Promise.all(this.state.gethAddresses.map((address) => { - return api.personal.setAccountName(address, 'Geth Import'); + return api.parity.setAccountName(address, 'Geth Import'); })); }) .then(() => { @@ -276,16 +282,19 @@ export default class CreateAccount extends Component { }); } - return api.personal + return api.parity .newAccountFromWallet(this.state.json, this.state.password) .then((address) => { this.setState({ address: address }); - return api.personal + return api.parity .setAccountName(address, this.state.name) - .then(() => api.personal.setAccountMeta(address, { passwordHint: this.state.passwordHint })); + .then(() => api.parity.setAccountMeta(address, { + timestamp: Date.now(), + passwordHint: this.state.passwordHint + })); }) .then(() => { this.onNext(); diff --git a/js/src/modals/DeployContract/DetailsStep/detailsStep.js b/js/src/modals/DeployContract/DetailsStep/detailsStep.js index 1eebe4304..e0f02bc70 100644 --- a/js/src/modals/DeployContract/DetailsStep/detailsStep.js +++ b/js/src/modals/DeployContract/DetailsStep/detailsStep.js @@ -15,8 +15,9 @@ // along with Parity. If not, see . import React, { Component, PropTypes } from 'react'; +import { MenuItem } from 'material-ui'; -import { AddressSelect, Form, Input, InputAddressSelect } from '../../../ui'; +import { AddressSelect, Form, Input, InputAddressSelect, Select } from '../../../ui'; import { validateAbi } from '../../../util/validation'; import styles from '../deployContract.css'; @@ -98,6 +99,7 @@ export default class DetailsStep extends Component { return inputs.map((input, index) => { const onChange = (event, value) => this.onParamChange(index, value); + const onChangeBool = (event, _index, value) => this.onParamChange(index, value === 'true'); const onSubmit = (value) => this.onParamChange(index, value); const label = `${input.name}: ${input.type}`; let inputBox = null; @@ -115,6 +117,26 @@ export default class DetailsStep extends Component { ); break; + case 'bool': + const boolitems = ['false', 'true'].map((bool) => { + return ( + { bool } + ); + }); + inputBox = ( + + ); + break; + default: inputBox = ( { switch (input.type) { + case 'address': + params.push('0x'); + break; + + case 'bool': + params.push(false); + break; + + case 'bytes': + params.push('0x'); + break; + + case 'uint': + params.push('0'); + break; + case 'string': params.push(''); break; default: - params.push('0x'); + params.push('0'); break; } }); diff --git a/js/src/modals/DeployContract/deployContract.js b/js/src/modals/DeployContract/deployContract.js index 3e1b10599..588d16f6a 100644 --- a/js/src/modals/DeployContract/deployContract.js +++ b/js/src/modals/DeployContract/deployContract.js @@ -18,7 +18,7 @@ import React, { Component, PropTypes } from 'react'; import ActionDoneAll from 'material-ui/svg-icons/action/done-all'; import ContentClear from 'material-ui/svg-icons/content/clear'; -import { BusyStep, CompletedStep, Button, IdentityIcon, Modal, TxHash } from '../../ui'; +import { BusyStep, CompletedStep, CopyToClipboard, Button, IdentityIcon, Modal, TxHash } from '../../ui'; import { ERRORS, validateAbi, validateCode, validateName } from '../../util/validation'; import DetailsStep from './DetailsStep'; @@ -155,6 +155,7 @@ export default class DeployContract extends Component {
Your contract has been deployed at
+
{ address }
@@ -212,10 +213,11 @@ export default class DeployContract extends Component { .deploy(options, params, this.onDeploymentState) .then((address) => { return Promise.all([ - api.personal.setAccountName(address, name), - api.personal.setAccountMeta(address, { + api.parity.setAccountName(address, name), + api.parity.setAccountMeta(address, { abi: abiParsed, contract: true, + timestamp: Date.now(), deleted: false, description }) diff --git a/js/src/modals/EditMeta/editMeta.js b/js/src/modals/EditMeta/editMeta.js index b2ba89d61..7f0a061e2 100644 --- a/js/src/modals/EditMeta/editMeta.js +++ b/js/src/modals/EditMeta/editMeta.js @@ -99,11 +99,10 @@ export default class EditMeta extends Component { renderTags () { const { meta } = this.state; - const { tags } = meta || []; return ( this.props.onClose()) .catch((error) => { diff --git a/js/src/modals/ExecuteContract/executeContract.js b/js/src/modals/ExecuteContract/executeContract.js index 67f350feb..b45cf6875 100644 --- a/js/src/modals/ExecuteContract/executeContract.js +++ b/js/src/modals/ExecuteContract/executeContract.js @@ -19,7 +19,7 @@ import ActionDoneAll from 'material-ui/svg-icons/action/done-all'; import ContentClear from 'material-ui/svg-icons/content/clear'; import { BusyStep, CompletedStep, Button, IdentityIcon, Modal, TxHash } from '../../ui'; -import { validateAddress } from '../../util/validation'; +import { validateAddress, validateUint } from '../../util/validation'; import DetailsStep from './DetailsStep'; @@ -41,6 +41,7 @@ export default class ExecuteContract extends Component { state = { amount: '0', amountError: null, + fromAddressError: null, func: null, funcError: null, values: [], @@ -77,7 +78,8 @@ export default class ExecuteContract extends Component { renderDialogActions () { const { onClose, fromAddress } = this.props; - const { sending, step } = this.state; + const { sending, step, fromAddressError, valuesError } = this.state; + const hasError = fromAddressError || valuesError.find((error) => error); const cancelBtn = (